首页 > 解决方案 > 更改 DataGrid 中的项目。这是正确的方法吗?

问题描述

我有一个绑定到 ObservableCollection 的 DataGrid,我确信我用来更新该集合中的项目的方式不是正确的方式。我在刷新 DataGrid 时遇到了问题。如果我直接修改一个项目,DataGrid 不会刷新,直到我单击另一个单元格。我可以看到 NotifyPropertyChanged 在“Details”和“_Detail”中被击中,但 UI 只是没有刷新。在尝试了很多东西之后,我找到了一个解决方法:我删除了前一个,并添加了新项目。事情是我不想以正确的方式去做。那么……是哪一个?

C#

public class AsientoDetallesViewModel : ViewModelBase, IInteractionRequestAware, INotifyPropertyChanged
{
    private ObservableCollection<Details> details;
    public ObservableCollection<Details> Details
    {
        get => details;
        set
        {
            SetProperty(ref details, value, nameof(Details));
            NotifyPropertyChanged(nameof(Details));
        }
    }

    private Detail _detail;
    public Detail _Detail
    {
        get => _detail;
        set
        {
            SetProperty(ref _detail, value, nameof(_Detail));
            NotifyPropertyChanged(nameof(_Detail));
        }
    }

    private void UpdateRow()
    {
        var itemUpdated = _Detail;
        itemUpdated.Account.Name = "some name";
        itemUpdated.Account.Name2 = "another name";

        //the workaround
        Detalles.Remove(itemUpdated);
        Detalles.Add(itemUpdated);
    }
}

XAML

<DataGrid ItemsSource="{Binding Details, Mode=TwoWay}"
          SelectedItem="{Binding _Details, Mode=TwoWay}"
          AutoGenerateColumns="False">
<DataGrid.Columns>
            <DataGridTemplateColumn>
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Path=Binding Path=Account.Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Center" Margin="0, 3, 0, 0" ></TextBlock>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTemplateColumn>
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Path=Account.Name2, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="0, 3, 0, 0"></TextBlock>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
         </DataGrid.Columns>
    </DataGrid>

标签: c#wpfxaml

解决方案


它是从类的Account属性返回的对象Detail,它必须实现INotifyPropertyChanged接口并引发更改通知以使TextBlocks绑定到NameName2属性得到刷新。

AsientoDetallesViewModel是否实现并不重要,INotifyPropertyChanged因为您没有绑定到此类的属性。


推荐阅读