显示Databound WPF ComboBox的默认值

Ori*_*rds 22 c# data-binding wpf combobox

我有一个数据绑定WPF comboxbox,我使用该SelectedValuePath属性根据对象的文本以外的东西选择一个选定的值.这可能最好用一个例子来解释:

<ComboBox ItemsSource="{Binding Path=Items}"
          DisplayMemberPath="Name"
          SelectedValuePath="Id"
          SelectedValue="{Binding Path=SelectedItemId}"/>
Run Code Online (Sandbox Code Playgroud)

这个东西的datacontext看起来像这样:

DataContext = new MyDataContext
{
    Items = {
        new DataItem{ Name = "Jim", Id = 1 },
        new DataItem{ Name = "Bob", Id = 2 },
    },
    SelectedItemId = -1,
};
Run Code Online (Sandbox Code Playgroud)

当我显示预先填充的数据时,这一切都很好,其中SelectedItemId匹配有效Item.Id.

问题是,在新项目的情况下,SelectedItemId未知的地方.WPF的作用是将组合框显示为空白.我不想要这个.我想禁止组合框中的空白项; 我希望它显示列表中的第一项.

这可能吗?我可以编写一些代码来明确地SelectedItemId预先设置,但由于UI的缺点,我不得不改变我的数据模型.

Ben*_*ier 9

我认为你将不得不在这里做一些手工工作来获得这种行为.无论SelectedItemId是否匹配,您都可以在首次显示ComboBox时检入代码,然后根据该代码更改所选索引.或者,如果您知道如果没有相应的项目,SelectedItemId将始终为-1,则可以使用数据触发器.

方法1:

if (!DataContext.Items.Exists(l => l.Id == DataContext.SelectedItemId))
{
    MyComboBox.SelectedIndex = 0;  //this selects the first item in the list
}
Run Code Online (Sandbox Code Playgroud)

方法2:

<Style TargetType="ComboBox">
    <Style.Triggers>
        <DataTrigger Binding="{Binding Path=SelectedItemId}" Value="-1">
            <Setter Property="SelectedIndex" Value="0"/>
        </DataTrigger>
    </Style.Triggers>
</Style>
Run Code Online (Sandbox Code Playgroud)


MBD*_*lop 5

您可以使用这种样式触发器:如果 selecteditem 为空,则选择第一个元素。

<Trigger Property="SelectedItem" Value="{x:Null}">
    <Setter Property="SelectedIndex" Value="0"/>
</Trigger>
Run Code Online (Sandbox Code Playgroud)