开发者

Display a Default value for a Databound WPF ComboBox

开发者 https://www.devze.com 2022-12-14 15:25 出处:网络
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 ex

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,
};

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

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.

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.


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.

Method 1:

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

Method 2:

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


you may use this style trigger: if selecteditem is null, first element is selected.

<Trigger Property="SelectedItem" Value="{x:Null}">
    <Setter Property="SelectedIndex" Value="0"/>
</Trigger>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号