Search code examples
c#wpftriggersruntimecode-behind

Modify Style (add a trigger) dynamically on runtime


I want to add some graphic items on runtime in my object of my WPF application. My goal is to add a circle around my button (only by codebehind on runtime) and to add a trigger to my ControlTemplate.

Everything is fine, my circle around my button shows up BUT my problem is: I cannot create any trigger, it says:

After a 'TriggerCollection' is in use (sealed), it cannot be modified.

What I understand is I cannot modify a Style when it's rendered or used by something else. I tried to copy the Style to modify the new one but I can't access to the trigger.

My object is like this:

<Style x:Key="Button_1" TargetType="{x:Type MyDLL:MyObject}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type MyDLL:MyObject}">
                <Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="190" Height="140">
                    ....
                </Grid>
                <ControlTemplate.Triggers>
                    <Trigger Property="Property1" Value="True">
                        <Setter.../>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

If I copy my Style to a new style, how can I add the trigger into the ControlTemplate?

If I copy my ControlTemplate to a new ControlTemplate, the new one is also sealed.

My code behind to create my trigger is:

Trigger trigger = new Trigger { Property = DragModeProperty, Value = false };
Setter setter = new Setter { Property = VisibilityProperty, Value = Visibility.Collapsed, TargetName = "DRAG" };
trigger.Setters.Add(setter);
Template.Triggers.Add(trigger); // THIS ONE CAUSE THE ERROR

Solution

  • Found it. I just create my trigger on a new container (Grid) instead of on my Button. Simple.