Изменение значка триггера кнопки WPF

Привет, во-первых, спасибо за любую помощь в указании меня в правильном направлении. У меня есть приложение в WPF, которое начинает вызывать у меня проблемы. Я в порядке с основами, но теперь я углубляюсь в это, становится все сложнее, и я не уверен, что это недостаток знаний или ограничение XAML.

В моем приложении есть RadioButtons, и я использую для этого стиль, чтобы вернуть их как ToggleButtons, используя свойство BasedOn.

Все это прекрасно, в этот стиль включена информация о стиле и триггерные события для OnClick и мыши, над которыми переопределяются действия по умолчанию.

Проблема, с которой я сталкиваюсь, заключается в том, что я хочу иметь возможность менять содержимое (изображение значка), когда переключатель IsChecked.

Для этого я не могу жестко закодировать изображение в стиле, и я не хочу помещать всю эту информацию о стиле для OnClick, MouseOver и т. д. в каждую кнопку.

Я попытался добавить дополнительный стиль в сам RadioButton и основываясь на стиле, который я сейчас использую, но код для этого не обновляет содержимое (изображение значка). Единственный пример, который я могу найти, - это шаблон элемента управления, если я установлю границу внутри шаблона OnChecked, она отобразит границу, но я не уверен, что использую правильное свойство для изменения содержимого переключателя.

Родительский стиль со всеми триггерами выглядит так

<Style x:Key="RadioBtnToolStyle"  BasedOn="{StaticResource {x:Type ToggleButton}}" TargetType="{x:Type RadioButton}">       
    <Setter Property="Background" Value="{x:Null}" />
    <Setter Property="HorizontalAlignment" Value="Center" />
    <Setter Property="Foreground" Value="{x:Null}" />
    <Setter Property="Padding" Value="0" />
    <Setter Property="Margin" Value="3" />
    <Setter Property="BorderBrush" Value="{x:Null}" />          
    <Setter Property="RenderTransform">
        <Setter.Value>
            <ScaleTransform CenterX="30" CenterY="30" ScaleX="1" ScaleY="1" />
        </Setter.Value>
    </Setter>
    <Setter Property="OverridesDefaultStyle" Value="True" />
    <Setter Property="Cursor" Value="Hand" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="RadioButton">
                <Border Name="border" BorderThickness="0" BorderBrush="Black" Background="{TemplateBinding Background}">
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Opacity" Value="0.8" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="IsPressed" Value="True">
            <Trigger.EnterActions>
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation From="1" To="0.8" RepeatBehavior="Forever" AutoReverse="True" Duration="00:00:00.6" Storyboard.TargetProperty="RenderTransform.ScaleX" />
                        <DoubleAnimation From="1" To="0.8" RepeatBehavior="Forever" AutoReverse="True" Duration="00:00:00.6" Storyboard.TargetProperty="RenderTransform.ScaleY" />
                    </Storyboard>
                </BeginStoryboard>
            </Trigger.EnterActions>
            <Trigger.ExitActions>
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation To="1" Duration="00:00:00.6" Storyboard.TargetProperty="RenderTransform.ScaleX" />
                        <DoubleAnimation To="1" Duration="00:00:00.6" Storyboard.TargetProperty="RenderTransform.ScaleY" />
                    </Storyboard>
                </BeginStoryboard>
            </Trigger.ExitActions>
        </Trigger>
    </Style.Triggers>
</Style>

И моя кнопка с моим добавленным стилем в настоящее время выглядит так

