繁体   English   中英

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

[英]How to create DataSource dependency property on a wpf User Control

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

<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来设置属性值而不是类的属性。 这使得作为依赖属性的属性设置器中的自定义代码几乎无用。

你应该做的是覆盖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;
    }

还行吧:

  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;

你设置了值,但删除你的绑定!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM