c# - 更改 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>
解决方案
它是从类的Account
属性返回的对象Detail
,它必须实现INotifyPropertyChanged
接口并引发更改通知以使TextBlocks
绑定到Name
和Name2
属性得到刷新。
AsientoDetallesViewModel
是否实现并不重要,INotifyPropertyChanged
因为您没有绑定到此类的属性。
推荐阅读
- javascript - 正则表达式用 iframe src 文本中的 youtube 链接替换 iframe
- node.js - 在 NodeJs 和 express 中存储和使用访问令牌的最佳实践
- julia - Julia:为什么在函数中指定参数类型会导致(看似)不一致的行为?
- docker - Docker:使用 docker-compose 与主机共享预填充的容器文件夹
- c# - 有没有办法阻止实体框架从不读取属性是特定值的条目?
- c - 如何从文本文件中读取整数和字符并将它们存储在单独的数组中?
- react-native - 更新 redux 中维护的对象数组时 react-native FlatList 渲染数据出现问题
- php - 从客户端发送的电子邮件响应以 php 保存到我的数据库
- powershell - 在 Octopus Deploy 中使用 Powershell 新生成的 API 密钥
- python-3.x - 如何将python中的telnet句柄从一个类传递到另一个类