我在使用WinUI 3绑定ObservableCollection时遇到了一些问题:
(a(当集合发生更改(添加或删除项目(时,ListView不会更新。
(b(重新排序ListView(使用控件本身(后,ListView不会保持新的顺序。
类定义
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Xml.Linq;
public class Standards
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private ObservableCollection<Standard> _Collection;
public ObservableCollection<Standard> Collection {
get => _Collection;
set { if (_Collection != value) { _Collection = value;
NotifyPropertyChanged("Description"); } }
}
}
public class Standard : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public Standard() { }
public Standard(XElement e)
{
Name = e.Attribute("name").Value;
Description = e.Attribute("description").Value;
}
public Standard(string standard, string description)
{
Name = standard;
Description = description;
}
private string _Description;
private string _name;
public string Name { get => _name; set { if (_name != value){ _name = value; NotifyPropertyChanged("Name"); } }
}
public string Description { get => _Description; set { if (_Description != value) { _name = value; NotifyPropertyChanged("Description"); } } }
}
WinUI XAML
<ListView x:Name="lvStandards"
Grid.Row="2"
Margin="5"
CanReorderItems="True"
ReorderMode="Enabled"
AllowDrop="True"
ItemsSource="{x:Bind viewModel.Standards.Collection, Mode=TwoWay}"/>
在我的测试中,它按预期工作。我认为你的装订有问题。如果我在运行时绑定:
lvData.ItemsSource = standards.Collection;
所有操作都很好,并且集合被重新排序。向集合中添加项目也会使它们显示在列表视图中。
请尝试在运行时绑定。
这个问题中可能缺少它,但至少您需要在Standards类中实现INotifyPropertyChanged
,并将Collection的NotifyPropertyChanged
处的参数更改为";集合";。
public class Standards : INotifyPropertyChanged // HERE
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private ObservableCollection<Standard> _Collection;
public ObservableCollection<Standard> Collection
{
get => _Collection;
set
{
if (_Collection != value)
{
_Collection = value;
NotifyPropertyChanged("Collection"); // HERE
}
}
}
}
还可以查看CommunityToolkit MVVM NuGet包。它会让你的生活更轻松,让你的代码变得小巧干净。
[ObservableObejct]
public partial class Standards
{
[ObservableProperty]
private ObservableCollection<Standard> _Collection;
}