如何在运行时更改XAML中设计的自定义按钮的背景色

本文关键字:自定义 背景色 按钮 XAML 运行时 | 更新日期: 2023-09-27 18:29:55

我使用表达式blend制作了一个自定义按钮,并将其粘贴到我的xaml代码中。

<phone:PhoneApplicationPage.Resources>
 <Style x:Key="ButtonStyle1" TargetType="Button">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Grid>
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Normal"/>
                                <VisualState x:Name="Disabled"/>
                                <VisualState x:Name="MouseOver"/>
                            </VisualStateGroup>
                            <VisualStateGroup x:Name="FocusStates">
                                <VisualState x:Name="Focused"/>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                        <Rectangle RadiusY="21" RadiusX="20" Stroke="White"/>
                        <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
 </Style>
</phone:PhoneApplicationPage.Resources>

然后,我在c#代码中使用了这个资源来动态更改颜色、字体大小、背景、前景和所有可能的属性。

 public partial class MainPage : PhoneApplicationPage
{
    public MainPage()
    {
        InitializeComponent();
        createButton();
    }
    public void createButton()
    {            
        Button buttton = new Button { Height = 100, Background = new SolidColorBrush(Colors.Blue), Width = 300,  Content = " Button", Style = this.Resources["ButtonStyle1"] as Style };                  
        ContentPanel.Children.Add(buttton);
    }

但我无法做到这一点,并没有任何变化反映在按钮上。有什么办法吗。我知道我必须改变矩形的颜色。但是不知道怎么做。我试了很多。谢谢

如何在运行时更改XAML中设计的自定义按钮的背景色

那么,哪些属性应该影响哪个?您为按钮创建了一个自定义控件模板,这意味着您可以决定如何绘制按钮。如果查看您的模板,您的按钮由一个Grid和两个子控件组成:RectangleContentPresenter

现在,当你说:

var btn = new Button
{
    Background = new SolidColorBrush(Color.Blue);
};

什么应该变成蓝色?GridRectangle控件?ContentPresenter?这个问题原则上无法回答,您需要决定ControlTemplate中的哪个控件继承父控件的属性。

换句话说:Button的属性通过TemplateBinding向下传递到ControlTemplate中的控件。因此,如果您想将Button.Background的含义转换为Rectangle.Background,您可以将模板更改为:

<Rectangle RadiusY="21" RadiusX="20" Stroke="White"
            Fill="{TemplateBinding Background}"/>

现在你得到了可能是你想要的东西。当您设置Button.Background时,您只需将其转移到目标子控件,因为视觉树中没有Button,它会被它的控件模板替换。