Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically access a datagrid row details control

I've got a datagrid with some defined columns and then a row details template. How do I access a control in the row details template within the code behind? I've got a button that I want to programmatically enable/disable, but I can't figure out how to get access to it in the code behind. I've seen this on the MSDN:

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

but that's just describing a regular data template, so when I tried that it didn't work. My case is a row details data template. Surely someone has written code to access a control within a datagrid row details template that can comment on this (Would be much appreciated).

like image 867
BrianP Avatar asked Aug 10 '10 20:08

BrianP


3 Answers

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 content presenters until I got to the one for the row details).

like image 57
BrianP Avatar answered Nov 10 '22 16:11

BrianP


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";
    }
}
like image 21
Martin Meeser Avatar answered Nov 10 '22 15:11

Martin Meeser


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.

like image 35
Daniel Pratt Avatar answered Nov 10 '22 17:11

Daniel Pratt