如何在wpf用户控件上创建DataSource依赖项属性

时间:2009-06-05 20:09:21

标签: c# wpf

我有一个包装网格的用户控件。我希望能够设置底层网格的数据源,但是通过用户控件,如下所示:

<my:CustomGrid DataSource="{Binding Path=CollectionView}" />

我已经在网格中设置了这样:

    private static readonly DependencyProperty DataSourceProperty 
        = DependencyProperty.Register("DataSource", typeof(IEnumerable), typeof(CustomGrid));

    public IEnumerable DataSource
    {
        get { return (IEnumerable)GetValue(DataSourceProperty); }
        set
        {
            SetValue(DataSourceProperty, value);
            underlyingGrid.DataSource = value;
        }
    }

但这不起作用(它也没有给我一个错误)。永远不会设置数据源。我错过了什么?

2 个答案:

答案 0 :(得分:8)

当WPF加载您的控件并遇到XAML中指定的DependencyProperty时,它使用DependencyObject.SetValue来设置属性值而不是类的属性。这使得作为依赖属性的属性设置器中的自定义代码几乎无用。

你应该做的是覆盖OnPropertyChanged方法(来自DependencyObject):

    protected override void OnPropertyChanged( DependencyPropertyChangedEventArgs e ) {
        base.OnPropertyChanged( e );

        if( e.Property == DataSourceProperty ) {
            underlyingGrid.DataSource = e.NewValue;
        }
    }

或者,您可以在注册DependencyProperty时指定回调:

    public static readonly DependencyProperty DataSourceProperty =
        DependencyProperty.Register( "DataSource", typeof( IEnumerable ), typeof( MyGridControl ), new PropertyMetadata( DataSourceChanged ) );

并且在回调中的OnPropertyChanged中实现与上面相同的效果:

    public static void DataSourceChanged( DependencyObject element, DependencyPropertyChangedEventArgs e ) {
        MyGridControl c = (MyGridControl) element;
        c.underlyingGrid.DataSource = e.NewValue;
    }

答案 1 :(得分:1)

这没关系:

  public static readonly DependencyProperty ItemsSourceProperty =
            DependencyProperty.Register("ItemsSource", typeof(IList), typeof(YourControl),
            newFrameworkPropertyMetadata(null,FrameworkPropertyMetadataOptions.AffectsArrange,new PropertyChangedCallback(OnIsChanged)));

 private static void OnIsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            YourControl c = (YourControl)d;
            c.OnPropertyChanged("ItemsSource");
        }

 public IList ItemsSource
        {
            get
            {
                return (IList)GetValue(ItemsSourceProperty);
            }
            set
            {
                SetValue(ItemsSourceProperty, value);
            }
        } 

问题在于: 当你设置

MyGridControl c = (MyGridControl) element;
c.underlyingGrid.DataSource = e.NewValue;

您设置了值,但删除了绑定!