在WPF UserControl中公开控件的属性

时间:2012-10-08 23:49:58

标签: wpf dependency-properties

我有一个usercontrol,里面有一个网格控件

 <UserControl x:Class="MyGrid">
      <Telerik:RadGridView EnableRowVirtualization="false"> 
     </Telerik:RadGridView/>
 </UserControl>

如何使用DependencyProperty公开usercontrol中控件的EnableRowVirtualization属性,以便当有人使用MyGrid用户控件时,用户将执行类似这样的操作

  <grids:MyGrid  EnableRowVirtualization="false"> </grids:MyGrid>

更新:现在,这就是我的目标

 public partial class MyGrid //myGrid userControl
 {
    public bool EnableRowVirtualization
    {
        get { return (bool)GetValue(EnableRowVirtualizationProperty); }
        set { SetValue(EnableRowVirtualizationProperty, value); }
    }

    // Using a DependencyProperty as the backing store for EnableRowVirtualization.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty EnableRowVirtualizationProperty =
        DependencyProperty.Register("EnableRowVirtualization", typeof(bool), typeof(MaxGridView), new UIPropertyMetadata(false, OnEnableRowVirtualizationPropertyChanged)
     );


    private static void OnEnableRowVirtualizationPropertyChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
    {
        var grid = (RadGridView)depObj;

        if (grid != null)
        {
            grid.EnableRowVirtualization = (bool)e.NewValue;
        }
    }

1 个答案:

答案 0 :(得分:1)

如果为Telerik网格指定名称,则可以从依赖项属性的代码中访问它。如果在定义依赖项属性时也将它与PropertyChanged属性元数据组合在一起,那么您可以简单地将值传递到底层网格。

这只是我的头脑,但这样的事情应该可以解决问题:

public static readonly DependencyProperty EnableRowVirtualizationProperty =
    DependencyProperty.Register("EnableRowVirtualization"
    , typeof(bool)
    , typeof(MyGrid)
    , new UIPropertyMetadata(false, OnEnableRowVirtualizationPropertyChanged) 
    );


private static void OnEnableRowVirtualizationPropertyChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
{
    var myGrid = depObj as MyGrid;
    if (myGrid != null)
    {
        myGrid.InnerTelerikGrid.EnableRowVirtualization = e.NewValue;
    }
}

有关详细信息,请查看DependencyProperty.RegisterAttached Method (String, Type, Type, PropertyMetadata)UIPropertyMetadata Constructor (Object, PropertyChangedCallback)