WPF列表框绑定只读取可更新的可观察集合。 [英] WPF list box bound to read only observable collection not updating.
问题描述
大家好,
我有一个查询,我确定我之前遇到过这个问题,谷歌搜索的结果却提出了同样的问题我已经实现了(以某种方式)。
我有一个MVVM应用程序,其中一个V-VM是显示一些文件列表。
viewModel有一个只读的observable集合属性,如下所示:
Hi guys,
I have a query and I'm sure I've had the issue before yet the results from googling are bringing up the same thing which I have already implemented (in a fashion).
I have a MVVM application and one of the V-VM's is to display some file listings.
The viewModel has a read only observable collection property which looks like this:
public ReadOnlyObservableCollection<TemplateFileViewModel> ListOfTemplates
{
get
{
m_FileListing = new ObservableCollection<TemplateFileViewModel>();
if (!String.IsNullOrWhiteSpace(TemplateDirectoryPath))
{
foreach (var s in Directory.GetFiles(TemplateDirectoryPath, "*.MyEXT",
IncludeSubFolders ? SearchOption.AllDirectories :
SearchOption.TopDirectoryOnly))
{
m_FileListing.Add(new TemplateFileViewModel(s));
}
}
return new ReadOnlyObservableCollection<TemplateFileViewModel>(m_FileListing);
}
}
我还有一个属性TemplateDirectoryPath,如下所示:
I also have a property "TemplateDirectoryPath" which looks like this:
public string TemplateDirectoryPath
{
get { return m_TemplateDirectoryPath; }
set
{
if (Equals(m_TemplateDirectoryPath, value) || !Directory.Exists(value)) return;
m_TemplateDirectoryPath = value;
OnPropertyChanged("TemplateDirectoryPath");
OnPropertyChanged("ListOfTemplates");
}
}
想法是当TemplateDirectoryPath更新时,会触发一个列表框来刷新它内容,绑定到视图模型上的ListOfTemplates属性。
我的理解是,如果我使用OnPropertyChanged事件,它应该导致视图执行数据更新。
我的列表框绑定如下:
The idea is that when the TemplateDirectoryPath is updated it triggers a list box to refresh its contents, which is bound to the ListOfTemplates property on the view model.
No my understanding is that if I user the "OnPropertyChanged" event it should result in the view doing a data refresh.
My listbox is bound as follows:
<ListBox Grid.Column="0" ItemsSource="{Binding Path=ListOfTemplates, UpdateSourceTrigger=PropertyChanged}" ItemTemplate="{StaticResource TemplateFileDataTemplate}"/>
为什么这不会触发更新屏幕上?从我所看到的一切看来都是正确的,我错过了一些非常明显的东西吗?
谢谢
Why would this not be triggering an update on the screen? From what I can see it all appears correct, am I missing something really obvious?
Thanks
推荐答案
我找到了我的问题,
我的ViewModel继承自实现INotifyPropertyChanged的基类,但是我必须将我的viewModel声明为例如:
I found my Issue,
My ViewModel was inheriting from a base class that implemented INotifyPropertyChanged, however I had to declare my viewModel as such:
internal class myVM: myBaseVM, INotifyPropertyChanged
并确保正确的引用到位,否则无法触发事件。因为我的基类已经实现了INotifyPropertyChanged的方法/事件,所以我不必复制它们的实现。
and ensure the correct references were in place else it failed to trigger the events. Because my base class already implemented the methods/events for INotifyPropertyChanged, I did not have to duplicate their implementation.
这篇关于WPF列表框绑定只读取可更新的可观察集合。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!