[英]C# BindingList<> not updating a WPF Listbox on changed items
我在一个 MVVM C# 项目中。
我想显示一个对象列表。 我想添加和删除此列表中的项目,并更改此列表中的项目。
所以我选择了 BindingList<> 而不是 ObservableCollection<>,如果一个项目发生了变化,它不会被注意到。 (我还测试了网络中的 ObservableCollectionEx,但这与我的 BindingList 具有相同的行为)。 但是当项目改变时,列表框并没有改变。 (添加和删除项目在列表框中更新)
在我的 XAML 中
<ListBox DisplayMemberPath="NameIndex" ItemsSource="{Binding Profiles}" SelectedItem="{Binding SelectedProfile}">
或替代 ItemTemplate
<ListBox DockPanel.Dock="Right" ItemsSource="{Binding Profiles}" SelectedItem="{Binding SelectedProfile}" Margin="0,10,0,0">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding NameIndex}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
在我的 ViewModel 中(ViewModelBase 正在实现 INotifyPropertyChanged 等)
public class ProfileListViewModel : ViewModelBase
{
private BindingList<Profile> profiles;
public BindingList<Profile> Profiles
{
get
{
return profiles;
}
set
{
profiles = value;
RaisePropertyChanged();
}
}
我的项目也在实现 INotifyPropertyChanged,我在我的 Setter 中调用 OnPropertyChanged("Name")。
我的模型
public class Profile : INotifyPropertyChanged
{
public Profile(){}
public int ProfileID { get; set; }
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
OnPropertyChanged("Name");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
用 ViewModel 连接 View(BindingList 在 View 之前初始化)
ProfileListViewModel plvw= new ProfileListViewModel(message.Content);
var profileView = new ProfileListView(plvw);
profileView.ShowDialog();
在 View.xaml.cs
public ProfileListView(ProfileListViewModel plvw)
{
InitializeComponent();
DataContext = plvw;
}
当我更改对象的名称时,我会收到我在 ViewModel( Profiles.ListChanged += Profiles_ListChanged;
)中订阅的 ListChanged 事件,用于测试但 ListBox 中的项目没有改变。
我做错了什么? 如何获得更新的列表框?
由于您的 DisplayIndex 是计算属性NameIndex
,当它的值由于其他属性的变化而变化时,您需要调用OnPropertyChanged("NameIndex")
,例如:
public string Name
{
get
{
return name;
}
set
{
name = value;
OnPropertyChanged("Name");
OnPropertyChanged("NameIndex");
}
}
使用 Profiles.ResetBindings() 再次绑定它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.