根据内容将 ComBobox 设置为 ComboBox Item

Set ComBox to ComboBoxItem based on content

我有一个组合框,其中的组合框项在 xaml 中进行了硬编码,我正在尝试根据字符串值以编程方式设置组合框的值。

XAML:

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

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

comboConditionValue.SelectedItem = "Item 1";

当然,当组合框包含 ComboBoxItems 而不是绑定到列表时,这不起作用。我可以这样找到正确的值:

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

这是一种设置值的混乱而缓慢的方法,有谁知道我可以设置正确的 ComboBoxItem 而无需循环遍历完整列表的更简单方法吗?

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

在你后面查看代码:

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

然后在您的 myViewModel class 中,您有一个 属性 用于所选项目:

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>