C# 使用ObservableCollection进行WinRT数据绑定
在我的ViewModel中,我定义了以下C# 使用ObservableCollection进行WinRT数据绑定,c#,data-binding,windows-runtime,winrt-xaml,dependency-properties,C#,Data Binding,Windows Runtime,Winrt Xaml,Dependency Properties,在我的ViewModel中,我定义了以下observateCollection private readonly ObservableCollection<ChartSerie> _seriesData = new ObservableCollection<ChartSerie>(); public ObservableCollection<ChartSerie> SeriesData { get { return _s
observateCollection
private readonly ObservableCollection<ChartSerie> _seriesData = new ObservableCollection<ChartSerie>();
public ObservableCollection<ChartSerie> SeriesData
{
get { return _seriesData; }
}
ItemSource是我控件中的DependencyProperty
public object ItemSource
{
get { return (object)GetValue(ItemSourceProperty); }
set { SetValue(ItemSourceProperty, value); }
}
public static readonly DependencyProperty ItemSourceProperty =
DependencyProperty.Register("ItemSource", typeof(object), typeof(MultipleColumnChart), new PropertyMetadata(null, OnItemSourceChanged));
控件继承自网格。我已将OnItemSourceChanged
定义如下
private static void OnItemSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var chart = d as MultipleDoubleColumnChart;
foreach (var serie in (IList)chart.ItemSource)
{
var child = new ColumnChart();
...
...
}
}
创建页面和视图模型时,序列数据集合为空,对OnItemSourceChanged
的第一次也是唯一一次调用不会执行任何操作(如预期)。在页面上单击某个按钮后,数据被加载,新的ChartSerie对象被创建并添加到SeriesData
虽然
SeriesData
是一个observecollection
方法,但不再调用onimsourcechanged
方法
发生了什么/出现了什么问题以及需要更改什么才能调用OnItemSourceChanged?
ObservableCollection
不会强制调用OnItemSourceChanged
。在标准的ItemsControl
中,它会激发onitmchanged
。您需要做的是将ItemSource
强制转换为INotifyCollectionChanged
(当设置属性时),然后(如果它不为null)将事件处理程序添加到CollectionChanged
。这将在数据更改时触发。好的,我在OnItemSourceChanged中有这样的内容:var source=(System.Collections.Specialized.INotifyCollectionChanged)chart.ItemSource;source.CollectionChanged+=source\u CollectionChanged
Source\u CollectionChanged
是静态的。我如何访问像“OnItemSourceChange”参数->DependencyObject d
中那样的非静态方法?通常,我不会在OnItemSourceChanged
中设置CollectionChanged
;我在ItemSource
的setter方法中设置它。这样,Source\u CollectionChanged
就不是静态的了。如果仍要按原样使用,可以对方法接收的sender
参数设置大小写,类似于将d转换为MultipleDoubleColumnChart
的方式。
private static void OnItemSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var chart = d as MultipleDoubleColumnChart;
foreach (var serie in (IList)chart.ItemSource)
{
var child = new ColumnChart();
...
...
}
}