Adam Jachocki
Adam Jachocki

Reputation: 2125

Custom control and additional style in generic.xaml for it

I have created custom control and a default style for it.

My XAML is simple:

<Style TargetType="{x:Type local:MyControl}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate>
                <Border CornerRadius="10" BorderThickness="1" Background="Transparent" BorderBrush="Black"/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

I connect to this style using DefaultStyleKey:

DefaultStyleKey = typeof(MyControl);

And it works. But now I want to create other style for my control. It's because my control can have some modes defined as enums, like:

public enum ControlMode
{
    Mode1,
    Mode2
}

Now, when my control is in Mode1 I want it to have its default style. But when it's in Mode2 I want it to have another style, like:

<Style TargetType="{x:Type local:MyControl}" x:Key"styleForMode2>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate>
                <Border BorderThickness="1" Background="White" BorderBrush="Black"/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

How can I achieve that? DefaultStyleKey works only for type name, so the only thing I came up with is to create another class for my control: MyControlWithMode2. But I'm sure there is more proper way. Right?

(this is library not an application, so I cannot use application's resources)

Upvotes: 0

Views: 69

Answers (1)

Clemens
Clemens

Reputation: 128013

Assuming your control has a Mode property, the default Style could declare Triggers to set different ControlTemplates for different modes:

<Style TargetType="local:MyControl">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate>
                <Border CornerRadius="10" BorderThickness="1"
                        Background="Transparent" BorderBrush="Black"/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="Mode" Value="Mode2">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate>
                        <Border BorderThickness="1" Background="White"
                                BorderBrush="Black"/>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Trigger>
    </Style.Triggers>
</Style>

Upvotes: 2

Related Questions