DataTemplate, LoadContent, and DataTriggers do not fire

I have a custom UserControl that has a DependencyProperty "ItemTemplate" of type "DataTemplate". I instantiate this ItemTemplate via .LoadContent (), assign .DataContext, and put it in ContentControl. The only drawback that I have is that DataTemplate.Triggers do not start.

Xaml example code:

<Window.Resources>
    <DataTemplate x:Key="MyTemplate">
        <Label Name="MyLabel" Content="Default"/>
        <DataTemplate.Triggers>
            <DataTrigger Binding="{Binding}" Value="1">
                <Setter TargetName="MyLabel" Property="Content" Value="True" />
            </DataTrigger>
            <DataTrigger Binding="{Binding}" Value="0">
                <Setter TargetName="MyLabel" Property="Content" Value="False" />
            </DataTrigger>
        </DataTemplate.Triggers>
    </DataTemplate>        
</Window.Resources>

<ContentControl x:Name="MyContent" />

Code example:

private void Window_Loaded(object sender, RoutedEventArgs e) {
    var template = FindResource("MyTemplate") as DataTemplate;

    var instance = template.LoadContent() as FrameworkElement;
    instance.DataContext = "1";
    MyContent.Content = instance;
}

The output is "Default."

The same DataTemplate used in the ListBox works fine:

<ListBox x:Name="MyListBox" ItemTemplate="{StaticResource MyTemplate}" />

Code for:

MyListBox.ItemsSource = new[] { "1", "0" };

The output is "True" and "False".

Any ideas on starting DataTemplate.Triggers? Do I need to manually run all the triggers cyclically and execute them? If so, how can I evaluate the trigger?

Thanks in advance,

Christian

+3
1

DataTemplate ContentControl , , :

MyContent.ContentTemplate = FindResource("MyTemplate") as DataTemplate;
MyContent.Content = "1";
+3

Source: https://habr.com/ru/post/1715231/


All Articles