【问题标题】:How to overwrite a nested style property in xaml/UWP如何覆盖 xaml/UWP 中的嵌套样式属性
【发布时间】:2017-01-04 16:29:04
【问题描述】:

我想要一个红色按钮。我无法获得红色按钮,我认为原因是我无法覆盖所有按钮默认为的样式的模板属性。

按钮本身是简单的,设置它的背景不会改变它的颜色:

<Button x:Name="redButton" Content="Red Button" Width="180" Height="80" Background="Red"/>

它默认的样式:

<Style x:Key="ButtonBase" TargetType="Button">
    <Style.Setters>
        <Setter Property="Foreground" Value="{StaticResource ButtonForeground}" />
        <Setter Property="FontSize" Value="{StaticResource ButtonFontSize}" />
        <Setter Property="HorizontalContentAlignment" Value="Center" />
        <Setter Property="VerticalContentAlignment" Value="Center" />
        <Setter Property="MinWidth" Value="80" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Grid x:Name="RootGrid" Width="Auto">
                        <Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
                            <ContentPresenter
                                x:Name="Content"
                                Margin="5"
                                HorizontalAlignment="Center"
                                VerticalAlignment="Center" />
                        </Grid>
                        <VisualStateManager.VisualStateGroups>
                            <!--                               -->
                            <!-- About a hundred lines of code -->
                            <!--                               -->
                        </VisualStateManager.VisualStateGroups>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style.Setters>
</Style>

“RootGrid”内部的网格是我想要的红色背景。获得这种风格的红色按钮的最简单方法是什么?

【问题讨论】:

    标签: c# xaml uwp


    【解决方案1】:

    在ControlTemplate中为Grid的Background属性设置一个TemplateBinding:

    <Grid x:Name="RootGrid" Width="Auto">
        <Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="{TemplateBinding Background}">
    

    【讨论】:

      【解决方案2】:

      您需要覆盖按钮的模板:

          <Button Content="sample button">
              <Button.Template>
                  <ControlTemplate TargetType="{x:Type Button}">
                      <Border Background="Red" BorderBrush="DimGray" BorderThickness="1" CornerRadius="2">
                          <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                      </Border>
                  </ControlTemplate>
              </Button.Template>
          </Button>
      

      【讨论】:

      • 这也可以,但我必须将其更改为 TargetType="Button"。使用 {x:Type Button} 引发错误。
      猜你喜欢
      • 2020-06-13
      • 2011-04-09
      • 1970-01-01
      • 2017-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多