<RadioButton GroupName="Tools"  Grid.Row="0" Content="{StaticResource BrightnessContrast}" IsChecked="{Binding IsBrightnessAndContrastEnabled}">                   
                    <RadioButton.Style>                            
                        <Style TargetType="RadioButton" BasedOn="{StaticResource RadioBtnToolStyle}">
                            <Setter Property="OverridesDefaultStyle" Value="True" />
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate TargetType="RadioButton">
                                        <ContentPresenter Content="{StaticResource BrightnessContrast}" HorizontalAlignment="Center" VerticalAlignment="Center" />         
                                        <ControlTemplate.Triggers>
                                            <Trigger Property="IsChecked" Value="True">
                                                <Setter Property="Content" Value="{StaticResource InvertImageBtn}" />
                                            </Trigger>
                                            <Trigger Property="IsChecked" Value="False">
                                                <Setter Property="Content" Value="{StaticResource  LogoFooterBackgroundStyle}" />
                                            </Trigger>
                                        </ControlTemplate.Triggers>
                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </RadioButton.Style>
                </RadioButton>

Я видел один или два примера использования Events, но до сих пор мне удавалось избегать написания чего-либо в моем коде и содержать все это в моей ViewModel, поэтому, если есть способ сделать это в XAMl, это было бы идеально.

Извините, если я объяснил это плохо, и еще раз спасибо за любую помощь.


person Colm Clarke    schedule 09.12.2015    source источник
comment
Хотя я думаю, что весь ваш подход к проблеме неверен (потому что вы все равно жестко кодируете проверенный/не проверенный контент, даже если они привязаны), попробуйте вместо этого установить для параметра Value={StaticResource InvertImageBtn} значение={DynamicResource InvertImageBtn} . Это заставит ссылку обновляться каждый раз, когда вы меняете ресурс InvertImageBtn. В настоящее время с помощью StaticResource он разрешается только во время создания.   -  person Gralo    schedule 10.12.2015


Ответы (1)


