Пользовательская кнопка - фон не меняется - PullRequest
2 голосов
/ 24 сентября 2011

Я пытаюсь сделать пользовательскую кнопку, моя единственная проблема в том, что фон не меняется. Я знаю, что мне нужно установить значение фона как {TemplateBinding Background}, но я не могу найти нужное место. Я пытался, но это просто не работает.

Кнопка была создана в смешанном выражении, поэтому, я полагаю, оттуда может произойти любая странная вещь, которую вы можете увидеть.

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style x:Key="DEHRButton" TargetType="{x:Type Button}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Grid>
                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup x:Name="CommonStates">
                            <VisualStateGroup.Transitions>
                                <VisualTransition GeneratedDuration="0:0:0.1"/>
                            </VisualStateGroup.Transitions>
                            <VisualState x:Name="Normal"/>
                            <VisualState x:Name="MouseOver">
                                <Storyboard>
                                    <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.StrokeThickness)" Storyboard.TargetName="path">
                                        <EasingDoubleKeyFrame KeyTime="0" Value="2"/>
                                    </DoubleAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="Pressed">
                                <Storyboard>
                                    <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.StrokeThickness)" Storyboard.TargetName="path">
                                        <EasingDoubleKeyFrame KeyTime="0" Value="3"/>
                                    </DoubleAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="Disabled">
                                <Storyboard>
                                    <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="path">
                                        <EasingDoubleKeyFrame KeyTime="0" Value="0.7"/>
                                    </DoubleAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="path">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>
                    <Path Fill="{TemplateBinding Background}"/>
                    <Path x:Name="path" Data="M14.666499,0.5 L14.833,0.94661933 14.833,0.5 67.170002,0.5 81.166,0.5 95.502998,0.5 81.336502,38.5 81.166,38.042648 81.166,38.5 28.833,38.5 14.833,38.5 0.5,38.5 z" Stretch="Fill" Stroke="{TemplateBinding BorderBrush}">
                        <Path.Fill>
                            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                                <GradientStop Color="Black" Offset="0"/>
                                <GradientStop Color="White" Offset="1"/>
                            </LinearGradientBrush>
                        </Path.Fill>
                    </Path>
                    <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                </Grid>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsFocused" Value="True"/>
                    <Trigger Property="IsDefaulted" Value="True"/>
                    <Trigger Property="IsMouseOver" Value="True"/>
                    <Trigger Property="IsPressed" Value="True"/>
                    <Trigger Property="IsEnabled" Value="False"/>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
<!-- Resource dictionary entries should be defined here. -->

Заранее спасибо за помощь.

1 Ответ

1 голос
/ 24 сентября 2011

Проблема, с которой вы столкнулись, заключается в том, что свойство Fill привязывается два раза (один раз к фону и один раз к стилю по умолчанию - черно-белому).

Вот как вы решаете свою проблему:

<Style x:Key="DEHRButton" TargetType="{x:Type Button}">
        <Setter Property="Background">
            <Setter.Value>
                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="Black" Offset="0"/>
                    <GradientStop Color="White" Offset="1"/>
                </LinearGradientBrush>
            </Setter.Value>
        </Setter>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Grid>
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualStateGroup.Transitions>
                                    <VisualTransition GeneratedDuration="0:0:0.1"/>
                                </VisualStateGroup.Transitions>
                                <VisualState x:Name="Normal"/>
                                <VisualState x:Name="MouseOver">
                                    <Storyboard>
                                        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.StrokeThickness)" Storyboard.TargetName="path">
                                            <EasingDoubleKeyFrame KeyTime="0" Value="2"/>
                                        </DoubleAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="Pressed">
                                    <Storyboard>
                                        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.StrokeThickness)" Storyboard.TargetName="path">
                                            <EasingDoubleKeyFrame KeyTime="0" Value="3"/>
                                        </DoubleAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="Disabled">
                                    <Storyboard>
                                        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="path">
                                            <EasingDoubleKeyFrame KeyTime="0" Value="0.7"/>
                                        </DoubleAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="path">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                        <Path x:Name="path" Fill="{TemplateBinding Background}" Data="M14.666499,0.5 L14.833,0.94661933 14.833,0.5 67.170002,0.5 81.166,0.5 95.502998,0.5 81.336502,38.5 81.166,38.042648 81.166,38.5 28.833,38.5 14.833,38.5 0.5,38.5 z" Stretch="Fill" Stroke="{TemplateBinding BorderBrush}">

                        </Path>
                        <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsFocused" Value="True"/>
                        <Trigger Property="IsDefaulted" Value="True"/>
                        <Trigger Property="IsMouseOver" Value="True"/>
                        <Trigger Property="IsPressed" Value="True"/>
                        <Trigger Property="IsEnabled" Value="False"/>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Вы определяете внешний вид по умолчанию как Setter для свойства Background, и ваш шаблон привязывает заливку к фону. Это позволяет вам иметь некоторое значение по умолчанию для фона, но также позволяет вам установить собственный фон непосредственно из элемента управления, например так:

<Button Background="Azure" Style="{StaticResource DEHRButton}" Height="20" Width="100"/>

Здесь больше о Visual Tree в WPF. Один из старших, с которыми я работал, однажды сказал, что прежде чем начать программировать на XAML, вам нужно сначала понять концепцию Visual Tree и Logical Tree, иначе вы начнете ненавидеть его.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...