WPF中从ViewModel更新时,组合框的SelectedItem值变为空

3

我在每个数据表行中创建了一个组合框。以下代码段用于创建组合框:

<ComboBox Width="166"
          ItemTemplate="{StaticResource GridBinding}"
          SelectedItem="{Binding Path=Car, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, IsAsync=True}"
          SelectedValue="{Binding Path=Car, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, IsAsync=True}">
    <ComboBox.GroupStyle>
        <GroupStyle HeaderTemplate="{StaticResource GroupHeader}" />
    </ComboBox.GroupStyle>
    <ComboBox.Style>
        <Style TargetType="ComboBox">
            <Setter Property="ItemsSource" Value="{Binding Path=Cars}" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=IsSelected, RelativeSource={RelativeSource AncestorType=DataGridCell}}" Value="True">
                    <Setter Property="ItemsSource" Value="{Binding Path=DataContext.GroupedCars, RelativeSource={RelativeSource AncestorType=DataGrid}}" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ComboBox.Style>
</ComboBox>

在组合框中用于绑定“SelectedItem”的“Car”属性是一个类“Car”的对象,它包含一些属性,如id、name等。

我面临的问题是,当我更新“Car”属性的值并在其setter中调用“NotifyPropertyChanged”时,组合框中的“SelectedItem”的值变为空白/空。

请建议。


你应该使用SelectedItem OR SelectedValue,而不是两者都用。 - ibebbs
仅使用“SelectedItem”时,当从ViewModel更改时,它不会更新UI上的值。这是因为“SelectedItem”使用引用将值与每个itemsource的项目进行比较。 - Ena Jain
1个回答

2
所选项在更新ItemSource后已不再集合中,并被设置为null。
我已经简化了您的XAML以进行演示。
<ComboBox ItemsSource="{Binding Cars}"
          SelectedItem="{Binding Car}">
    <ComboBox.Style>
        <Style TargetType="ComboBox">
            <Style.Triggers>
                <Trigger Property="SelectedItem" Value="{x:Null}">
                    <Setter Property="SelectedIndex" Value="0" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </ComboBox.Style>
</ComboBox>

现在,当您进行更新时,第一项将被选中。


1
感谢您的帮助。ibebbs建议的上述方法与使用链接[https://rachel53461.wordpress.com/2011/08/20/comboboxs-selecteditem-not-displaying/]结合使用对我很有帮助。 - Ena Jain

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接