【问题标题】:How to pass reference of an control to another control in XAML如何将控件的引用传递给 XAML 中的另一个控件
【发布时间】:2010-11-14 23:47:21
【问题描述】:

我需要将控件的引用传递给另一个自定义控件。 我创建了一个自定义控件,其中包含一个依赖属性associateDatagridProperty

    public static readonly DependencyProperty
        AssociatedDataGridProperty = DependencyProperty.Register(
            "AssociatedDatagrid",
            typeof(DataGrid),
            typeof(CustomControl),
            new FrameworkPropertyMetadata(null,
                FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)
            );

    public Datagrid AssociatedDatagrid
    {
        get { return (Datagrid )base.GetValue(AssociatedDataGridProperty); }
        set { base.SetValue(AssociatedDataGridProperty, value); }
    }

在 XAML 中我像这样分配值

<Datagrid x:name=ClientGrid />

这里的Datagrid是Microsoft WPF工具包datagrid

<CustomControl x:Name="DatagridPaging"  
               Canvas.Left="24"    
               Canvas.Top="236"
               AssociatedDatagrid="{Binding ElementName=clientsGrid ,Path=Name}">

当我尝试访问 AssociatedDatagrid 属性的值时,它总是显示 null

谁能告诉我正确的做法?

【问题讨论】:

    标签: wpf data-binding controls


    【解决方案1】:

    代码如下:

    将在第二个元素中引用的第一个元素:

    <Label x:Name="aGivenNameLabel" Content="kikou lol"/>  
    

    第二个元素:

    <ContentControl Content={Binding ElementName=aGivenNameLabel}" />
    

    祝你好运!

    【讨论】:

      【解决方案2】:

      您的Binding 中不需要Path=Name。你最终在这里做的是传递DataGridName 属性的值。

      【讨论】:

      • 我不会发布另一个答案(因为我同意),我只是在这里添加一个注释,以防仍然存在混淆。主要是,在幕后,Binding 正在尝试执行以下操作: AssociatedDatagrid = (clientsGrid.Name as Datagrid);这将是空的。
      猜你喜欢
      • 1970-01-01
      • 2018-01-19
      • 2010-09-23
      • 1970-01-01
      • 1970-01-01
      • 2010-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多