Display a Default value for a Databound WPF ComboBox

前端 未结 2 1711
逝去的感伤
逝去的感伤 2020-12-14 17:44

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. Th

相关标签:
2条回答
  • 2020-12-14 18:05

    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>
    
    0 讨论(0)
  • 2020-12-14 18:09

    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 讨论(0)
提交回复
热议问题