2010-08-10 40 views
9

我有一個數據網格,其中包含一些已定義的列,然後是一個行詳細信息模板。如何在後面的代碼中訪問行詳細信息模板中的控件?我有一個我想以編程方式啓用/禁用的按鈕,但我無法弄清楚如何在後面的代碼中訪問它。我已經看到了這個在MSDN:如何以編程方式訪問數據網格行詳細信息控件

http://msdn.microsoft.com/en-us/library/bb613579.aspx

但是這只是描述常規數據模板,所以當我試過,沒有奏效。我的情況是一個行詳細數據模板。當然有人編寫代碼來訪問可以對此進行評論的DataGrid行詳細信息模板中的控件(非常感謝)。

回答

7

好吧,我想通了,如何得到這個工作,我不得不調整被張貼在原來的問題是MSDN本文中的代碼....

DataGridRow row = (DataGridRow)(KeywordsGrid.ItemContainerGenerator.ContainerFromItem(KeywordsGrid.SelectedItem)); 

// Getting the ContentPresenter of the row details 
DataGridDetailsPresenter presenter = FindVisualChild<DataGridDetailsPresenter>(row); 

// Finding Remove button from the DataTemplate that is set on that ContentPresenter 
DataTemplate template = presenter.ContentTemplate; 
Button button = (Button)template.FindName("RemoveItemButton", presenter); 

「KeywordsGrid」是聯繫在一起的變量我的數據網格。請注意,在我調用FindVisualChild時,我使用的是「DataGridDetailsPresenter」類而不是「ContentPresenter」(這是關鍵...它強制FindVisualChild方法遍歷所有內容演示者,直到我到達一個爲行細節)。

1

您可以定義(或者確實存在)一個屬性,用於表示按鈕的啓用狀態的網格中顯示的對象的類型?如果是,那麼修改行詳細模板以將按鈕的IsEnabled屬性綁定到該屬性會更簡單。

+0

是的,在我的視圖模型,我可以在一個屬性用於數據網格的類。所以這是一個辦法。我只是想出瞭如何在類的代碼中做到這一點。我將把它作爲一個單獨的答案發布。感謝您的答覆! – BrianP 2010-08-10 21:11:27

1

使用DataGrid.LoadingRowDetails事件!這非常直截了當。

我發現這個在這裏: How to change Text of TextBlock which is in DataTemplate of Row Details for each DataGrid Row Details?

例子:

XAML

<DataGrid.RowDetailsTemplate> 
    <DataTemplate> 
     <TextBlock x:Name="Test">Test</TextBlock> 
     </DataTemplate> 
</DataGrid.RowDetailsTemplate> 

C#

private void dgVehicles_LoadingRowDetails(object sender, DataGridRowDetailsEventArgs e) 
{ 
    TextBlock tbTest = e.DetailsElement.FindName("Test") as TextBlock; 
    if (tbTest != null) 
    { 
     tbTest.Text = "Juhuu"; 
    } 
} 
相關問題