简体   繁体   中英

How to overwrite a nested style property in xaml/UWP

I want a red button. I cannot get a red button, and I think the reason is that I cannot overwrite the template property of the style all of my buttons default to.

The button itself is bare-bones, and setting its Background does not change its color:

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

The style it defaults to:

<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>

The grid immediately inside of "RootGrid" is what I want to have a red background. What is the simplest way of getting a red button with this style?

Set a TemplateBinding for the Background property of the Grid in the ControlTemplate:

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

You need override template of button:

    <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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM