WPF上位机,如何在表格中动态更新数据

假如我有一个学生类:

    public partial class Student
    {

        public int Id { get; set; }
        public string Name { get; set; }
        public string Age { get; set; }
    }

建立一个ObservableCollection:

        [ObservableProperty]
        private ObservableCollection<Student> students = new();

并在ViewModel的构造函数里面初始化:

        public MainWindowViewModel(MyS7Entry myS7Entry)
        {

            this.myS7 = myS7Entry;

            Students = new()
            {
                new()
                {
                    Id = 1,
                    Name = "珍妮特",
                    Age = "40"
                },
                new()
                {
                    Id = 2,
                    Name = "麦达琳",
                    Age = "53"
                },
                new()
                {
                    Id = 3,
                    Name = "克莱尔",
                    Age = "30"
                }
            };
            //isConnected = myS7Master.IsConnected;


        }

定义一个按钮来更新DataGrid:

        [RelayCommand]
        void Update()
        {
            Students[2].Name = "戴安娜";
            Students[2].Age = "35";
        }

前端代码:

        <Grid Grid.Row="0" Grid.Column="2">
            <DataGrid AlternationCount="2"
                AutoGenerateColumns="False" ItemsSource="{Binding Students}">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="Id" Width="*" Binding="{Binding Id}" />
                    <DataGridTextColumn Header="年龄" Width="*" Binding="{Binding Age}" />
                    <DataGridTextColumn Header="姓名" Width="*" Binding="{Binding Name}" />
                DataGrid.Columns>
            DataGrid>
        Grid>
        <Grid Grid.Row="1" Grid.Column="2">
            <Button Content="更新" Command="{Binding UpdateCommand}"/>
        Grid>

但是ObservableCollection
只能通过自身成员的增加和删除通知WPF的DataGrid。

点击按钮无效:

WPF上位机,如何在表格中动态更新数据_第1张图片

如果Student 继承了通知接口 ObservableObject

不需要写注解:

using CommunityToolkit.Mvvm.ComponentModel;

namespace MyTokitTest1.Mvvm
{
    public partial class Student:ObservableObject
    {
        //[ObservableProperty]
        //private int id;
        //[ObservableProperty]
        //public string name;
        //[ObservableProperty]
        //public string age;

        public int Id { get; set; }
        public string Name { get; set; }
        public string Age { get; set; }
    }
}

更新成功:

WPF上位机,如何在表格中动态更新数据_第2张图片

代码地址:

https://gitee.com/helodoger/my-csharp-code.git

你可能感兴趣的:(wpf)