我创建了一个简单的Treeview,我绑定了一个ObservableCollection。
ObservableCollection<IMarketDataViewModel> MarketDataItems;
public interface IMarketDataViewModel
{
string Title { get; }
ObservableCollection<IMarketDataViewModel> Items { get; set; }
}
public MarketDataUserControl(IMarketDataViewer viewModel)
{
InitializeComponent();
DataContext = viewModel;
marketDataTreeView.ItemsSource = viewModel.MarketDataItems;
}
当我在ViewModel中更新数据时,我只看到Treeview中的第一个级别。我发现解决问题的唯一方法是在我的ViewModel中创建一个事件,当更新数据而不是在MarketDataItems上调用PropertyChange时,我触发事件并且视图重置marketDataTreeView.ItemsSource如下:
private void ViewModelOnOnUpdateItems()
{
marketDataTreeView.ItemsSource = null;
marketDataTreeView.ItemsSource = viewModel.MarketDataItems;
}
这项工作非常完美 - &gt;显示所有级别。
有人知道为什么PropertyChange不起作用以及我为什么要重置ItemsSource?
答案 0 :(得分:0)
我认为你应该实现对ItemSource
的绑定,这是由一个属性完成的:
// Create property
public ObservableCollection<IMarketDataViewModel> MarketDataItems { get; private set; }
...
// Create Binding
Binding bindingObject = new Binding("MarketDataItems");
bindingObject.Source = this; //codebehind class instance which has MarketDataItems
marketDataTreeView.SetBinding(TreeView.ItemsSource, bindingObject);
或XAML中的绑定:
<TreeView x:Name="marketDataTreeView" ItemsSource="{Binding Path=MarketDataItems}"/>
答案 1 :(得分:0)
最后问题是我没有调用OnPropertyChanged(“Items”)
public class MarketDataViewModelBase : IMarketDataViewModel, INotifyPropertyChanged
{
.....
private ObservableCollection<IMarketDataViewModel> items;
public ObservableCollection<IMarketDataViewModel> Items
{
get { return items; }
set
{
items = value;
OnPropertyChanged("Items"); //Add this line fix my issue
}
}
}