我有一个带有对象集合的自定义 WPF UserControl。
public class MyUserControl : UserControl
{
public readonly static DependencyProperty PointsSourceProperty =
DependencyProperty.Register("PointsSource", typeof(IEnumerable), typeof(MyUserControl), new FrameworkPropertyMetadata(null, OnPointsSourceChanged));
public IEnumerable PointsSource
{
get { return GetValue(PointsSourceProperty) as IEnumerable; }
set { SetValue(PointsSourceProperty, value); }
}
private ObservableCollection<DataPoint> _points = new ObservableCollection<DataPoint>();
public ObservableCollection<DataPoint> Points
{
get { return points; }
}
private static void OnPointsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// Expect to update Points collection
}
}
public class DataPoint : DependencyObject
{
public readonly static DependencyProperty TimeProperty =
DependencyProperty.Register("Time", typeof(DateTime), typeof(DataPoint));
public readonly static DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(double), typeof(DataPoint));
public DateTime Time
{
get { return (DateTime)GetValue(DateTimeProperty); }
set { SetValue(DateTimeProperty, value); }
}
public double Value
{
get { return (double)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
}
我这样定义我的控件,其中 Data 是视图模型中的可观察集合:
<my:myUserControl PointsSource="{Binding Data}">
<my:myUserControl.Points>
<my:Point Time="{Binding TimeUtc}" Value="{Binding Value}" />
</my:myUserControl.Points>
</my:myUserControl>
如何在PointsSource值更改时更新Points集合?