Стиль с изображением в качестве параметра - PullRequest
1 голос
/ 28 сентября 2011

Интересно, как я могу параметризовать источник изображения внутри стиля, и этот стиль используется внутри другого стиля. Позвольте мне попытаться быть более ясным. Я определил стиль для кнопок, у стиля есть изображение. Тогда у меня есть другой стиль. В этом стиле у меня есть две кнопки (я применил стиль кнопки), и я хочу изменить изображение каждой кнопки. Но я не могу заставить его работать.

Первая часть кода определяет стиль для кнопки, идея состоит в том, чтобы изменить изображение по мере необходимости для представления действия.

Это мой код:

<Style x:Key="InnerInscribirseButtonMatch" TargetType="{x:Type Button}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <ControlTemplate.Resources>
                        <Storyboard x:Key="MouseOver">
                            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)" Storyboard.TargetName="Blur_back">
                                <EasingDoubleKeyFrame KeyTime="0" Value="0"/>
                                <EasingDoubleKeyFrame KeyTime="0:0:0.1" Value="-0.666"/>
                            </DoubleAnimationUsingKeyFrames>
                            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="Blur_back">
                                <EasingDoubleKeyFrame KeyTime="0" Value="0"/>
                                <EasingDoubleKeyFrame KeyTime="0:0:0.1" Value="0.705"/>
                            </DoubleAnimationUsingKeyFrames>
                            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)" Storyboard.TargetName="contentPresenter">
                                <EasingDoubleKeyFrame KeyTime="0" Value="0"/>
                                <EasingDoubleKeyFrame KeyTime="0:0:0.1" Value="2.665"/>
                            </DoubleAnimationUsingKeyFrames>
                            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)" Storyboard.TargetName="contentPresenter">
                                <EasingDoubleKeyFrame KeyTime="0" Value="0"/>
                                <EasingDoubleKeyFrame KeyTime="0:0:0.1" Value="2.999"/>
                            </DoubleAnimationUsingKeyFrames>
                            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" Storyboard.TargetName="Blur_back">
                                <EasingColorKeyFrame KeyTime="0" Value="#FFE9E9A7"/>
                                <EasingColorKeyFrame KeyTime="0:0:0.1" Value="#FFF1F0DD"/>
                            </ColorAnimationUsingKeyFrames>
                            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)" Storyboard.TargetName="image">
                                <EasingDoubleKeyFrame KeyTime="0" Value="0"/>
                                <EasingDoubleKeyFrame KeyTime="0:0:0.1" Value="3"/>
                            </DoubleAnimationUsingKeyFrames>
                            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)" Storyboard.TargetName="image">
                                <EasingDoubleKeyFrame KeyTime="0" Value="0"/>
                                <EasingDoubleKeyFrame KeyTime="0:0:0.1" Value="4"/>
                            </DoubleAnimationUsingKeyFrames>
                            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" Storyboard.TargetName="Back">
                                <EasingColorKeyFrame KeyTime="0" Value="#FF356AA0"/>
                                <EasingColorKeyFrame KeyTime="0:0:0.1" Value="#FF1264B6"/>
                            </ColorAnimationUsingKeyFrames>
                        </Storyboard>
                    </ControlTemplate.Resources>
                    <Grid>
                        <Rectangle x:Name="Blur_back" RadiusY="5" RadiusX="5" Stroke="#FF3F4C6B" StrokeThickness="2" Fill="#FF5B8BBC" Margin="-4.5,-4" Opacity="0" RenderTransformOrigin="0.5,0.5">
                            <Rectangle.RenderTransform>
                                <TransformGroup>
                                    <ScaleTransform/>
                                    <SkewTransform/>
                                    <RotateTransform/>
                                    <TranslateTransform/>
                                </TransformGroup>
                            </Rectangle.RenderTransform>
                            <Rectangle.Effect>
                                <BlurEffect Radius="7"/>
                            </Rectangle.Effect>
                        </Rectangle>
                        <Rectangle x:Name="Back" RadiusY="5" RadiusX="5" Stroke="#FF3F4C6B" StrokeThickness="2" Fill="#FF356AA0"/>
                        <Rectangle x:Name="Glass" RadiusY="5" RadiusX="5" Stroke="#FF3F4C6B" StrokeThickness="2" Fill="White" Height="Auto" VerticalAlignment="Stretch" Opacity="0.15" Margin="0,0,0,61" RenderTransformOrigin="0.5,0.5">
                            <Rectangle.RenderTransform>
                                <TransformGroup>
                                    <ScaleTransform/>
                                    <SkewTransform/>
                                    <RotateTransform/>
                                    <TranslateTransform/>
                                </TransformGroup>
                            </Rectangle.RenderTransform>
                        </Rectangle>
                        <ContentPresenter x:Name="contentPresenter" HorizontalAlignment="Center" RecognizesAccessKey="True" VerticalAlignment="Bottom" RenderTransformOrigin="0.5,0.5" Margin="13.766,0,15.766,14.351" d:LayoutOverrides="Width">
                            <ContentPresenter.Effect>
                                <DropShadowEffect Opacity="0.77"/>
                            </ContentPresenter.Effect>
                            <ContentPresenter.RenderTransform>
                                <TransformGroup>
                                    <ScaleTransform/>
                                    <SkewTransform/>
                                    <RotateTransform/>
                                    <TranslateTransform/>
                                </TransformGroup>
                            </ContentPresenter.RenderTransform>
                        </ContentPresenter>
                        <Image x:Name="image" Margin="12,3.5,17,22.5" RenderTransformOrigin="0.5,0.5" Width="64" Height="64" Source="apuntarlista.png">
                            <Image.RenderTransform>
                                <TransformGroup>
                                    <ScaleTransform/>
                                    <SkewTransform/>
                                    <RotateTransform/>
                                    <TranslateTransform/>
                                </TransformGroup>
                            </Image.RenderTransform>
                        </Image>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <EventTrigger RoutedEvent="Mouse.MouseDown">
                            <BeginStoryboard x:Name="MouseOver_BeginStoryboard" Storyboard="{StaticResource MouseOver}"/>
                        </EventTrigger>
                        <EventTrigger RoutedEvent="Mouse.MouseUp">
                            <StopStoryboard BeginStoryboardName="MouseOver_BeginStoryboard"/>
                        </EventTrigger>
                        <EventTrigger RoutedEvent="Mouse.MouseLeave">
                            <StopStoryboard BeginStoryboardName="MouseOver_BeginStoryboard"/>
                        </EventTrigger>
                        <Trigger Property="IsCancel" Value="False"/>
                        <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>

ну, это часть, которую я хочу настроить. Исходная часть: Source = "apuntarlista.png"

<Image x:Name="image" Margin="12,3.5,17,22.5" RenderTransformOrigin="0.5,0.5" Width="64" Height="64" Source="apuntarlista.png">
                            <Image.RenderTransform>
                                <TransformGroup>
                                    <ScaleTransform/>
                                    <SkewTransform/>
                                    <RotateTransform/>
                                    <TranslateTransform/>
                                </TransformGroup>
                            </Image.RenderTransform>
                        </Image>

здесь у вас есть второй стиль

<Style x:Key="ButtonStyleCambiable" TargetType="{x:Type Button}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Grid Height="130" Width="Auto" Margin="50,0,-315,0">
                        <Rectangle x:Name="background" Fill="{Binding BackgroundColor, FallbackValue=#FF932424}" RadiusY="15" RadiusX="15" Stroke="{Binding BorderBackgroundColor, FallbackValue=#FF954444}" StrokeThickness="3" Height="130" Width="375" Margin="0" HorizontalAlignment="Left" d:LayoutOverrides="HorizontalAlignment"/>
                        <Rectangle x:Name="white_glass" Fill="White" RadiusY="15" RadiusX="15" Stroke="{x:Null}" StrokeThickness="3" Opacity="0.07" Height="65" VerticalAlignment="Top" Width="375" Margin="0" HorizontalAlignment="Left" ClipToBounds="True" d:LayoutOverrides="HorizontalAlignment"/>
                        <TextBlock HorizontalAlignment="Left" Margin="13,13.901,0,0" TextWrapping="Wrap" Width="272" VerticalAlignment="Center" FontSize="48" FontFamily="Cambria" Foreground="White" Text="{Binding Description, FallbackValue=50/100}" FontWeight="Bold">
                            <TextBlock.Effect>
                                <DropShadowEffect ShadowDepth="3" Opacity="0.35" BlurRadius="13"/>
                            </TextBlock.Effect></TextBlock>
                        <TextBlock HorizontalAlignment="Left" Margin="206,14.192,0,0" TextWrapping="Wrap" Width="122" VerticalAlignment="Top" FontSize="24" FontFamily="Cambria" Foreground="White" FontWeight="Bold" Text="En espera: " d:LayoutOverrides="HorizontalAlignment">
                            <TextBlock.Effect>
                                <DropShadowEffect ShadowDepth="3" Opacity="0.35" BlurRadius="13"/>
                            </TextBlock.Effect></TextBlock>
                        <TextBlock HorizontalAlignment="Left" Margin="210,50.123,0,51.739" TextWrapping="Wrap" Width="109" VerticalAlignment="Stretch" FontSize="24" FontFamily="Cambria" Foreground="White" FontWeight="Bold" Text="Libres: " d:LayoutOverrides="HorizontalAlignment, Height">
                            <TextBlock.Effect>
                                <DropShadowEffect ShadowDepth="3" Opacity="0.35" BlurRadius="13"/>
                            </TextBlock.Effect></TextBlock>
                        <TextBlock HorizontalAlignment="Left" Margin="292,51.123,0,50.739" TextWrapping="Wrap" Width="130" VerticalAlignment="Stretch" FontSize="24" FontFamily="Cambria" Foreground="White" FontWeight="Bold" Text="{Binding FreeSits, FallbackValue=10}" d:LayoutOverrides="HorizontalAlignment, Height">
                            <TextBlock.Effect>
                                <DropShadowEffect ShadowDepth="3" Opacity="0.35" BlurRadius="13"/>
                            </TextBlock.Effect></TextBlock>
                        <TextBlock HorizontalAlignment="Left" Margin="329,15.192,0,0" TextWrapping="Wrap" Width="96" VerticalAlignment="Top" FontSize="24" FontFamily="Cambria" Foreground="White" FontWeight="Bold" Text="{Binding PeopleWaiting, FallbackValue=1}" d:LayoutOverrides="HorizontalAlignment">
                            <TextBlock.Effect>
                                <DropShadowEffect ShadowDepth="3" Opacity="0.35" BlurRadius="13"/>
                            </TextBlock.Effect></TextBlock>
                        <Button Content="Inscribir" HorizontalAlignment="Left" Margin="381,2,0,2" Style="{DynamicResource InnerInscribirseButtonMatch}" Width="129" FontFamily="Calibri" FontSize="24" Foreground="White" Height="Auto" VerticalAlignment="Stretch" Opacity="0.85"/>
                        <Button Content="Info" HorizontalAlignment="Left" Margin="518,2,0,2" Style="{DynamicResource InnerInscribirseButtonMatch}" Width="129" FontFamily="Calibri" FontSize="24" Foreground="White" Height="Auto" VerticalAlignment="Stretch" Opacity="0.85"/>
                    </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>

