2009-11-18 33 views
2

我有一個datagrid,我在其中使用DataGridTemplateColumn和DataGridTextColumn。 我想在運行時訪問這些列,因此我已將x:Name屬性分配給它們。 但我沒有在代碼後面獲得該值,所以我查找了DataGrid,然後通過遍歷DataGrid.Columns讀取對象。我如何閱讀C#中的對象的名稱屬性?如何訪問x:代碼隱藏的名稱?

我需要這個在運行時對特定列執行一些特定的操作。

回答

1

datagrid列未添加到可視化樹中。 (所以也許你不能在後面的代碼中訪問它) - 請參閱可視化佈局上的blog

您可以查看標題屬性,或者您可以派生和添加自己的屬性來唯一標識列。這就是我所做的,我發現這些專欄有點香草,並且爲不同的用途衍生出了一些。

+0

但是,如果你確實讓他們閱讀x:代碼中的名字並不容易,s ee [如何在代碼中訪問x:Name屬性 - 對於非FrameworkElement對象?](http://stackoverflow.com/a/7172430/575530) – dumbledad

+0

一旦你開始行走視覺樹,就會遇到麻煩,將反射添加到它可以很快得到混亂。 –

1

另一種方法是定義一個附加屬性:在XAML

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

1)推導一類新的從數據網格與附加屬性

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)設置丙3)讀取值

+0

這是非常好的解決方案,並不是很明顯 – deafsheep

相關問題