在 MVVM 架构中,更新 DataGrid 绑定的数据源中的某个值,需要在 ViewModel 中进行以下操作:

  1. 在 ViewModel 中定义一个 ObservableCollection 类型的属性,用于存储 DataGrid 绑定的数据源。

  2. 在 XAML 中,将 DataGrid 的 ItemsSource 属性绑定到 ViewModel 中定义的 ObservableCollection 类型的属性。

  3. 在 ViewModel 中定义一个方法,用于更新 ObservableCollection 中的某个值。

  4. 在 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 会自动更新显示的数据。

WPF DataGrid MVVM 绑定数据源更新值:最佳实践和代码示例

原文地址: https://www.cveoy.top/t/topic/ntBi 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录