там у меня есть:

<Button Content="Inscribir" HorizontalAlignment="Left" Margin="381,2,0,2" Style="{DynamicResource InnerInscribirseButtonMatch}" Width="129" FontFamily="Calibri" FontSize="24" Foreground="White" Height="Auto" VerticalAlignment="Stretch" Opacity="0.85"/>

<Button Content="Info" HorizontalAlignment="Left" Margin="518,2,0,2" Style="{DynamicResource InnerInscribirseButtonMatch}" Width="129" FontFamily="Calibri" FontSize="24" Foreground="White" Height="Auto" VerticalAlignment="Stretch" Opacity="0.85"/>

как вы можете видеть, обе кнопки используют Style = "{DynamicResource InnerIncribirseButtonMatch}"

но я хочу, чтобы у каждого было другое изображение.

Как я могу это сделать? Надеюсь, что будет ясно.

Заранее спасибо.

Ответы [ 2 ]

3 голосов
/ 28 сентября 2011

Я думаю, что вы можете определить свойство Button.DataContext, например, по строке, и связать свойство Image.Source с элементом управления DataContext.

<Button DataContext="apuntarlista.png"
        Style="{DynamicResource InnerInscribirseButtonMatch}"
         />

<Button DataContext="apuntarlista2.png"
        Style="{DynamicResource InnerInscribirseButtonMatch}"
         />

А в вашем внутреннем стиле:

<Image x:Name="image" 
       RenderTransformOrigin="0.5,0.5" 
       Width="64" Height="64" Source="{Binding}">
                        <Image.RenderTransform>
                            <TransformGroup>
                                <ScaleTransform/>
                                <SkewTransform/>
                                <RotateTransform/>
                                <TranslateTransform/>
                            </TransformGroup>
                        </Image.RenderTransform>
                    </Image>
1 голос
/ 28 сентября 2011

ИМХО, я бы всегда старался не менять стиль, так что это требует конкретного ввода. Вот для чего Content и ContentTemplate. Но, конечно, иногда это сложно.

Мы используем для этих случаев AttachedProperty

Итак, создайте новый статический класс, назовите его, например, ButtonIconService. Прикрепленное свойство с именем Icon

установите его на свои кнопки, как

<Button ButtonIconService.Icon="pathToIcon.png"
<Button ButtonIconService.Icon="pathToOtherIcon.png"

и привяжите его к своему изображению в шаблоне.

<Image Source="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=(ButtonInfoService.Icon)}}"

Я не уверен, в какие моменты нужны скобки вокруг ButtonInfoService.Icon?

Надеюсь, это поможет.

...