2012-07-07 45 views
0

我有一個具有對象集合的自定義WPF UserControl。在更新項目源時更新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); } 
    } 
} 

我定義我的控制是這樣,其中的數據是在視圖模型觀察集合:

<my:myUserControl PointsSource="{Binding Data}"> 
<my:myUserControl.Points> 
    <my:Point Time="{Binding TimeUtc}" Value="{Binding Value}" /> 
</my:myUserControl.Points> 
</my:myUserControl> 

如何更新收集而PointsSource值改變了嗎?

回答

0

試試這個:

private static void OnPointsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
{ 
    MyUserControl control = d as MyUserControl; 

    // you have to replace ViewModelItemClass with the name of your class T 
    // in ObservableCollection<T> from the property Data in your ViewModel 
    var sourceCollection = e.NewValue as IEnumerable<ViewModelItemClass>; 

    control._points.Clear(); 
    foreach (var item in sourceCollection) 
    { 
     control._points.Add(new DataPoint { Time = item.TimeUtc, Value = item.Value }); 
    } 
}