прежде всего, даже если вы основываете свой стиль на стиле кнопки-переключателя, вы должны управлять состоянием IsChecked RadioButton в своей модели представления. Если вам это удается, это хорошо. Во-вторых, если вы тормозите шаблон управления в своем базовом стиле, дальнейшая попытка торможения избыточна, потому что вы просто тормозите предыдущую, которая сломала исходную точку. Поэтому, если вы хотите придать элементу управления новый вид, попробуйте повторно создать шаблон ContentTemplate в стиле элемента управления. В вашем случае вы изменили исходный шаблон, поэтому у вас не будет области галочки, будет отображаться только содержимое. Относительно примеров: 1. Вот RadioButton, меняющий свой внутренний маркер (область галочки), добавляйте собственные кисти по своему желанию:

    <ImageBrush x:Key="CheckedBullet" ImageSource="MyResources/Koala.jpg"/>
    <ImageBrush x:Key="UnCheckedBullet" ImageSource="MyResources/Penguins.jpg"/>

    <Style x:Key="MyRadioButton" TargetType="{x:Type RadioButton}">
        <Setter Property="SnapsToDevicePixels" Value="true"/>
        <Setter Property="OverridesDefaultStyle" Value="true"/>
        <Setter Property="FocusVisualStyle"    Value="{StaticResource RadioButtonFocusVisual}"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type RadioButton}">
                    <BulletDecorator Background="Transparent">
                        <BulletDecorator.Bullet>
                            <Grid Width="50" Height="50" >
                                <Ellipse x:Name="Border"  
            Fill="{StaticResource NormalBrush}"
            StrokeThickness="1"
            Stroke="{StaticResource NormalBorderBrush}" />
                                <Ellipse Margin="3" x:Name="CheckMark" IsHitTestVisible="False"/>
                            </Grid>
                        </BulletDecorator.Bullet>
                        <ContentPresenter 
        Margin="4,0,0,0"
        VerticalAlignment="Center"
        HorizontalAlignment="Left"
        RecognizesAccessKey="True"/>
                    </BulletDecorator>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsChecked" Value="True">
                            <Setter TargetName="CheckMark" Property="Fill" Value="{StaticResource CheckedBullet}"/>
                        </Trigger>
                        <Trigger Property="IsChecked" Value="False">
                            <Setter TargetName="CheckMark" Property="Fill" Value="{StaticResource UnCheckedBullet}"/>
                        </Trigger>
                        <Trigger Property="IsMouseOver" Value="true">
                            <Setter TargetName="Border" Property="Fill" Value="{StaticResource DarkBrush}" />
                        </Trigger>
                        <Trigger Property="IsPressed" Value="true">
                            <Setter TargetName="Border" Property="Fill" Value="{StaticResource PressedBrush}" />
                            <Setter TargetName="Border" Property="Stroke" Value="{StaticResource GlyphBrush}" />
                        </Trigger>
                        <Trigger Property="IsEnabled" Value="false">
                            <Setter TargetName="Border" Property="Fill" Value="{StaticResource DisabledBackgroundBrush}" />
                            <Setter TargetName="Border" Property="Stroke" Value="#40000000" />
                            <Setter Property="Foreground" Value="#80000000"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
 <!--xaml code that use the style MyRadioButton defined above-->
    <RadioButton HorizontalAlignment="Center" VerticalAlignment="Center"
                 IsChecked="{Binding IsBrightnessAndContrastEnabled, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
        <RadioButton.Style>
            <Style TargetType="RadioButton" BasedOn="{StaticResource MyRadioButton}">
                <Style.Triggers>
                    <Trigger Property="IsChecked" Value="True">
                        <Setter Property="Content" Value="Checked!!!" />
                    </Trigger>
                    <Trigger Property="IsChecked" Value="False">
                        <Setter Property="Content" Value="Check me!!!" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </RadioButton.Style>
    </RadioButton>
  1. Вот кисти для стиля выше:

        <Style x:Key="RadioButtonFocusVisual">
        <Setter Property="Control.Template">
            <Setter.Value>
                <ControlTemplate>
                    <Border>
                        <Rectangle 
        Margin="15,0,0,0"
        StrokeThickness="1"
        Stroke="#60000000"
        StrokeDashArray="1 2"/>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    
    <!-- Fill Brushes -->
    
    <LinearGradientBrush x:Key="NormalBrush" StartPoint="0,0" EndPoint="0,1">
        <GradientBrush.GradientStops>
            <GradientStopCollection>
                <GradientStop Color="#FFF" Offset="0.0"/>
                <GradientStop Color="#CCC" Offset="1.0"/>
            </GradientStopCollection>
        </GradientBrush.GradientStops>
    </LinearGradientBrush>
    
    <LinearGradientBrush x:Key="HorizontalNormalBrush" StartPoint="0,0" EndPoint="1,0">
        <GradientBrush.GradientStops>
            <GradientStopCollection>
                <GradientStop Color="#FFF" Offset="0.0"/>
                <GradientStop Color="#CCC" Offset="1.0"/>
            </GradientStopCollection>
        </GradientBrush.GradientStops>
    </LinearGradientBrush>
    
    <LinearGradientBrush x:Key="LightBrush" StartPoint="0,0" EndPoint="0,1">
        <GradientBrush.GradientStops>
            <GradientStopCollection>
                <GradientStop Color="#FFF" Offset="0.0"/>
                <GradientStop Color="#EEE" Offset="1.0"/>
            </GradientStopCollection>
        </GradientBrush.GradientStops>
    </LinearGradientBrush>
    
    <LinearGradientBrush x:Key="HorizontalLightBrush" StartPoint="0,0" EndPoint="1,0">
        <GradientBrush.GradientStops>
            <GradientStopCollection>
                <GradientStop Color="#FFF" Offset="0.0"/>
                <GradientStop Color="#EEE" Offset="1.0"/>
            </GradientStopCollection>
        </GradientBrush.GradientStops>
    </LinearGradientBrush>
    
    <LinearGradientBrush x:Key="DarkBrush" StartPoint="0,0" EndPoint="0,1">
        <GradientBrush.GradientStops>
            <GradientStopCollection>
                <GradientStop Color="#FFF" Offset="0.0"/>
                <GradientStop Color="#AAA" Offset="1.0"/>
            </GradientStopCollection>
        </GradientBrush.GradientStops>
    </LinearGradientBrush>
    
    <LinearGradientBrush x:Key="PressedBrush" StartPoint="0,0" EndPoint="0,1">
        <GradientBrush.GradientStops>
            <GradientStopCollection>
                <GradientStop Color="#BBB" Offset="0.0"/>
                <GradientStop Color="#EEE" Offset="0.1"/>
                <GradientStop Color="#EEE" Offset="0.9"/>
                <GradientStop Color="#FFF" Offset="1.0"/>
            </GradientStopCollection>
        </GradientBrush.GradientStops>
    </LinearGradientBrush>
    
    <SolidColorBrush x:Key="DisabledForegroundBrush" Color="#888" />
    
    <SolidColorBrush x:Key="DisabledBackgroundBrush" Color="#EEE" />
    
    <SolidColorBrush x:Key="WindowBackgroundBrush" Color="#FFF" />
    
    <SolidColorBrush x:Key="SelectedBackgroundBrush" Color="#DDD" />
    
    <!-- Border Brushes -->
    
    <LinearGradientBrush x:Key="NormalBorderBrush" StartPoint="0,0" EndPoint="0,1">
        <GradientBrush.GradientStops>
            <GradientStopCollection>
                <GradientStop Color="#CCC" Offset="0.0"/>
                <GradientStop Color="#444" Offset="1.0"/>
            </GradientStopCollection>
        </GradientBrush.GradientStops>
    </LinearGradientBrush>
    
    <LinearGradientBrush x:Key="HorizontalNormalBorderBrush" StartPoint="0,0" EndPoint="1,0">
        <GradientBrush.GradientStops>
            <GradientStopCollection>
                <GradientStop Color="#CCC" Offset="0.0"/>
                <GradientStop Color="#444" Offset="1.0"/>
            </GradientStopCollection>
        </GradientBrush.GradientStops>
    </LinearGradientBrush>
    
    <LinearGradientBrush x:Key="DefaultedBorderBrush" StartPoint="0,0" EndPoint="0,1">
        <GradientBrush.GradientStops>
            <GradientStopCollection>
                <GradientStop Color="#777" Offset="0.0"/>
                <GradientStop Color="#000" Offset="1.0"/>
            </GradientStopCollection>
        </GradientBrush.GradientStops>
    </LinearGradientBrush>
    
    <LinearGradientBrush x:Key="PressedBorderBrush" StartPoint="0,0" EndPoint="0,1">
        <GradientBrush.GradientStops>
            <GradientStopCollection>
                <GradientStop Color="#444" Offset="0.0"/>
                <GradientStop Color="#888" Offset="1.0"/>
            </GradientStopCollection>
        </GradientBrush.GradientStops>
    </LinearGradientBrush>
    
    <!-- Miscellaneous Brushes -->
    <SolidColorBrush x:Key="GlyphBrush" Color="#FF00FF00" />
    
    <SolidColorBrush x:Key="LightColorBrush" Color="#DDD" />
    
  2. Вот стиль переключателя, который меняет свое содержимое только с помощью стиля IsChecked (как в вашем примере с небольшими изменениями, описанными выше):

        <ImageBrush x:Key="CheckedBullet" ImageSource="MyResources/Koala.jpg"/>
    <ImageBrush x:Key="UnCheckedBullet" ImageSource="MyResources/Penguins.jpg"/>
    <Style x:Key="RadioBtnToolStyle" TargetType="{x:Type RadioButton}">
        <Setter Property="Background" Value="#00FFFFFF" />
        <Setter Property="HorizontalAlignment" Value="Center" />
        <Setter Property="Foreground" Value="{x:Null}" />
        <Setter Property="Padding" Value="0" />
        <Setter Property="Margin" Value="3" />
        <Setter Property="BorderBrush" Value="{x:Null}" />
        <Setter Property="OverridesDefaultStyle" Value="True" />
        <Setter Property="RenderTransform">
            <Setter.Value>
                <ScaleTransform CenterX="30" CenterY="30" ScaleX="1" ScaleY="1" />
            </Setter.Value>
        </Setter>
        <Setter Property="Cursor" Value="Hand" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="RadioButton">
                    <Border Name="border" BorderThickness="0" BorderBrush="Black" Background="{TemplateBinding Background}">
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Opacity" Value="0.8" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="IsPressed" Value="True">
                <Trigger.EnterActions>
                    <BeginStoryboard>
                        <Storyboard>
                            <DoubleAnimation From="1" To="0.8" AutoReverse="False" Duration="00:00:00.6" Storyboard.TargetProperty="RenderTransform.ScaleX" />
                            <DoubleAnimation From="1" To="0.8" AutoReverse="False" Duration="00:00:00.6" Storyboard.TargetProperty="RenderTransform.ScaleY" />
                        </Storyboard>
                    </BeginStoryboard>
                </Trigger.EnterActions>
                <Trigger.ExitActions>
                    <BeginStoryboard>
                        <Storyboard>
                            <DoubleAnimation To="1" Duration="00:00:00.6" Storyboard.TargetProperty="RenderTransform.ScaleX" />
                            <DoubleAnimation To="1" Duration="00:00:00.6" Storyboard.TargetProperty="RenderTransform.ScaleY" />
                        </Storyboard>
                    </BeginStoryboard>
                </Trigger.ExitActions>
            </Trigger>
        </Style.Triggers>
    </Style>
        <!--code that use the style above-->
    <RadioButton GroupName="Tools"  Grid.Row="0" IsChecked="{Binding IsBrightnessAndContrastEnabled, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Right" VerticalAlignment="Bottom">
        <RadioButton.Style>
            <Style TargetType="RadioButton" BasedOn="{StaticResource RadioBtnToolStyle}">
                <Setter Property="Width" Value="50"></Setter>
                <Setter Property="Height" Value="50"></Setter>
                <Style.Triggers>
                    <Trigger Property="IsChecked" Value="True">
                        <Setter Property="Content" Value="{StaticResource InvertImageBtn}" />
                    </Trigger>
                    <Trigger Property="IsChecked" Value="False">
                        <Setter Property="Content" Value="{StaticResource  LogoFooterBackgroundStyle}" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </RadioButton.Style>
    </RadioButton>
    

  3. And here is the combo that can manage IsChecked state by itself (but you can't combain the combo and RadioButton in the way you did):

       <ToggleButton IsChecked="{Binding IsBrightnessAndContrastEnabled, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" VerticalAlignment="Top">
        <ToggleButton.Style>
            <Style TargetType="ToggleButton" BasedOn="{StaticResource SpecialButtonStyle}">
                <Setter Property="Width" Value="50"></Setter>
                <Setter Property="Height" Value="50"></Setter>
                <Style.Triggers>
                    <Trigger Property="IsChecked" Value="True">
                        <Setter Property="Content" Value="{StaticResource InvertImageBtn2}" />
                    </Trigger>
                    <Trigger Property="IsChecked" Value="False">
                        <Setter Property="Content" Value="{StaticResource  LogoFooterBackgroundStyle2}" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </ToggleButton.Style>
    </ToggleButton>
    
  4. SpecialButtonStyle, чтобы сделать кнопку-переключатель радиальной:

    <Image x:Key="InvertImageBtn2" Source="MyResources/Koala.jpg" />
    <Image x:Key="LogoFooterBackgroundStyle2" Source="MyResources/Penguins.jpg" />
    <Color x:Key="ButtonLowerPartKey">#FFD5E0EE</Color>
    <Color x:Key="ButtonUpperPartKey">#FFEAF1F8</Color>
    <Color x:Key="PressedColorButtonLowerPartKey">#FFF4C661</Color>
    <Color x:Key="PressedButtonUpperPartKey">#FFF4CC87</Color>
    <Color x:Key="HooveredButtonLowerPartKey">#FFFFD06D</Color>
    <Color x:Key="HooveredButtonUpperPartKey">#FFFFF0DF</Color>
    <Style x:Key="SpecialButtonStyle" TargetType="ToggleButton" BasedOn="{StaticResource {x:Type ToggleButton}}">
        <Setter Property="Padding" Value="5">
        </Setter>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate>
                    <Grid x:Name="Grid">
                        <Ellipse x:Name="ButtonControlBorder" Stroke="{TemplateBinding BorderBrush}" 
                             StrokeThickness="{TemplateBinding BorderThickness}" 
                             Width="{TemplateBinding Width}" Height="{TemplateBinding Height}">
                            <Ellipse.Fill>
                                <LinearGradientBrush x:Name="BrushKey" MappingMode="RelativeToBoundingBox" SpreadMethod="Repeat" StartPoint="0.5,0" EndPoint="0.5,1">
                                    <LinearGradientBrush.GradientStops>
                                        <GradientStop Offset="0.5" Color="{StaticResource ButtonUpperPartKey}" />
                                        <GradientStop Offset="0.5" Color="{StaticResource ButtonUpperPartKey}" />
                                        <GradientStop Offset="0.5" Color="{StaticResource ButtonLowerPartKey}" />
                                    </LinearGradientBrush.GradientStops>
                                </LinearGradientBrush>
                            </Ellipse.Fill>
                        </Ellipse>
                        <Ellipse x:Name="Pressed" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}" Opacity="0">
                            <Ellipse.Fill>
                                <LinearGradientBrush x:Name="PressedBrushKey" MappingMode="RelativeToBoundingBox" SpreadMethod="Repeat" StartPoint="0.5,0" EndPoint="0.5,1">
                                    <LinearGradientBrush.GradientStops>
                                        <GradientStop Offset="0.5" Color="{StaticResource PressedButtonUpperPartKey}" />
                                        <GradientStop Offset="0.5" Color="{StaticResource PressedButtonUpperPartKey}" />
                                        <GradientStop Offset="0.5" Color="{StaticResource PressedColorButtonLowerPartKey}" />
                                    </LinearGradientBrush.GradientStops>
                                </LinearGradientBrush>
                            </Ellipse.Fill>
                        </Ellipse>
                        <Ellipse x:Name="InnerPressed" 
                            Width="{Binding ElementName=Pressed, Path=Width}" Height="{Binding ElementName=Pressed, Path=Height}" 
                            Stroke="DarkOrange" Opacity="0" StrokeThickness="1" SnapsToDevicePixels="True" Fill="Transparent"/>
                        <ContentPresenter Content="{TemplateBinding Button.Content}" HorizontalAlignment="Center" VerticalAlignment="Center">
                            <ContentPresenter.OpacityMask>
                                <VisualBrush Visual="{Binding ElementName=ButtonControlBorder}" />
                            </ContentPresenter.OpacityMask>
                        </ContentPresenter>
                        <Grid.Triggers>
                            <EventTrigger RoutedEvent="Mouse.MouseEnter">
                                <BeginStoryboard x:Name="MouseEnterStoryboard">
                                    <Storyboard>
                                        <ColorAnimation Storyboard.TargetName="BrushKey" Storyboard.TargetProperty="GradientStops[0].Color" From="{StaticResource ButtonUpperPartKey}" To="{StaticResource HooveredButtonUpperPartKey}" Duration="0:0:0.3" AutoReverse="False" />
                                        <ColorAnimation Storyboard.TargetName="BrushKey" Storyboard.TargetProperty="GradientStops[2].Color" From="{StaticResource ButtonLowerPartKey}" To="{StaticResource HooveredButtonLowerPartKey}" Duration="0:0:0.3" />
                                    </Storyboard>
                                </BeginStoryboard>
                            </EventTrigger>
                            <EventTrigger RoutedEvent="Mouse.MouseLeave">
                                <BeginStoryboard>
                                    <Storyboard>
                                        <ColorAnimation Storyboard.TargetName="BrushKey" Storyboard.TargetProperty="GradientStops[0].Color" From="{StaticResource HooveredButtonUpperPartKey}" To="{StaticResource ButtonUpperPartKey}" Duration="0:0:1" AutoReverse="False" />
                                        <ColorAnimation Storyboard.TargetName="BrushKey" Storyboard.TargetProperty="GradientStops[2].Color" From="{StaticResource HooveredButtonLowerPartKey}" To="{StaticResource ButtonLowerPartKey}" Duration="0:0:1" />
                                    </Storyboard>
                                </BeginStoryboard>
                            </EventTrigger>
                        </Grid.Triggers>
                    </Grid>
                    <ControlTemplate.Resources>
                        <Storyboard x:Key="MouseUpTimeLine">
                            <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="Pressed" Storyboard.TargetProperty="Opacity">
                                <SplineDoubleKeyFrame KeyTime="00:00:00.25" Value="0" />
                            </DoubleAnimationUsingKeyFrames>
                        </Storyboard>
                        <Storyboard x:Key="MouseDownTimeLine">
                            <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="Pressed" Storyboard.TargetProperty="Opacity">
                                <SplineDoubleKeyFrame KeyTime="00:00:00.05" Value="0.8" />
                            </DoubleAnimationUsingKeyFrames>
                        </Storyboard>
                        <Storyboard x:Key="InnerPressedMouseUpTimeLine">
                            <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="InnerPressed" Storyboard.TargetProperty="Opacity">
                                <SplineDoubleKeyFrame KeyTime="00:00:00.25" Value="0" />
                            </DoubleAnimationUsingKeyFrames>
                        </Storyboard>
                        <Storyboard x:Key="InnerPressedMouseDownTimeLine">
                            <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="InnerPressed" Storyboard.TargetProperty="Opacity">
                                <SplineDoubleKeyFrame KeyTime="00:00:00.05" Value="1" />
                            </DoubleAnimationUsingKeyFrames>
                        </Storyboard>
                    </ControlTemplate.Resources>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" SourceName="Grid" Value="True">
                            <Setter Property="Stroke" TargetName="ButtonControlBorder">
                                <Setter.Value>
                                    <SolidColorBrush Color="{StaticResource HooveredButtonLowerPartKey}">
                                    </SolidColorBrush>
                                </Setter.Value>
                            </Setter>
                        </Trigger>
                        <Trigger Property="ButtonBase.IsPressed" Value="True">
                            <Trigger.EnterActions>
                                <BeginStoryboard Storyboard="{StaticResource MouseDownTimeLine}" />
                                <BeginStoryboard Storyboard="{StaticResource InnerPressedMouseDownTimeLine}">
                                </BeginStoryboard>
                            </Trigger.EnterActions>
                            <Trigger.ExitActions>
                                <BeginStoryboard Storyboard="{StaticResource MouseUpTimeLine}" />
                                <BeginStoryboard Storyboard="{StaticResource InnerPressedMouseUpTimeLine}">
                                </BeginStoryboard>
                            </Trigger.ExitActions>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    
  5. Посмотреть код модели:

    частное логическое значение _isBrightnessAndContrastEnabled;

    public bool IsBrightnessAndContrastEnabled
    {
        get { return _isBrightnessAndContrastEnabled; }
        set
        {
            _isBrightnessAndContrastEnabled = !IsBrightnessAndContrastEnabled;
            OnPropertyChanged();
        }
    }
    
  6. Важный!!! Вы должны поместить все определенные стили в область ресурсов кода xaml под своим контролем.

  7. Как это выглядит здесь. Буду рад помочь, если у вас возникнут проблемы с кодом. С Уважением
person Ilan    schedule 10.12.2015
comment
Большое спасибо, это сработало. Просто из любопытства, если бы я использовал векторную графику, содержащую холст, и я должен был сохранить это как ресурс, как я мог бы ссылаться на этот холст? - person Colm Clarke; 10.12.2015
comment
@ColmClarke, можешь перефразировать свое мнение? Я не уверен, что понимаю, что вы имеете в виду. - person Ilan; 12.12.2015