C# 如何在wpf用户控件上创建DataSource dependency属性

C# 如何在wpf用户控件上创建DataSource dependency属性,c#,wpf,C#,Wpf,我有一个包装网格的用户控件。我希望能够设置底层网格的数据源,但通过用户控件,如下所示: <my:CustomGrid DataSource="{Binding Path=CollectionView}" /> private static readonly DependencyProperty DataSourceProperty = DependencyProperty.Register("DataSource", typeof(IEnumerable)

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

<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;
        }
    }

但这不起作用(它也不会给我一个错误)。从未设置数据源。我缺少什么?

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

您应该做的是重写该方法(从DependencyObject):

或者,您可以在注册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;
    }
这没关系:

  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;
您设置了值,但删除了绑定

+1另一个选项(cleaner,IMHO)是仅从XAML绑定。在声明网格的UserControl中,执行如下操作
MyGridControl c = (MyGridControl) element;
c.underlyingGrid.DataSource = e.NewValue;