Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataTemplate, LoadContent and DataTriggers not firing

I have a custom UserControl which has a DependencyProperty "ItemTemplate" of type "DataTemplate". I create an instance of this ItemTemplate via .LoadContent(), assign the .DataContext and put it an ContentControl. The only drawback I have is that DataTemplate.Triggers are not fired.

Example Xaml 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" />

Example Code Behind:

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;
}

Output is "Default".

The same DataTemplate used in a ListBox works fine:

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

Code Behind:

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

Output is "True" and "False".

Any ideas how to fire the DataTemplate.Triggers? Do I need to manually cycle over all triggers and execute them? If yes how can I evaluate a trigger?

Thanks in advance,

Christian

like image 676
Christian Birkl Avatar asked Oct 14 '22 14:10

Christian Birkl


1 Answers

Apply your DataTemplate to a ContentControl rather than modifying it on the fly like you are:

MyContent.ContentTemplate = FindResource("MyTemplate") as DataTemplate;
MyContent.Content = "1";
like image 73
Kent Boogaart Avatar answered Oct 20 '22 17:10

Kent Boogaart