根据内容将ComBox设置为ComboBoxItem

时间:2015-05-08 00:41:39

标签: c# wpf combobox

我有一个带有在xaml中硬编码的组合框的组合框,我试图根据字符串值以编程方式设置组合框的值。

XAML:

<ComboBox  Name="comboCondition">
    <ComboBoxItem>Item 1</ComboBoxItem>
    <ComboBoxItem>Item 2</ComboBoxItem
</ComboBox>

不使用ComboBoxItems时通常会使用的代码:

comboConditionValue.SelectedItem = "Item 1";

当组合框包含ComboBoxItem而不是绑定到List时,这当然不起作用。我能够找到这样的正确值:

foreach (var item in comboCondition.Items)
{
     if ((item as ComboBoxItem).Content.ToString() == "Item 1")
         comboCondition.SelectedItem = item;
}

这是一种设置值的混乱和缓慢的方式,有没有人知道我可以设置正确的ComboBoxItem而不循环完整列表的任何更简单的方法?

1 个答案:

答案 0 :(得分:1)

您使用视图模型并以这种方式绑定您的组合框(首选方式)

在您的视图代码中:

public myView()
{
this.DataContext = new myViewModel();
}

然后在myViewModel类中,您拥有所选项目的属性:

private string _selectedItem;
public string SelectedItem
{
    get { return _selectedItem; }
    set
    {
        _selectedItem = value;
        PropertyChangedEvent.Notify(this,"SelectedItem");
    }            
}

然后,在你的view.xaml中,你绑定到你的组合框:

<ComboBox  Name="comboCondition" SelectedItem="{Binding SelectedItem}">
    <ComboBoxItem>Item 1</ComboBoxItem>
    <ComboBoxItem>Item 2</ComboBoxItem
</ComboBox>