views:

479

answers:

1

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

+1  A: 

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

HTH, Kent

Kent Boogaart
Yeah, that did the trick (one little type, you meant MyContent.Content = "1" (or "0")). Thanks!
Christian Birkl
Yep, fixed type - thanks.
Kent Boogaart