Чередование изображения и цвета в качестве фона кнопки в зависимости от состояния в XAML - PullRequest
1 голос
/ 23 декабря 2010

У меня есть изображение, которое я использую в качестве фона для моих кнопок.Если кнопка отключена, я хочу, чтобы она была определенного цвета, в данном случае, #FFCCCCCC, но когда она включена, я хочу, чтобы она использовала изображение в качестве фона.Это возможно?Я изменяю шаблон в Expression Blend, но не могу найти правильную комбинацию.Кажется, что кнопка имеет либо фон изображения, либо цвет фона, но не может меняться в зависимости от состояния.

Я использую Windows Phone 7 / Silverlight.

Мой XAML ниже:

    <Style x:Key="SiteKeyButtonStyle" TargetType="Button">
        <Setter Property="VerticalAlignment" Value="Top" />
        <Setter Property="HorizontalAlignment" Value="Center" />
        <Setter Property="FontFamily" Value="{StaticResource PhoneFontFamilyNormal}" />
        <Setter Property="FontSize" Value="24" />
        <Setter Property="Foreground" Value="#FFFFFF" />
        <Setter Property="BorderThickness" Value="0" />
        <Setter Property="MinWidth" Value="140" />
        <Setter Property="Height" Value="50" />
        <Setter Property="Padding" Value="24, 0, 24, 0" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Grid Background="Transparent">
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Normal"/>
                                <VisualState x:Name="MouseOver"/>
                                <VisualState x:Name="Pressed">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentContainer" Storyboard.TargetProperty="Foreground">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneBackgroundBrush}" />
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ButtonBackground" Storyboard.TargetProperty="BorderBrush">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneForegroundBrush}" />
                                        </ObjectAnimationUsingKeyFrames>
                                        <DoubleAnimation Duration="0" To="0.6" Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="ButtonBackground" />
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="Disabled">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentContainer" Storyboard.TargetProperty="Foreground">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneDisabledBrush}" />
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ButtonBackground" Storyboard.TargetProperty="BorderBrush">
                                            <DiscreteObjectKeyFrame KeyTime="0" >
                                                <DiscreteObjectKeyFrame.Value>
                                                    <SolidColorBrush Color="#FFCCCCCC"/>
                                                </DiscreteObjectKeyFrame.Value>
                                            </DiscreteObjectKeyFrame>
                                        </ObjectAnimationUsingKeyFrames>
                                        <DoubleAnimation Duration="0" Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="ButtonBackground" To="1" />
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                        <Border x:Name="ButtonBackground" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="0" >
                            <Border.Background>
                                <ImageBrush ImageSource="/ProjectName;component/Images/Icons/button-background.png" Stretch="Fill"/>
                            </Border.Background>
                            <ContentControl x:Name="ContentContainer" Foreground="{TemplateBinding Foreground}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}" Padding="{TemplateBinding Padding}" Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}"/>
                        </Border>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Ответы [ 2 ]

2 голосов
/ 23 декабря 2010

Типичный подход к такого рода вещам заключается в добавлении элемента Rectangle в базовый дизайн следующим образом: -

                    <Border x:Name="ButtonBackground" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="0" >
                         <Rectangle x:Name="BackgroundElement">
                             <Rectangle.Fill>
                                 <ImageBrush ImageSource="/ProjectName;component/Images/Icons/button-background.png" Stretch="Fill"/>
                             </Rectangle.Fill>
                         </Rectangle>
                         <ContentControl x:Name="ContentContainer" Foreground="{TemplateBinding Foreground}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}" Padding="{TemplateBinding Padding}" Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}"/>
                     </Border>

Теперь вы можете изменить Disabled VisualState, чтобы фон не был прозрачным, но#FFCCCCCC.Также добавьте DoubleAnimation, чтобы установить Opacity для «BackgroundElement» в 0 как в состоянии «Отключено», так и в состоянии «Нажатие».

Таким образом, при включении изображение в прямоугольнике будет скрыто за содержимым контейнера содержимого.Когда отключено, изображение прозрачно и виден цвет #FFCCCCCC.При нажатии цвет PhoneForegroundBrush виден.

0 голосов
/ 23 декабря 2010

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

 <Style TargetType="{x:Type Button}">
     <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">

                    </ControlTemplate>
                </Setter.Value>
            </Setter>
     <Style.Triggers>
                <Trigger Property="IsEnabled" Value="False">
                    <ControlTemplate TargetType="{x:Type Button}">

                    </ControlTemplate>
                </Trigger>
     </Style.Trigger>
    </Style>
...