开发者

Set a default value in combobox programmatically

I am working on WPF. I am using visual studio 2010, .NET 4.0 and using a Radcombobox in my application. It is getting populated co开发者_开发技巧rrectly with 3 strings in it and now I am having trouble choosing a default value. I want to select the first index value as the default value when it starts up loading the 3 strings in the combo box drop down. How do i do this programmatically? Should this be done in xaml or in C#?


Use a counter. Create a boolean variable and call it boolDefaultSet. It should initialize with a default value of false.

Presumably you would use a loop to output the option boxes for your select box... inside that loop write some logic to check whether boolDefaultSet is true. If not, then print the option box with an attribute of 'selected', then set boolDefaultSet equal to true. Here is some vb code that you could implement in C#:

Dim boolDefaultSet as boolean
for i as integer = 0 to 2
    if boolDefaultSet then
        Response.Write("<option value="+myval+">"+myval+"</option>")
    else
        Response.Write("<option value="+myval+" selected>"+myval+"</option>")
        boolDefaultSet=true
next i


If setting SelectedIndex from XAML was not working I would try to do it in C# code load event.

myName.SelectedIndex = 0;


You shouldn't use SelectedValue AND SelectedIndex at the same time since it often creates a sort of conflict. I suggest you remove SelectedIndex="0" from the xaml and set the property to which you bind your SelectedValue from the code.

example:

MySelectedValue = MyItemsSource[0];


This is more of an MVVM answer:

Bind the SelectedIndex property in XAML to a property on your ViewModel.

SelectedIndex="{Binding Path=SelectedIndex, Mode=TwoWay}"

In your ViewModel, set the SelectedIndex value to 1 and then call PropertyChangeNotification so the view knows to update (this assumes your ViewModel implements INotifyPropertyChanged, and most VM implementations use a base class to do this).

SelectedIndex = 1;
NotifyPropertyChanged("SelectedIndex");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