Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
515 views
Welcome To Ask or Share your Answers For Others

1 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...