wpf MVVM ObservableCollection;不更新视图
我遇到的问题是我的 ObservableCollection 没有更新视图。我可以在 OnPropertyChange 之前放置一个断点,并可以验证我的集合中是否包含名称。
在我的模型中,我有一个事件会触发一个包含随机名称的列表。
在我的视图模型中,我订阅了此事件,并且我的事件处理程序执行此操作,
void _manager_ProcessesChanged(List<string> n)
{
//create a new collection to hold current Ids
ObservableCollection<string> names = new ObservableCollection<string>();
//copy ids into our collection
foreach (string name in n)
{
names.Add(name);
}
Names = names;
}
我的 Names 属性看起来像这样
ObservableCollection<string> _names = new ObservableCollection<string>();
public ObservableCollection<string> Names
{
get { return _names; }
set
{
_names = value;
OnPropertyChanged("Names");
}
}
,我的视图绑定看起来像这样
<Window.DataContext>
<vm:MainWindowViewModel/>
</Window.DataContext>
<Grid>
<ListBox ItemsSource="{Binding Path=Names}"/>
</Grid>
如果我将
的集合更改为 < ;int>
它似乎工作正常..我错过了什么?
I am having an issue where my ObservableCollection is not updating the view. I can place a breakpoint prior to the OnPropertyChange and can verify that my collection has the names in them.
In my model i have a event that fires a List with random names in it.
in my view model i subscribe to this event and my event handler does this
void _manager_ProcessesChanged(List<string> n)
{
//create a new collection to hold current Ids
ObservableCollection<string> names = new ObservableCollection<string>();
//copy ids into our collection
foreach (string name in n)
{
names.Add(name);
}
Names = names;
}
my Names property looks like so
ObservableCollection<string> _names = new ObservableCollection<string>();
public ObservableCollection<string> Names
{
get { return _names; }
set
{
_names = value;
OnPropertyChanged("Names");
}
}
and my view binds looks like this
<Window.DataContext>
<vm:MainWindowViewModel/>
</Window.DataContext>
<Grid>
<ListBox ItemsSource="{Binding Path=Names}"/>
</Grid>
If i change the collection for <string>
to <int>
it seems to work fine.. what am i missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您重新实例化 ObservableCollection,您将失去与该集合的绑定。
您应该 .Clear(...) 和 .Add(...) 项目,并且您还应该将 ObservableCollection Names 更改为自动属性。无需在此处调用 OnPropertyChanged,因为它是由类型为您处理的。
If you re-instantiate the ObservableCollection you will lose your binding to the collection.
You should .Clear(...) and .Add(...) the items, and you should also just change ObservableCollection Names to an auto-property. No need to call OnPropertyChanged here, as it is handled by the type for you.
我也遇到过这个。不确定这是否是理想的解决方案(当然看起来不是)但这对我有用
I've run into this as well. Not sure if this is the ideal solution (sure doesn't seem like it) but this has worked for me