22

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.

Orion Edwards
  • 121,657
  • 64
  • 239
  • 328

2 Answers2

10

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>
Ben Collier
  • 2,632
  • 1
  • 23
  • 18
  • Would this be neccesary even if the binding Mode was oneWayToSource. I mean where the thing bound to won't effect the ComboBox only the other way around I always wan't the ComboBox to start at the first item in the List but instead it's blank. – Ingó Vals Jan 05 '11 at 14:03
5

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>
MBDevelop
  • 103
  • 1
  • 11
  • 1
    not familiar with triggers but, do we crash if we have a null collection and we do set Value="0" ? thanks – ramnz Dec 16 '11 at 19:42