List和ObservableCollection和ListBinding在MVVM模式下的对比

List和ObservableCollection和ListBinding在MVVM模式下的对比

List

当对List进行增删操作后,并不会对View进行通知。

csharp 复制代码
//Employee
public class Employee : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler? PropertyChanged;
    public string Name { get; set; }
    private int salary;
    public int Salary
    {
        get { return salary; }
        set
        {
            salary = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Salary)));
        }
    }
}
xml 复制代码
<!--View-->
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition Height="40" />
    </Grid.RowDefinitions>
    <DataGrid ItemsSource="{Binding Employees}" />
    <StackPanel
        Grid.Row="1"
        VerticalAlignment="Center"
        Orientation="Horizontal">
        <Button Command="{Binding addCommand}" Content="Add" />
        <TextBlock Text="工资总额" />
        <TextBox Text="{Binding TotalSalary, Mode=OneWay}" />
    </StackPanel>
</Grid>
csharp 复制代码
//MainViewModel
public partial class MainViewModel:INotifyPropertyChanged
{
    public List<Employee> Employees { get; }
    public int TotalSalary=>Employees.Sum(x => x.Salary);

    
    public MainViewModel()
    {
        Employees = new List<Employee>() { 
            new Employee(){Name="Tom",Salary=200},
            new Employee(){Name="Tim",Salary=450},
            new Employee(){Name="Jerry",Salary=780},
            new Employee(){Name="Jake",Salary=540},
            new Employee(){Name="Kit",Salary=670},
        };
        
    }
    [RelayCommand]
    private void add()
    {
        Employees.Add(new Employee() {  Name = "Lit", Salary = 260 });
        //通知TotalSalay
        PropertyChanged?.Invoke(this,new PropertyChangedEventArgs(nameof(TotalSalary)));
    }

    public event PropertyChangedEventHandler? PropertyChanged;
}

可以看到,点击Add后,上面列表中并没有更新,但是工资总额已经更新,这说明新的数据已经加到了List中,但是List并没有通知View。

ObservableCollection

  • ObservableCollection可以在增加和删除时,对View进行通知

    修改MainViewModel

    csharp 复制代码
    public partial class MainViewModel:INotifyPropertyChanged
    {
        public ObservableCollection<Employee> Employees { get; }
        public int TotalSalary=>Employees.Sum(x => x.Salary);
    
        
        public MainViewModel()
        {
            Employees = new ObservableCollection<Employee>() { 
                new Employee(){Name="Tom",Salary=200},
                new Employee(){Name="Tim",Salary=450},
                new Employee(){Name="Jerry",Salary=780},
                new Employee(){Name="Jake",Salary=540},
                new Employee(){Name="Kit",Salary=670},
            };
            
        }
        [RelayCommand]
        private void add()
        {
            Employees.Add(new Employee() {  Name = "Lit", Salary = 260 });
            PropertyChanged?.Invoke(this,new PropertyChangedEventArgs(nameof(TotalSalary)));
        }
        //增加一个Modify方法
        [RelayCommand]
        private void Modify()
        {
            Employees[2].Salary = 999;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(TotalSalary)));
        }
    
        public event PropertyChangedEventHandler? PropertyChanged;
    }

    可以发现,点击Add,View中也相应地进行了更新,而且工资总额也相应改变。同时,无论是add还是Modify,都使用了PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(TotalSalary)));它的改进做法是使用CollectionChanged事件。

csharp 复制代码
//改进做法,增加CollectionChanged,可以删除add()和Modify()的PropertyChanged...了
Employees.CollectionChanged += (_, _) => { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(TotalSalary))); };

BindingList

BindingList提供了更多的功能,提供了排序、搜索、过滤等功能。此外,BindingList 还提供了对数据源的更多控制,如 AllowNew、AllowEdit 和 AllowRemove 属性,用于控制是否允许添加、编辑和删除项。

BindingList提供了ListChanged事件,该事件参数中提供了详细的信息,但是ObservableCollection 是线程安全的,可以在多个线程中使用。而 BindingList 不是线程安全的,如果需要在多个线程中使用,需要进行额外的线程同步处理。

相关推荐
Scout-leaf1 天前
WPF新手村教程(三)—— 路由事件
c#·wpf
用户298698530142 天前
程序员效率工具:Spire.Doc如何助你一键搞定Word表格排版
后端·c#·.net
牧马人win2 天前
SmartDapper.Repository
.net
埃博拉酱3 天前
VS Code Remote SSH 连接 Windows 服务器卡在"下载 VS Code 服务器":prcdn DNS 解析失败的诊断与 BITS 断点续传
windows·ssh·visual studio code
mudtools3 天前
搭建一套.net下能落地的飞书考勤系统
后端·c#·.net
玩泥巴的3 天前
搭建一套.net下能落地的飞书考勤系统
c#·.net·二次开发·飞书
唐宋元明清21883 天前
.NET 本地Db数据库-技术方案选型
windows·c#
加号33 天前
windows系统下mysql多源数据库同步部署
数据库·windows·mysql
tryCbest3 天前
Windows环境下配置pip镜像源
windows·pip