开发者

How can I access x:Name from Code Behind?

I have a datagrid in which I am using DataGridTemplateColumn and DataGridTextColumn. I want to access these columns at runtime so I have assigned x:Name property to them. But I was not getting that value in code behind, so I looked for DataGrid and then read objects by iterating through DataGrid.Columns. How can I read x:Name property from that object in C#?

I need this to perform some specific oper开发者_如何学JAVAations with particular columns at runtime.


The datagrid column does not get added to the visual tree. (so maybe you cant access it in the code behind because of this) - see vinces blog on the visual layout.

You can look at the header property, or you could derive and add your own property to uniquely identify the column. That's what I do, I've found the columns a bit vanilla and have derived a fair few for different uses.


Another alternative is to define an attached property:

1) Derive a new class from DataGrid with the attached property

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) Set the prop in Xaml

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

3) Read the value

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