How to programmatically access a datagrid row details control

江枫思渺然 提交于 2019-12-05 02:08:58

Okay, I figured out how to get this working I had to tweak the code that is posted in that MSDN article in the original question ....

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" is the variable tied to my datagrid. Notice in my call to FindVisualChild, i'm using a "DataGridDetailsPresenter" class instead of a "ContentPresenter" (This was the key ... it forced the FindVisualChild method to iterate all the way through all the contentpresenters until I got to the one for the row details).

Can you define (or does there already exist) a property on the type of object being displayed in the grid that represents the enabled state of the button? If yes, then it would be much simpler to modify the row detail template to bind the button's IsEnabled property to that property.

Martin Meeser

Use the DataGrid.LoadingRowDetails event! It is much more straight forward.

I found this here: How to change Text of TextBlock which is in DataTemplate of Row Details for each DataGrid Row Details?

Example:

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";
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!