【问题标题】:WPF DataGrid bound to entity framework doesn't update after change of data in ViewModel在 ViewModel 中更改数据后,绑定到实体框架的 WPF DataGrid 不会更新
【发布时间】:2017-03-23 11:39:11
【问题描述】:

我正在开发一个 WPF 应用程序,其中我将数据网格绑定到实体框架。

这是我的数据网格定义:

            <DataGrid x:Name="grd_formula_arguments" Grid.Row="1" Grid.Column="2" Style="{StaticResource commonControlStyle}" IsReadOnly="True"
                      ItemsSource="{Binding FormulaArgumentsAndFields, Mode=TwoWay, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}"
                      AutoGenerateColumns="False" EnableRowVirtualization="True"
                      CanUserAddRows="False">
                <DataGrid.Columns>
                    <DataGridTextColumn x:Name="col_attribute_name" Binding="{Binding attribute_name}" Header="Argument"/>
                    <DataGridTextColumn x:Name="col_assigned_field_name" Binding="{Binding assigned_field_name}" Header="Feld"/>
                </DataGrid.Columns>
            </DataGrid>

ItemsSource 绑定到 viewmodel 中的一个属性,这是我的实体 formula_field_attributes 的列表。 该实体包含列attribute_name 和assigned_field_name。 这是 viewmodel 属性:

public List<formula_field_attributes> FormulaArgumentsAndFields
{
    get { return formulaArgumentsAndFields; }
    set
    {
        formulaArgumentsAndFields = value;
        RaisePropertyChanged("FormulaArgumentsAndFields");
    }
}

一开始列表只包含属性名,assigned_field_name 为空。 然后我可以为列表中的属性分配一个字段名。

        var argumentname = ((formula_field_attributes)grd_formula_arguments.SelectedItem).attribute_name;
        foreach (var item in changeTextProperties.FormulaArgumentsAndFields)
        {
            if (item.attribute_name == argumentname)
            {
                item.assigned_field_name = fieldName;
            }
        }
        changeTextProperties.RaisePropertyChanged("FormulaArgumentsAndFields");

当我在操作后查看 viewmodel 属性时,它看起来很好。 但我在数据网格中看不到我的更改。 我做错了什么?

提前致谢!

【问题讨论】:

  • 实现了接口 INotifyPropertyChanged。与 RaisePropertyChanged 方法相同。
  • 在您操作集合中的数据后调用RaisePropertyChanged("FormulaArgumentsAndFields");,这样您的 UI 就知道它已经改变了。
  • @XAMIMAX 我尝试了 RaisePropertyChanged("FormulaArgumentAndFields") 但数据网格的内容没有改变。是否有可能我必须使用 ObeservableCollection 而不是 List?
  • 使用 OberservableCollection no List....这是正确的方法。
  • @Wolfgang Feneberg:我也试过了,但没有阳性结果。

标签: c# wpf entity-framework mvvm datagrid


【解决方案1】:

同时我通过以下步骤解决了问题:

  1. 我将 viewmodel 属性的类型更改为 ObeservableCollection。
  2. 我对设置方法进行了更改。我创建了一个新的 ObservableCollection 对象,从 VM 属性中获取项目,设置我想要的assigned_field_name - 最后我使用新对象设置 VM 属性。

我知道这不是我应该做的,但它确实有效。

【讨论】:

  • 你试过我的建议了吗?它避免更改底层集合类型,保持您的代码与其余 VM 代码兼容,并且只更改 UI 处理集合的方式。
  • @XAXIMAX:是的,我尝试了 ObservableCollection,并在我的代码中进行了更改,因为它绝对是更好的选择。但是数据网格并没有实现,即使我调用了 RaisePropertyChanged 方法。很好奇。
猜你喜欢
  • 2013-06-03
  • 1970-01-01
  • 1970-01-01
  • 2011-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-10
相关资源
最近更新 更多