【问题标题】:How can I access x:Name from Code Behind?如何从 Code Behind 访问 x:Name?
【发布时间】:2009-11-18 13:42:36
【问题描述】:

我有一个数据网格,我在其中使用 DataGridTemplateColumn 和 DataGridTextColumn。 我想在运行时访问这些列,所以我为它们分配了 x:Name 属性。 但是我没有在后面的代码中得到那个值,所以我查找了 DataGrid,然后通过遍历 DataGrid.Columns 来读取对象。如何在 C# 中从该对象读取 x:Name 属性?

我需要它来在运行时对特定列执行一些特定操作。

【问题讨论】:

    标签: wpf datagrid


    【解决方案1】:

    datagrid 列未添加到可视化树中。 (因此,也许您因此无法在后面的代码中访问它) - 请参阅视觉布局上的 vinces blog

    您可以查看标题属性,也可以派生并添加自己的属性来唯一标识列。这就是我所做的,我发现这些列有点普通,并且为不同的用途派生了相当多的列。

    【讨论】:

    【解决方案2】:

    另一种选择是定义附加属性:

    1) 使用附加属性从 DataGrid 派生一个新类

    Public Class FilteringDataGrid
       Inherits DataGrid
    
    
       Public Shared Function GetFilterProp(ByVal element As DependencyObject) As String
          If element Is Nothing Then
             Throw New ArgumentNullException("element")
          End If
    
          Return CStr(element.GetValue(FilterPropProperty))
       End Function
    
       Public Shared Sub SetFilterProp(ByVal element As DependencyObject, ByVal value As String)
          If element Is Nothing Then
             Throw New ArgumentNullException("element")
          End If
    
          element.SetValue(FilterPropProperty, value)
       End Sub
    
       Public Shared ReadOnly FilterPropProperty As  _
                              DependencyProperty = DependencyProperty.RegisterAttached("FilterProp", _
                              GetType(String), GetType(FilteringDataGrid), _
                              New FrameworkPropertyMetadata(Nothing))
    End Class
    

    2) 在Xaml中设置prop

    <dg:DataGridTextColumn local:FilteringDataGrid.FilterProp="ItemName" x:Name="dbcItemName" Header="Item" >
    

    3) 读取值

    【讨论】:

    • 这是一个非常好的解决方案,但不知何故并不那么明显
    猜你喜欢
    • 2019-10-03
    • 2015-12-06
    • 1970-01-01
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多