gpt4 book ai didi

WPF ListView : Howto refresh manually?

转载 作者:行者123 更新时间:2023-12-04 16:06:45 24 4
gpt4 key购买 nike

我有 WPF ListView 的绑定(bind)问题。 View 模型实现 INotifyPropertyChanged 以触发数据更新。但它包含一个不实现 INotifyPropertyChanged 的​​类型(“Person”)的可观察集合。

ListView启动后显示我绑定(bind)的人,没问题。但是在更改模型的数据(人的年龄)之后,我需要以某种方式手动更新视觉表示/绑定(bind) - 这是我的问题。

如果有人能将我引导到正确的方向,我将不胜感激,谢谢!

模型非常简单:

// does not implement INotifyPropertyChanged interface
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}

PersonList 是一个 ObservableCollection,它通过 ItemsSource 绑定(bind)到 ListView:

<ListView x:Name="ListViewPersons" ItemsSource="{Binding PersonList}">
<ListView.View>
<GridView>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"></GridViewColumn>
<GridViewColumn Header="Age" DisplayMemberBinding="{Binding Age}"></GridViewColumn>
</GridView>
</ListView.View>
</ListView>

View 的代码隐藏将“年龄增长”委托(delegate)给 View 模型。模型数据更改后,我需要以某种方式更新 GUI,这是我的问题:

private void Button_Click(object sender, RoutedEventArgs e)
{
...

// increasing the age of each person in the model
viewModel.LetThemGetOlder();

**// how to update the View?**

// does not work
ListViewPersons.GetBindingExpression(ListView.ItemsSourceProperty)
.UpdateTarget();

// does not work either
ListViewPersons.InvalidateProperty(ListView.ItemsSourceProperty);
}
}

为了完整起见,ViewModel:

class ViewModel : INotifyPropertyChanged
{
public ViewModel()
{
PersonList = new ObservableCollection<Person>
{
new Person {Name = "Ellison", Age = 56},
new Person {Name = "Simpson", Age = 44},
new Person {Name = "Gates", Age = 12},
};
}

internal void LetThemGetOlder()
{
foreach (var p in PersonList)
{
p.Age += 35;
}
}

private ObservableCollection<Person> _personList;
public ObservableCollection<Person> PersonList
{
get { return _personList; }
set
{
_personList = value;
OnPropertyChanged();
}
}

public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}

最佳答案

您可以尝试 Items.Refresh(); 但我会重新考虑我的类设计,尤其是您的 View 模型和模型。为什么您的模型不实现 INotifyPropertyChanged?为什么不以 1:1 的比例将模型包装在 View 模型中?目前您正在围绕 WPF 工作,只有在有充分理由的情况下才应该这样做。

关于WPF ListView : Howto refresh manually?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17143134/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com