简体   繁体   English

以编程方式在组合框中设置默认值

[英]Set a default value in combobox programmatically

I am working on WPF. 我正在WPF上工作。 I am using visual studio 2010, .NET 4.0 and using a Radcombobox in my application. 我正在使用Visual Studio 2010,.NET 4.0,并在我的应用程序中使用Radcombobox。 It is getting populated correctly with 3 strings in it and now I am having trouble choosing a default value. 它正确填充了3个字符串,现在我很难选择默认值。 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. 我想在启动加载组合框中的3个字符串下拉列表时选择第一个索引值作为默认值。 How do i do this programmatically? 如何以编程方式执行此操作? Should this be done in xaml or in C#? 应该用xaml还是C#完成?

Use a counter. 使用计数器。 Create a boolean variable and call it boolDefaultSet. 创建一个布尔变量,并将其命名为boolDefaultSet。 It should initialize with a default value of false. 它应该使用默认值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. 大概您将使用循环来输出选择框的选项框...在该循环内编写一些逻辑以检查boolDefaultSet是否为true。 If not, then print the option box with an attribute of 'selected', then set boolDefaultSet equal to true. 如果不是,则打印属性为“ selected”的选项框,然后将boolDefaultSet设置为true。 Here is some vb code that you could implement in C#: 这是一些您可以在C#中实现的vb代码:

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. 如果从XAML设置SelectedIndex无效,我将尝试在C#代码加载事件中进行操作。

myName.SelectedIndex = 0; myName.SelectedIndex = 0;

You shouldn't use SelectedValue AND SelectedIndex at the same time since it often creates a sort of conflict. 您不应该同时使用SelectedValue和SelectedIndex,因为它经常会产生某种冲突。 I suggest you remove SelectedIndex="0" from the xaml and set the property to which you bind your SelectedValue from the code. 我建议您从xaml中删除SelectedIndex =“ 0”并设置将代码中的SelectedValue绑定到的属性。

example: 例:

MySelectedValue = MyItemsSource[0];

This is more of an MVVM answer: 这更多是MVVM的答案:

Bind the SelectedIndex property in XAML to a property on your ViewModel. 将XAML中的SelectedIndex属性绑定到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). 在您的ViewModel中,将SelectedIndex值设置为1,然后调用PropertyChangeNotification,以便该视图知道要更新(这假定您的ViewModel实现了INotifyPropertyChanged,并且大多数VM实现都使用基类来执行此操作)。

SelectedIndex = 1;
NotifyPropertyChanged("SelectedIndex");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM