【问题标题】:Change color of WPF button using code使用代码更改 WPF 按钮的颜色
【发布时间】:2017-10-12 07:18:55
【问题描述】:

我有使用多边形几何制作的 WPF 三角形按钮:

<UserControl x:Class="Formats.Triangle_Down"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:Formats"
         mc:Ignorable="d" Height="100" Width="100">
<Grid Margin="0,0,10,10">
    <Grid.RowDefinitions>
        <RowDefinition Height="7*"/>
        <RowDefinition Height="11*"/>
    </Grid.RowDefinitions>
    <Button Background="Transparent" Content="Button" Foreground="Transparent" Margin="0,0,50,0">
        <Button.Template>
            <ControlTemplate TargetType="Button">
                <Grid Background="{TemplateBinding Background}">
                    <Polygon x:Name="triangle" Points="10,10 20,30 30,10"  Stroke="Lime"
                     StrokeThickness="2" Fill="Lime" Margin="0,0,-91,-85">
                        </Polygon>
                    </Grid>
        </Button.Template>
    </Button>
</Grid>

所以我的问题是:如何使用 C# 代码更改 ButtonBackground 颜色和 Borderbrush? 当我使用这个时:

button.Background = System.Windows.Media.Brushes.Red;

什么都没有改变(如果我没记错的话,因为它不会改变多边形的填充)。 我知道使用“边框”改变颜色的方法

<Border Background="{TemplateBinding Background}">
<Button.Content>
</Border>

但它不适合我,因为我的按钮是三角形的。

那么,我该如何解决这个问题呢?

【问题讨论】:

标签: c# wpf


【解决方案1】:

在您的模板中,您将多边形放在网格中并将网格背景绑定到Button.Background,同时将多边形的颜色硬编码到Lime。这样你以后不能改变多边形的颜色。相反 - 将多边形颜色绑定到 Button.Background:

<Button Background="Lime"
        Content="Button"
        Foreground="Transparent"
        Margin="0,0,50,0">
    <Button.Template>
        <ControlTemplate TargetType="Button">
            <Polygon x:Name="triangle"
                     Points="10,10 20,30 30,10"
                     Stroke="{TemplateBinding Background}"
                     StrokeThickness="2"
                     Fill="{TemplateBinding Background}"
                     Margin="0,0,-91,-85"></Polygon>
        </ControlTemplate>
    </Button.Template>
</Button>

然后改变Button.Background会改变多边形的颜色。

【讨论】:

    猜你喜欢
    • 2014-11-17
    • 2017-12-08
    • 1970-01-01
    • 2017-10-18
    • 2014-03-08
    • 2017-11-10
    • 2013-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多