Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generating WPF styles containing Triggers from C# code

Tags:

c#

styles

wpf

xaml

i had some trouble generating WPF styles containing Triggers from C# code. Here's the WPF code i want to generate trough C#.

<Style.Triggers>
    <Trigger Property="IsMouseOver" Value="true">
        <Setter Property="BitmapEffect">
            <Setter.Value>
                <OuterGlowBitmapEffect GlowColor="Gold" GlowSize="10" />
            </Setter.Value>
        </Setter>
    </Trigger>
</Style.Triggers>

I alredy tried to generate like this :

Style style = new Style();
Trigger trigger = new Trigger();
Setter setter = new Setter();

style.Triggers.Add(trigger);
trigger.Property = (DependencyProperty.Register("IsMouseOver", Type.GetType("IsMouseOver"), Type.GetType("Canvas"))); //Line not tested
//trigger.Setters.Add(new Setter(new BitmapEffect()); //Line not working

But i could not figure out how to use trigger.Setters with a BitmapEffect

Thanks you in advance!

like image 208
Gab Avatar asked Jun 07 '11 17:06

Gab


1 Answers

The direct translation would be:

OuterGlowBitmapEffect effect = new OuterGlowBitmapEffect();
effect.GlowColor = Colors.Gold;
effect.GlowSize = 10;

Setter setter = new Setter();
setter.Property = UIElement.BitmapEffectProperty;
setter.Value = effect;

Trigger trigger = new Trigger();
trigger.Property = UIElement.IsMouseOverProperty;
trigger.Value = true;
trigger.Setters.Add(setter);

Style style = new Style();
style.Triggers.Add(trigger);

This can be cleaned up to:

var effect = new OuterGlowBitmapEffect() {
    GlowColor = Colors.Gold,
    GlowSize = 10,
};

var setter = new Setter() {
    Property = UIElement.BitmapEffectProperty,
    Value = effect,
};

var trigger = new Trigger() {
    Property = UIElement.IsMouseOverProperty,
    Value = true,
    Setters = { setter },
};

var style = new Style() {
    Triggers = { trigger },
};

But this is based on your coding style.

like image 56
CodeNaked Avatar answered Nov 01 '22 06:11

CodeNaked