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

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

问题描述

我有,我现在用的是 SelectedValuePath 属性的基础上比对象的文本以外的东西来选择选定值数据绑定WPF comboxbox。组合框的ItemsSource ={绑定路径=项目}
;

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}"/>



为这件事DataContext的是这样的:

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.

现在的问题是,在新项目的情况下,其中 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.

推荐答案

我想你将不得不做一些手工作品在这里得到这种行为。你可以检查代码当你第一次显示ComboBox中SelectedItemId是否不涨匹配或不落后,然后更改基于选定的索引。 。或者,如果你知道SelectedItemId永远是-1时,有没有相应的项目,你可以使用一个datatrigger

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.

方法1:

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



方法2:

Method 2:

<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天全站免登陆