Question

I am trying to switch ControlTemplate of Button in Style.

<Style TargetType="Button">
      <Style.Triggers>
          <DataTrigger Binding="{Binding Path=TestProperty}" Value="true">
                <Setter Property="Template" Value="{StaticResource MyCustomTemplate}"/>
           </DataTrigger>
       </Style.Triggers>
</Style>

It's working fine until I change button's template in code. For example,

myButton.Template = someTemplate;

Even this is enought to reproduce a bug:

myButton.Template = myButton.Template;

By the way the following code will correctly change myButton foregound to Aqua. It means that trigger is working fine. Its just can not set Template

<Style TargetType="Button">
    <Style.Triggers>
        <DataTrigger Binding="{Binding Path=TestProperty}" Value="true">
            <Setter Property="Template" Value="{StaticResource MyCustomTemplate}"/>
            <Setter Property="Foreground" Value="Aqua"></Setter>
        </DataTrigger>
    </Style.Triggers>
</Style>

Why is this happening?

Was it helpful?

Solution

As was mentioned in comments for the question, using MVVM and changing controls in code behind is a bad idea.

Your behavior should define a boolean attached property, let's call it IsInEditMode. Then, instead of setting the template directly, set the value of the attached property to true. In your styles/templates add triggers to change templates (or set visibility for parts of the template) depending on the value of IsInEditMode.

This way you'll have ability to react to all combinations of properties (IsInEditMode && TestProperty; IsInEditMode && !TestProperty; etc...)

Also, you'll be able to use the behavior on other controls.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top