I'm trying to switch the template for a datagrid based on certain conditionals, but even though I define a template, the program does not compile, saying my window doesn't contain a definition for said template.
XAML
<ControlTemplate TargetType="DataGrid" x:Name="myGrid">
<DataGrid>
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding ID}"></DataGridTextColumn>
<DataGridTextColumn Header="Tag" Binding="{Binding Tag}"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</ControlTemplate>
C#
if (mybool == true)
scrollWin.gridMain.Template = scrollWin.myGrid;
This seemed like a "just restart Visual Studio" issue, but that didn't help. I don't get any errors before trying to run the program, hovering over "myGrid" shows that it recognizes it as a member of scrollWin. Any ideas?
The ControlTemplate
should be defined as a resource with an x:Key
instead of an x:Name
:
<ControlTemplate TargetType="DataGrid" x:Key="myGrid">
If you then put in the Resources
dictionary (<Grid.Resources>
or whatever type grdMain
is) of gridMain
, you could get a reference to it like this:
scrollWin.gridMain.Template = scrollWin.gridMain.Resources["myGrid"] as ControlTemplate;
The definition of the template itself looks a bit odd but that's anothe issue.