如何以编程方式访问数据网格行详细信息控件

10

我有一个带有一些定义列和行详细信息模板的数据网格。在代码后台中如何访问行详细信息模板中的控件?我有一个想要以编程方式启用/禁用的按钮,但我无法弄清楚如何在代码后台中访问它。我在MSDN上看到了这个:

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

但那只是描述一个常规的数据模板,所以当我尝试时它并没有起作用。我的情况是行细节数据模板。肯定有人已经编写了访问数据网格行详细信息模板中控件的代码,可以对此进行评论(非常感谢)。
3个回答

9

好的,我找到了如何让它工作的方法。我必须调整原始问题中发布在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是与我的DataGrid相关联的变量。请注意,在调用FindVisualChild时,我使用了一个DataGridDetailsPresenter类,而不是ContentPresenter(这是关键...它强制FindVisualChild方法迭代所有内容呈现器,直到我找到行细节的那个)。


在WPF中没有FindVisualChild方法... - Lei

4
使用DataGrid.LoadingRowDetails事件!这更加直接简单。
我在这里找到了这个方法: 如何更改位于每个DataGrid行详细信息的DataTemplate中的TextBlock的文本? 示例:
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";
    }
}

我知道这是老问题,但这应该是被接受的答案! - Nandostyle

1

你能定义一个类型或者已经存在的属性,来表示在网格中显示的对象的启用状态吗?如果可以的话,那么修改行详细模板以将按钮的IsEnabled属性与该属性绑定将会更简单。


是的,在我的视图模型中,我可以在用于数据网格的类中拥有一个属性。所以这是一种方法。我刚刚也找到了如何在代码后台类中实现它。我会将其作为独立答案发布。感谢您的回复! - BrianP

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接