1
votes

I'm having a problem when dynamically adding a DataTrigger to an existing element.

If I hard-code it in MainWindow.XAML like this it works fine:

In App.Xaml:

...
<Application.Resources>
    <ControlTemplate x:Key="MyTemplate">
        <TextBox AcceptsReturn="True" AcceptsTab="True" AllowDrop="True" Text="{Binding Content}"/>
    </ControlTemplate>
</Application.Resources>
...

In MainWindow.XAML:

...
<DataTemplate>
    <Control x:Name="ViewPlaceHolder" Template="{StaticResource ViewPlaceHolderTemplate}" />
    <DataTemplate.Triggers>
        <DataTrigger Binding="{Binding TypeName}" Value="MyViewModelName">
            <Setter TargetName="ViewPlaceHolder" Property="Template" Value="{StaticResource MyTemplate}" />
        </DataTrigger>
    </DataTemplate.Triggers>
</DataTemplate>
...

But if I create the DataTrigger in code behind as follows:

...
    DataTrigger tr = new DataTrigger();
    Binding b = new Binding();
    b.Path = new PropertyPath("TypeName");
    tr.Value = triggerValue;
    tr.Binding = b;
    Setter st = new Setter(Control.TemplateProperty, "{StaticResource MyTemplate}");
    st.TargetName = "ViewPlaceHolder";
    tr.Setters.Add(st);
    myDataTemplate.Triggers.Add(tr);
...

I get the following error during binding (there is no error when I add the trigger to the template and using XamlWriter.Write(myDataTemplate) shows its been added to the DataTemplate properly):

'StaticResource MyTemplate' is not a valid value for the 'System.Windows.Controls.Control.Template' property on a Setter.

I have to load the Trigger at runtime because it (triggerValue) comes from an dynamically loaded plugin. If I add the ControlTemplate directly to the Setter instead of referencing it as a StaticResource it also works fine but I don't like the idea of having to load the same ControlTemplate on every page/window where I might need it.

Any idea of how I can get the Setter in the DataTrigger to reference the resource if I add it from Code behind?

1

1 Answers

2
votes

You are trying to set the value of the Template property to the actual literal string "{StaticResource MyTemplate}".

You need to look up the resource instance using something like this:

var myTemplate = Application.Current.TryFindResource("MyTemplate") as ControlTemplate;
// Do something appropriate if myTemplate is null
Setter st = new Setter(Control.TemplateProperty, myTemplate);