Skip to main content
 首页 » 编程设计

c#之WPF EF6 Datagrid Cell 在以编程方式更改时不会更新,除非用户编辑单元格

2024年02月13日20kenshinobiy

我有一个绑定(bind)到 EF6 Dbcontext 的 WPF 数据网格。我有很多功能,例如手动编辑等。

问题 编辑绑定(bind)到网格的 EF 对象不会在网格上更新。但是,如果我在这些背景编辑之一之后手动编辑单元格,它会立即显示正确的值。

场景/设置

涉及的 ViewSources

<Window.Resources> 
 <CollectionViewSource x:Key="equipmentViewSource" d:DesignSource="{d:DesignInstance {x:Type HAI_Job_EF_Model:Equipment}, CreateList=True}"/> 
 <CollectionViewSource x:Key="equipmentAssociatedDevicesViewSource"  
                              Source="{Binding AssociatedDevices, Source={StaticResource equipmentViewSource}}"/>     
 </Window.Resources> 

请注意,关联设备是 Equipment 对象中的 ObservableCollection。

WPF 数据网格(仅示例部分)

<DataGrid x:Name="associatedDevicesDataGrid" Grid.Row="1" AutoGenerateColumns="False"  
                              MaxWidth="1200" EnableRowVirtualization="True"  
                              RowDetailsVisibilityMode="VisibleWhenSelected" CanUserDeleteRows="False" 
                              DataContext="{StaticResource equipmentAssociatedDevicesViewSource}" ItemsSource="{Binding}"  
                              CellEditEnding="associatedDevicesDataGrid_CellEditEnding"  
                              SelectionChanged="associatedDevicesDataGrid_SelectionChanged"  
                              PreviewKeyDown="associatedDevicesDataGrid_PreviewKeyDown" 
                              LostFocus="associatedDevicesDataGrid_LostFocus"> 
                <DataGrid.Resources> 
                    <!-- DATGRID STYLE CELL: Gives padding space inside cells --> 
                    <Style TargetType="DataGridCell"> 
                        <Setter Property="Padding" Value="5,5"/> 
                        <Setter Property="Template"> 
                            <Setter.Value> 
                                <ControlTemplate TargetType="{x:Type DataGridCell}"> 
                                    <Border Padding="{TemplateBinding Padding}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True"> 
                                        <ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/> 
                                    </Border> 
                                </ControlTemplate> 
                            </Setter.Value> 
                        </Setter> 
                    </Style> 
                </DataGrid.Resources> 
                <DataGrid.Columns> 
                    <DataGridTextColumn x:Name="quantityColumn" Header="Qty" MaxWidth="50"  
                                        Binding="{Binding Quantity, StringFormat={}\{0:N0\}, Mode=TwoWay, UpdateSourceTrigger=LostFocus}"/> 
                    <DataGridComboBoxColumn x:Name="typeColumn" Header="Type" MaxWidth="150"  
                                            ItemsSource="{Binding Source={StaticResource assDevTypeFilteredViewSource}}" 
                                            SelectedItemBinding="{Binding Path=Type, UpdateSourceTrigger=PropertyChanged}"  
                                            TextBinding="{Binding Path=Type, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"> 
                        <DataGridComboBoxColumn.EditingElementStyle> 
                            <Style TargetType="ComboBox"> 
                                <Setter Property="IsEditable" Value="True"/> 
                                <Setter Property="Text" Value="{Binding Path=Type}"/> 
                                <Setter Property="IsSynchronizedWithCurrentItem" Value="True" /> 
                                <Setter Property="IsTextSearchEnabled" Value="True" /> 
                                <Setter Property="IsTextSearchCaseSensitive" Value="False" /> 
                            </Style> 
                        </DataGridComboBoxColumn.EditingElementStyle> 
                    </DataGridComboBoxColumn> 
 
                    <DataGridTemplateColumn x:Name="certificateNumberColumn" Header="Certificate Number" Width="Auto" MaxWidth="200"> 
                        <DataGridTemplateColumn.CellTemplate> 
                            <DataTemplate> 
                                <ComboBox Name="cbxAssDevCertComboBox"  
                                          IsEditable="True" IsTextSearchEnabled="True" IsTextSearchCaseSensitive="False" 
                                          ItemsSource="{Binding GenericFilterResults}" 
                                          Text="{Binding Path=CertificateNumber, UpdateSourceTrigger=PropertyChanged}" 
                                          SelectionChanged="cbxAssDevCertComboBox_SelectionChanged"/> 
                            </DataTemplate> 
                        </DataGridTemplateColumn.CellTemplate> 
                    </DataGridTemplateColumn> 
                    <DataGridTextColumn x:Name="manufacturerColumn" Header="Manufacturer" Width="Auto" MaxWidth="150"  
                                        Binding="{Binding Manufacturer, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/> 

背景变化 组合框“cbxAssDevCertComboBox”selectionchanged 事件然后更新其他单元格源对象的所有值。这是不刷新的更新。

尝试/考虑的主要选项

  1. 我没有完全了解 MVVM,也没有遵循它。我现在太深了,无法为这个项目做出改变。我只需要他妈的东西来更新......!

  2. 我不能将每个单独的 EF 对象都包装在一个 Observable 集合中……没有其他东西需要它,所以这是为什么呢?这不就是 CollectionViewSource 本质上所做的吗?!

  3. 更新 Datagrids ItemSource bindingexpression 没有帮助。

  4. 使用更新

我如何更新单元格,就像我在程序编辑后尝试手动编辑它们一样?

我现在已经浪费了几天时间试图解决这个问题;任何帮助将不胜感激。

请您参考如下方法:

ObservableCollection 很棒,但它仅在添加或删除项时通知 UI。当项目被修改时(即,当项目属性发生更改时)它不会通知 UI。

您需要在您的模型上实现 INotifyPropertyChanged 接口(interface)并启动它。

这是一个实现接口(interface)的示例模型类:

public class ModelClass : INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 
 
    protected virtual void OnPropertyChanged(string property) 
    { 
        if (PropertyChanged != null) 
            PropertyChanged(this, new PropertyChangedEventArgs(property)); 
    } 
 
    protected virtual void OnPropertyChanged<T>(Expression<Func<T>> selectorExpression) 
    { 
        if (selectorExpression == null) 
            throw new ArgumentNullException("selectorExpression"); 
        MemberExpression body = selectorExpression.Body as MemberExpression; 
        if (body == null) 
            throw new ArgumentException("The body must be a member expression"); 
        OnPropertyChanged(body.Member.Name); 
    } 
 
    string _myValue; 
    public string MyValue 
    { 
        get 
        { 
            return _myValue; 
        } 
        set 
        { 
            _myValue = value; 
            OnPropertyChanged(() => MyValue); 
        } 
    } 
} 

漂亮的 lambda 技巧取自 this SO question ...

当然,您可以从代码的其他部分手动调用 OnPropertyChanged(根据需要调整访问器或编写额外的公共(public)方法)。调用 OnPropertyChanged 应该会强制 UI 为显示的属性调用 getter。