我有一个带有一些定义列和行详细信息模板的数据网格。在代码后台中如何访问行详细信息模板中的控件?我有一个想要以编程方式启用/禁用的按钮,但我无法弄清楚如何在代码后台中访问它。我在MSDN上看到了这个:
但那只是描述一个常规的数据模板,所以当我尝试时它并没有起作用。我的情况是行细节数据模板。肯定有人已经编写了访问数据网格行详细信息模板中控件的代码,可以对此进行评论(非常感谢)。我有一个带有一些定义列和行详细信息模板的数据网格。在代码后台中如何访问行详细信息模板中的控件?我有一个想要以编程方式启用/禁用的按钮,但我无法弄清楚如何在代码后台中访问它。我在MSDN上看到了这个:
但那只是描述一个常规的数据模板,所以当我尝试时它并没有起作用。我的情况是行细节数据模板。肯定有人已经编写了访问数据网格行详细信息模板中控件的代码,可以对此进行评论(非常感谢)。好的,我找到了如何让它工作的方法。我必须调整原始问题中发布在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
方法迭代所有内容呈现器,直到我找到行细节的那个)。
<DataGrid.RowDetailsTemplate>
<DataTemplate>
<TextBlock x:Name="Test">Test</TextBlock>
</DataTemplate>
</DataGrid.RowDetailsTemplate>
private void dgVehicles_LoadingRowDetails(object sender, DataGridRowDetailsEventArgs e)
{
TextBlock tbTest = e.DetailsElement.FindName("Test") as TextBlock;
if (tbTest != null)
{
tbTest.Text = "Juhuu";
}
}
你能定义一个类型或者已经存在的属性,来表示在网格中显示的对象的启用状态吗?如果可以的话,那么修改行详细模板以将按钮的IsEnabled属性与该属性绑定将会更简单。