【问题标题】:MVVM WPF ComboBox SelectedValue isn't the exact valueMVVM WPF ComboBox SelectedValue 不是确切值
【发布时间】:2021-09-14 10:05:22
【问题描述】:

我正在尝试在 DataGrid.RowDetailsTemplate 中实现一个组合框

这是组合框:

<ComboBox
    Grid.Column="1"
    Width="300"
    BorderThickness="1"
    DisplayMemberPath="Name"
    Foreground="{StaticResource BrushTextForeground}"
    IsSynchronizedWithCurrentItem="True"
    ItemsSource="{Binding Path=DataContext.Categories, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
    SelectedValue="{Binding Path=Category, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

Categories 是 Category 的 IEnumerable 列表:

public IEnumerable<Category> Categories { get; set; }

Category 是 Transaction 列表中的一个属性,它也是我的 Datagrid 的 itemssource:

private readonly ObservableCollection<Transaction> _transactions;
public IEnumerable<Transaction> Transactions => _transactions;

问题是当我打开我的数据网格的行时,组合框不采用 selectedValue 类别的值,但她只采用 itemssource 类别的第一项 此外,当我从组合框中选择一个值时,将为数据网格中的所有行选择相同的值。

【问题讨论】:

  • 我怀疑您的集合 Categories 具有不同的对象,但与 Transaction 类中的对象具有相同的属性。如果是这种情况,ComboBox 正在比较实例。考虑将SelectedValuePathSelectedValue 一起使用。
  • 哦,我明白了,谢谢,这解决了第一个问题,但是现在当我在一个组合框中选择一些东西时,所有组合框都采用相同的值,你知道为什么吗?

标签: c# wpf mvvm combobox datagrid


【解决方案1】:

我会修改如下,考虑到您的类别列表是Categories,您之前在 ViewModel 中设置了SelectedCategory,并且您的类 Category 有一个属性 Name

<ComboBox 
  ItemsSource="{Binding Path=Categories}" 
  SelectedItem="{Binding Path=SelectedCategory}"
  //Mode=TwoWay, UpdateSourceTrigger=PropertyChanged not necessary
  DisplayMemberPath="Name" Margin="5"
/>
    

【讨论】:

    猜你喜欢
    • 2010-10-14
    • 2021-07-07
    • 2016-08-09
    • 1970-01-01
    • 2012-06-19
    • 1970-01-01
    • 2012-06-23
    • 2017-02-20
    • 1970-01-01
    相关资源
    最近更新 更多