Search code examples
c#wpfdatatemplateresourcedictionary

How to toggle between two DataTemplates in Code behind


I have a ResourceDictionary that has two DataTemplates. Each template has a stackpanel with an object.

In my code behind based on a conditionm I get from elsewhere, I want to embed one of those stackpanel's into a placeholder grid. Seems easy enough except I have an ItemClick event that demands a x:class or something.

//toggle.xaml
<ResourceDictionary .....>

   <DataTemplate x:Key="A">
     <StackPanel>
       ..Tab control with certain tabs with a button with a click event
     </StackPanel>
   </DataTemplate>

   <DataTemplate x:Key="B">
     <StackPanel>
       ..Tab control with with certain button with a click event
     </StackPanel>
   </DataTemplate>

</ResourceDictionary>
//in MainWindow.cs

<Window.....>
  <Window.Resources>
     <ResourceDictionary Source ="/toggle.xaml"
  </Window.Resources>

  <Grid x:Name="myGrid" />
  
</Window>
//in my MainWindow.xaml.cs code behind

var dictionary = (ResourceDictionary)Application.LoadComponent("/toggle.xaml", UriKind.Relative));
String key = "A";

if (certainConditionExists)
{
   key = "B";
}

var template = (DataTemplate)dictionary[key];
var panel = (StackPanel)template.Resources[key];
myGrid.Children.Add(panel);

Error: 'ResourceDictionary' root element requires a x:Class attribute to support event handlers in the XAML file


Solution

  • Actually I was doing way more than I had too. I realized all I had to do was collapse the tab header in one case and display them in another. So I didn't even need two DataTemplates or a datatemplate selector. Just need one Window with a tab control and and a way to collapse the tab headers if needed.