【问题标题】:SelectedItem value of combo box gets empty on updating from viewmodel in wpf从 wpf 中的视图模型更新时,组合框的 SelectedItem 值为空
【发布时间】:2017-01-14 03:50:35
【问题描述】:

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

<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”属性的值并在其设置器中调用“NotifyPropertyChanged”时,组合框中“SelectedItem”的值变为空白/空。

请提出建议。

【问题讨论】:

  • 你应该使用 SelectedItem OR SelectedValue,而不是两者。
  • 仅使用“SelectedItem”,当从视图模型更改时,它不会更新 UI 上的值。这是因为“SelectedItem”使用引用将值与 itemsource 的每个项目进行比较。

标签: wpf mvvm combobox


【解决方案1】:

SelectedItem 无法再在 Collection 中找到(当您更新 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>

现在第一个项目将在您更新时被选中。

【讨论】:

猜你喜欢
  • 2021-10-15
  • 1970-01-01
  • 1970-01-01
  • 2014-09-06
  • 2012-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多