WPF DataGrid MVVM 绑定的数据源更新某个值
在MVVM架构中,更新DataGrid绑定的数据源中的某个值,需要在ViewModel中进行以下操作:
-
在ViewModel中定义一个ObservableCollection类型的属性,用于存储DataGrid绑定的数据源。
-
在XAML中,将DataGrid的ItemsSource属性绑定到ViewModel中定义的ObservableCollection类型的属性。
-
在ViewModel中定义一个方法,用于更新ObservableCollection中的某个值。
-
在XAML中,将需要更新的值绑定到ViewModel中定义的方法。
以下是示例代码:
ViewModel代码:
public class MainViewModel : INotifyPropertyChanged
{
private ObservableCollection<MyData> _dataList;
public ObservableCollection<MyData> DataList
{
get { return _dataList; }
set
{
_dataList = value;
OnPropertyChanged("DataList");
}
}
public MainViewModel()
{
// 初始化数据源
DataList = new ObservableCollection<MyData>
{
new MyData{ Id=1, Name="张三", Age=20},
new MyData{ Id=2, Name="李四", Age=22},
new MyData{ Id=3, Name="王五", Age=25},
};
}
public void UpdateAge(int id, int age)
{
// 更新数据源中id对应的数据的Age值
var data = DataList.FirstOrDefault(d => d.Id == id);
if (data != null)
{
data.Age = age;
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyData
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
XAML代码:
<DataGrid ItemsSource="{Binding DataList}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding Id}" />
<DataGridTextColumn Header="Name" Binding="{Binding Name}" />
<DataGridTextColumn Header="Age" Binding="{Binding Age}" />
<DataGridTemplateColumn Header="操作">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="更新" Command="{Binding DataContext.UpdateCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}" CommandParameter="{Binding Id}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
在XAML中,我们将UpdateCommand绑定到了ViewModel中定义的更新方法UpdateAge,并将需要更新的数据的Id值作为CommandParameter传递给了UpdateCommand。当点击DataGrid中的“更新”按钮时,会触发UpdateCommand,调用ViewModel中的UpdateAge方法,更新ObservableCollection中对应的数据的Age值。由于DataGrid的ItemsSource已经和ViewModel中的DataList属性绑定,因此数据源更新后,DataGrid会自动更新显示的数据
原文地址: http://www.cveoy.top/t/topic/ckHa 著作权归作者所有。请勿转载和采集!