Gaining control over a DataGridCell

Assuming I have an arbitrary control inside a DataGridTemplateColumn, I want to know how to get the control, given that I got a DataGridCell that contains this control.

My XAML file containing the DataGrid looks like this:

<DataGrid Name="dgMovement"> ... <DataGridTemplateColumn Header="Target %"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <vi:PercentageEditor Value="{Binding TargetPercentage, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="100px" cal:Message.Attach="[Event PreviewLostKeyboardFocus] = [Action ChangeTargetPercentage];[Event PreviewGotKeyboardFocus] = [Action OnFocus]" Name="aa" /> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn>... 

I extracted the DataGridCell using extension methods as follows:

 DataGridCell cell = view.dgMovement2.GetCell(index, 6); 

Extension methods contained in a static class are found here.

The question is, how do I get a "PercentageEditor" once I get a DataGridCell? Can anybody help me? Any help would be greatly appreciated. Thanks!

+7
source share
1 answer

You can use the name of the control to find it in the template, for example.

 <DataGridTemplateColumn> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <uc:Bogus x:Name="root" ItemsSource="{Binding Machines}"/> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> 
 var cell = dataGrid.GetCell(5, 0); var cp = (ContentPresenter)cell.Content; var bogus = (Bogus)cp.ContentTemplate.FindName("root", cp); 

Note that this is usually not necessary, since changing the template controls for the most part can be done using data binding, attached properties, and events alone. In general, I would restrict template access through code to user controls (which often have labeled parts ).

+11
source

All Articles