Действительно ли возможно расширить ControlTemplate тем же путем, Вы расширяете Стиль в WPF?

Да мы делаем, это обычно происходит, когда мы начинаем разрабатывать что-то, и затем кто-то замечает, что это напоминает существующий шаблон. Мы тогда смотрим на него и видим, как это помогло бы нам достигнуть нашей цели.

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

Мышление Вы, мы не используем их много.

8
задан Carlo 9 October 2009 в 20:17
поделиться

1 ответ

Нашел решение. Вы не расширяете ControlTemplates, вместо этого вы определяете все необходимое базовое поведение, а затем позволяете стилю или самому элементу управления изменять его. Возьмем, к примеру, приведенный ниже пример. ControlTemplate устанавливает OpacityMask и закругленные углы для моего прямоугольника, стили задают цвет фона для каждой кнопки (с помощью TemplateBinding), и вот мое решение:

    <Window.Resources>
        <ControlTemplate x:Key="BaseMainButtonTemplate" TargetType="{x:Type Button}">
            <Grid TextBlock.Foreground="White" TextBlock.FontFamily="Calibri">
                <Rectangle Stroke="#FFE8E6E6" x:Name="rectangle" RadiusX="14.5" RadiusY="14.5" Fill="{TemplateBinding Property=Background}"> <!-- This TemplateBinding takes the color set by the style and applies it to the rectangle. Doing it this way, allows the style to modify the background color -->
                    <Rectangle.OpacityMask>
                        <LinearGradientBrush EndPoint="0,1" SpreadMethod="Reflect">
                            <GradientStop Offset="0" Color="Transparent"></GradientStop>
                            <GradientStop Offset="1" Color="Gray"></GradientStop>
                        </LinearGradientBrush>
                    </Rectangle.OpacityMask>
                </Rectangle>
                <ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" RecognizesAccessKey="True"/>
            </Grid>
            <ControlTemplate.Triggers>
                <!-- OpacityMask when it's Focused, Defaulted and Mouse is over -->
                <Trigger Property="IsFocused" Value="True"/>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="OpacityMask" TargetName="rectangle">
                        <Setter.Value>
                            <LinearGradientBrush EndPoint="0,1" SpreadMethod="Repeat">
                                <GradientStop Offset="1" Color="Transparent"></GradientStop>
                                <GradientStop Offset="0" Color="Gray"></GradientStop>
                            </LinearGradientBrush>
                        </Setter.Value>
                    </Setter>
                </Trigger>
                <!-- OpacityMask when it's pressed -->
                <Trigger Property="IsPressed" Value="True">
                    <Setter Property="Stroke" TargetName="rectangle">
                        <Setter.Value>
                            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                                <GradientStop Color="#FF223472" Offset="0"/>
                                <GradientStop Color="#FFF2F0F0" Offset="0.911"/>
                            </LinearGradientBrush>
                        </Setter.Value>
                    </Setter>
                    <Setter Property="StrokeThickness" TargetName="rectangle" Value="3"/>
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
        <Style x:Key="BlueButtonStyle" TargetType="{x:Type Button}">
            <Setter Property="Background" Value="Blue" />
            <Setter Property="Template" Value="{StaticResource BaseMainButtonTemplate}">
            </Setter>
        </Style>
        <Style x:Key="RedButtonStyle" TargetType="{x:Type Button}">
            <Setter Property="Background" Value="Red" />
            <Setter Property="Template" Value="{StaticResource BaseMainButtonTemplate}">
            </Setter>
        </Style>
        <Style x:Key="GreenButtonStyle" TargetType="{x:Type Button}">
            <Setter Property="Background" Value="Green" />
            <Setter Property="Template" Value="{StaticResource BaseMainButtonTemplate}">
            </Setter>
        </Style>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <StackPanel>
            <Button Style="{StaticResource BlueButtonStyle}" Height="30" Content="Test">
            </Button>
            <Button Style="{StaticResource RedButtonStyle}" Height="30" Content="Test">
            </Button>
            <Button Style="{StaticResource GreenButtonStyle}" Height="30" Content="Test">
            </Button>
        </StackPanel>
    </Grid>
6
ответ дан 5 December 2019 в 22:19
поделиться
Другие вопросы по тегам:

Похожие вопросы: