显示数据绑定 WPF 组合框的默认值 [英] Display a Default value for a Databound WPF ComboBox

查看:26
本文介绍了显示数据绑定 WPF 组合框的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a databound WPF comboxbox where I am using the SelectedValuePath property to select a selected value based on something other than the object's text. This is probably best explained with an example:

<ComboBox ItemsSource="{Binding Path=Items}"
          DisplayMemberPath="Name"
          SelectedValuePath="Id"
          SelectedValue="{Binding Path=SelectedItemId}"/>

这个东西的数据上下文看起来像这样:

The datacontext for this thing looks like this:

DataContext = new MyDataContext
{
    Items = {
        new DataItem{ Name = "Jim", Id = 1 },
        new DataItem{ Name = "Bob", Id = 2 },
    },
    SelectedItemId = -1,
};

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

This is all well and good when I'm displaying pre-populated data, where the SelectedItemId matches up with a valid Item.Id.

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

The problem is, in the new item case, where the SelectedItemId is unknown. What WPF does is show the combo box as blank. I do not want this. I want to disallow blank items in the combo box; I would like it to display the first item in the list.

这可能吗?我可以编写一些代码来显式地预先设置 SelectedItemId,但由于 UI 中的一个缺点而不得不更改我的数据模型似乎并不正确.

Is this possible? I could write some code to explicitly go and set the SelectedItemId beforehand, but it doesn't seem right to have to change my data model because of a shortcoming in the UI.

推荐答案

我认为您将不得不在此处进行一些手动工作才能获得此行为.无论 SelectedItemId 是否匹配,您都可以在第一次显示 ComboBox 时签入代码,然后根据此更改所选索引.或者,如果您知道在没有相应项目时 SelectedItemId 将始终为 -1,则可以使用数据触发器.

I think you are going to have to do some manual work here to get this behavior. You could check in code behind when you first display the ComboBox whether or not the SelectedItemId matches up or not and then change the selected index based on that. Or if you know that the SelectedItemId will always be -1 when there is no corresponding item, you could use a datatrigger.

方法一:

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

方法二:

<Style TargetType="ComboBox">
    <Style.Triggers>
        <DataTrigger Binding="{Binding Path=SelectedItemId}" Value="-1">
            <Setter Property="SelectedIndex" Value="0"/>
        </DataTrigger>
    </Style.Triggers>
</Style>

这篇关于显示数据绑定 WPF 组合框的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