【发布时间】:2010-01-26 22:28:31
【问题描述】:
我正在尝试添加自己的 ItemsSource 以向图表提供 GraphViewModel 列表。我认为我的做法不太正确,因为当我创建第一个 GraphViewModel 并将其添加到图表时,我的 DP 已更新,但未调用 OnGraphsCollectionChanged。
这应该如何工作?如果我通过绑定到命令的按钮将图表添加到我的 VM 属性,那么一切都很好。
这是 DP 代码,谁能解释它应该如何工作或我在初始化期间显示我的数据做错了什么?
public static readonly DependencyProperty GraphsProperty =
DependencyProperty.Register("ItemsSource",
typeof(ObservableCollection<GraphViewModel>),
typeof(DynamicPlotter),
new FrameworkPropertyMetadata(new PropertyChangedCallback(ChangeGraphs)));
public ObservableCollection<GraphViewModel> ItemsSource
{
get { return (ObservableCollection<GraphViewModel>)GetValue(GraphsProperty); }
set
{
SetValue(GraphsProperty, value);
ItemsSource.CollectionChanged += new NotifyCollectionChangedEventHandler(OnGraphsCollectionChanged);
}
}
public static void ChangeGraphs(DependencyObject source, DependencyPropertyChangedEventArgs eventArgs)
{
(source as DynamicPlotter).UpdateGraphs((ObservableCollection<GraphViewModel>)eventArgs.NewValue);
}
private void UpdateLineGraphs(ObservableCollection<GraphViewModel> grphs)
{
this.ItemsSource = grphs;
}
private void OnGraphsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
// This never gets called when you set the ItemsSource, but is where all the work is done
}
【问题讨论】:
标签: wpf mvvm dependency-properties