[英]C#WPF - Binding updates on add/remove but not on update [duplicate]
在我的 WPF 应用程序中,我有一个带有编辑、添加和删除按钮的 ListView。 按删除或添加按钮,立即在 GUI 中显示更改。
按下更新按钮,不会更改 GUI,只有当我更改到另一个页面(使用 IPage)并返回时,页面才会刷新/显示更改。
我也希望在更新某个位置的属性Naam时刷新视图。
Xml:
<ListView ItemsSource="{Binding Locations, Mode=TwoWay}" SelectedItem="{Binding SelectedLocation, Mode=TwoWay}">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Naam}"></TextBlock>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Button Content="Update" Command="{Binding UpdateLocationCommand}" />
<Button Content="Remove" Command="{Binding RemoveLocationCommand}" />
<Button Content="Add" Command="{Binding AddLocationCommand}" />
虚拟机:
class ClassName : ObservableObject, IPage, INotifyPropertyChanged
{
private ObservableCollection<LocatieModel> _locations = new ObservableCollection<LocatieModel>();
public ObservableCollection<LocatieModel> Locations
{
get { return _locations; }
set
{
_locations = value;
OnPropertyChange("Locaties");
}
}
private LocatieModel selectedLocation;
public LocatieModel SelectedLocation
{
get { return selectedLocation; }
set
{
selectedLocation= value;
OnPropertyChange("SelectedLocation");
}
}
public VM()
{
addLocationCommand = new Command(AddLocation, true);
updateLocationCommand = new Command(UpdateLocation, true);
removeLocationCommand = new Command(RemoveLocation, true);
}
private void AddLocation(object obj)
{
Locations.Add(new LocatieModel() { Naam = "banana1"});
}
private void RemoveLocation(object obj)
{
Locations.Remove(SelectedLocation);
}
private void UpdateLocation(object obj)
{
Locations.Single(l => l == SelectedLocation).Naam = "apple42";
}
// Part for InotificationChanged
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChange(string propertyname)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyname));
}
}
而 LocatieModel,只是一个模型:
public class LocatieModel
{
public int Id { get; set; }
public string Naam { get; set; }
}
如何让gui在更新时更新列表? 可以自动触发吗? 没有想法。 谢谢你的时间。
PS:我查看了可能的答案,但这使它成为一个不可见(不存在)元素的列表。
编辑:我昨天尝试在 LocatieModel 类中实现 INotifyPropertyChanged 但没有奏效。 可能是某个地方的疏忽,因为现在它起作用了。 谢谢 :)
要更新Naam
,您必须在LocatieModel类中实现INotifyPropertyChanged
。
定位模型到
public class LocatieModel : INotifyPropertyChanged
{
public int Id { get; set; }
private string naam;
public string Naam
{
get { return naam; }
set
{
naam = value;
OnPropertyChange(nameof(Naam));
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChange(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.