I have this TabControl
<TabControl
x:Name="TabControl"
ItemTemplate="{StaticResource MyTemplate}">
<TabControl.Resources>
<DataTemplate x:Key="MyTemplate">
<TextBlock
Width="80"
Height="25"
FontWeight="Bold"
Text="{Binding Header}" />
</DataTemplate>
<DataTemplate DataType="{x:Type objects:LivingBeing}">
...
</DataTemplate>
<DataTemplate DataType="{x:Type objects:Thing}">
...
</DataTemplate>
</TabControl.Resources>
</TabControl>
I set TabControl.ItemsSource = list; and The parent of each object in this list has Header variable and I want to programmatically set the title of each tab but it gives me error: "Cannot find resource named 'MyTemplate'. Resource names are case sensitive."
But the spelling is correct, how to fix this please?
CodePudding user response:
You should define the StaticResource before the control, not inside it!
Or use DynamicResource
Replace
ItemTemplate="{StaticResource MyTemplate}"
With
ItemTemplate="{DynamicResource MyTemplate}"
Note: For better performance, better to avoid DynamicResource wherever possible, so if there is no reason to use DynamicResource, go and define the resource for TabControl in one of its parents, for example:
<UserControl>
<UserControl.Resources>
<DataTemplate x:Key="MyTemplate">
<TextBlock
Width="80"
Height="25"
FontWeight="Bold"
Text="{Binding Header}" />
</DataTemplate>
</UserControl.Resources>
<TabControl
x:Name="TabControl"
ItemTemplate="{StaticResource MyTemplate}">
<TabControl.Resources>
<DataTemplate DataType="{x:Type objects:LivingBeing}">
...
</DataTemplate>
<DataTemplate DataType="{x:Type objects:Thing}">
...
</DataTemplate>
</TabControl.Resources>
</TabControl>
</UserControl>
To know more, Read this on StaticResource vs. DynamicResource.
