如何在代码中设置按钮的内部属性?

时间:2018-07-13 08:49:00

标签: c# wpf button

我有一个像这样的XAML按钮:

<Button x:Name="buttonOK" Content="OK" />

我没有附加XAML样式,也没有资源字典样式。没有外部样式可以设计我的按钮,这很好。那就是我想要的。

现在,我想在后面的代码中更改该按钮的RadiusX和RadiusY,因为我想要一个带圆角的按钮。我知道System.Windows.Controls.Button没有这些属性,但是我知道WPF矩形具有这些属性。

我不知道这是否正确;但是WPF按钮控件由其他控件组成?对?就像一个矩形和一个文本块或标签,并通过设置Button.Content,实际上是在更改按钮的内部标签的内容。我不确定我的想法多么幼稚。

最重要的是我想做这样的事情:

buttonOK.InnerRectangle.RadiusX = 5;
buttonOK.InnerRectangle.RadiusY = 5;

我希望用代码而不是XAML来实现全部功能,因为我在不同的XAML文件中有很多按钮,而且我想通过调用代码中的一种方法而不改变每个XAML文件来使它们圆滑。并非我所有XAML文件中的所有按钮,只是某些按钮。

我已经在所有窗口和用户控件中调用了一个方法,我只想向该方法添加圆角样式的按钮,这样就不会造成繁琐的代码。

1 个答案:

答案 0 :(得分:12)

将XAML从字符串加载到Style对象中,该对象允许更改代码中的拐角半径,然后设置按钮样式。

这是对我有用的代码:

        // OK
        private void buttonOK_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SetButtonCornerRadiusAndTriggerStyling(buttonOK, 5);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error at 'buttonOK_Click'" + Environment.NewLine + Environment.NewLine + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        // Set button corner radius and trigger styling
        public static void SetButtonCornerRadiusAndTriggerStyling(
            Button toStyle, int theCornerRadius,
            string theMouseOverBackground = "", string theMouseOverBorderBrush = "", string theMouseOverForeground = "",
            string thePressedBackground = "", string thePressedBorderBrush = "", string thePressedForeground = "",
            string theDisabledBackground = "", string theDisabledBorderBrush = "", string theDisabledForeground = "")
        {
            try
            {
                // Corner radius
                int cornerRadius = theCornerRadius;

                // Mouse over
                string defaultMouseOverBackground = "#BEE6FD";
                string defaultMouseOverBorderBrush = "#3C7FB1";
                string defaultMouseOverForeground = "Black";

                string mouseOverBackground = theMouseOverBackground;
                string mouseOverBorderBrush = theMouseOverBorderBrush;
                string mouseOverForeground = theMouseOverForeground;

                if (mouseOverBackground == null) { mouseOverBackground = ""; }
                if (mouseOverBorderBrush == null) { mouseOverBorderBrush = ""; }
                if (mouseOverForeground == null) { mouseOverForeground = ""; }

                if (mouseOverBackground.Length == 0) { mouseOverBackground = defaultMouseOverBackground; }
                if (mouseOverBorderBrush.Length == 0) { mouseOverBorderBrush = defaultMouseOverBorderBrush; }
                if (mouseOverForeground.Length == 0) { mouseOverForeground = defaultMouseOverForeground; }

                // Pressed
                string defaultPressedBackground = "#C4E5F6";
                string defaultPressedBorderBrush = "#2C628B";
                string defaultPressedForeground = "Black";

                string pressedBackground = thePressedBackground;
                string pressedBorderBrush = thePressedBorderBrush;
                string pressedForeground = thePressedForeground;

                if (pressedBackground == null) { pressedBackground = ""; }
                if (pressedBorderBrush == null) { pressedBorderBrush = ""; }
                if (pressedForeground == null) { pressedForeground = ""; }

                if (pressedBackground.Length == 0) { pressedBackground = defaultPressedBackground; }
                if (pressedBorderBrush.Length == 0) { pressedBorderBrush = defaultPressedBorderBrush; }
                if (pressedForeground.Length == 0) { pressedForeground = defaultPressedForeground; }

                // Disabled
                string defaultDisabledBackground = "#F4F4F4";
                string defaultDisabledBorderBrush = "#ADB2B5";
                string defaultDisabledForeground = "#83838C";

                string disabledBackground = theDisabledBackground;
                string disabledBorderBrush = theDisabledBorderBrush;
                string disabledForeground = theDisabledForeground;

                if (disabledBackground == null) { disabledBackground = ""; }
                if (disabledBorderBrush == null) { disabledBorderBrush = ""; }
                if (disabledForeground == null) { disabledForeground = ""; }

                if (disabledBackground.Length == 0) { disabledBackground = defaultDisabledBackground; }
                if (disabledBorderBrush.Length == 0) { disabledBorderBrush = defaultDisabledBorderBrush; }
                if (disabledForeground.Length == 0) { disabledForeground = defaultDisabledForeground; }

                string mainButtonStyleXAML = @"<Style xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' TargetType=""Button"">


    <Setter Property=""Template"">
        <Setter.Value>
            <ControlTemplate TargetType=""ButtonBase"">
                <Border
                    BorderThickness=""{TemplateBinding Border.BorderThickness}""
                    BorderBrush=""{TemplateBinding Border.BorderBrush}""
                    Background=""{TemplateBinding Panel.Background}""
                    Name=""BorderMain""
                    CornerRadius=""{CornerRadius}""
                    SnapsToDevicePixels=""True"">

                    <ContentPresenter
                        RecognizesAccessKey=""True""
                        Content=""{TemplateBinding ContentControl.Content}""
                        ContentTemplate=""{TemplateBinding ContentControl.ContentTemplate}""
                        ContentStringFormat=""{TemplateBinding ContentControl.ContentStringFormat}""
                        Name=""ContentPresenterMain""
                        Margin=""{TemplateBinding Control.Padding}""
                        HorizontalAlignment=""{TemplateBinding Control.HorizontalContentAlignment}""
                        VerticalAlignment=""{TemplateBinding Control.VerticalContentAlignment}""
                        SnapsToDevicePixels=""{TemplateBinding UIElement.SnapsToDevicePixels}""
                        Focusable=""False"" />
                </Border>

            <ControlTemplate.Triggers>

                <!-- Default -->
                <Trigger Property=""Button.IsDefaulted"" Value=""True"">
                    <Setter Property=""Border.BorderBrush"" TargetName=""BorderMain"">
                        <Setter.Value>
                            <DynamicResource
                                ResourceKey=""{x:Static SystemColors.HighlightBrushKey}"" />
                        </Setter.Value>
                    </Setter>
                </Trigger>

                <!-- Mouse Over -->
                <Trigger Property=""UIElement.IsMouseOver"" Value=""True"">
                    <Setter Property=""Panel.Background"" TargetName=""BorderMain"">
                        <Setter.Value>
                            <SolidColorBrush>{MouseOverBackground}</SolidColorBrush>
                        </Setter.Value>
                    </Setter>
                    <Setter Property=""Border.BorderBrush"" TargetName=""BorderMain"">
                        <Setter.Value>
                            <SolidColorBrush>{MouseOverBorderBrush}</SolidColorBrush>
                        </Setter.Value>
                    </Setter>
                    <Setter Property=""TextElement.Foreground"" TargetName=""ContentPresenterMain"">
                        <Setter.Value>
                            <SolidColorBrush>{MouseOverForeground}</SolidColorBrush>
                        </Setter.Value>
                    </Setter>
                </Trigger>

                <!-- Pressed -->
                <Trigger Property=""ButtonBase.IsPressed"" Value=""True"">
                    <Setter Property=""Panel.Background"" TargetName=""BorderMain"">
                        <Setter.Value>
                            <SolidColorBrush>{PressedBackground}</SolidColorBrush>
                        </Setter.Value>
                    </Setter>
                    <Setter Property=""Border.BorderBrush"" TargetName=""BorderMain"">
                        <Setter.Value>
                            <SolidColorBrush>{PressedBorderBrush}</SolidColorBrush>
                        </Setter.Value>
                    </Setter>
                    <Setter Property=""TextElement.Foreground"" TargetName=""ContentPresenterMain"">
                        <Setter.Value>
                            <SolidColorBrush>{PressedForeground}</SolidColorBrush>
                        </Setter.Value>
                    </Setter>
                </Trigger>

                <!-- Disabled -->
                <Trigger Property=""UIElement.IsEnabled"" Value=""False"">
                    <Setter Property=""Panel.Background"" TargetName=""BorderMain"">
                        <Setter.Value>
                            <SolidColorBrush>{DisabledBackground}</SolidColorBrush>
                        </Setter.Value>
                    </Setter>
                    <Setter Property=""Border.BorderBrush"" TargetName=""BorderMain"">
                        <Setter.Value>
                            <SolidColorBrush>{DisabledBorderBrush}</SolidColorBrush>
                        </Setter.Value>
                    </Setter>
                    <Setter Property=""TextElement.Foreground"" TargetName=""ContentPresenterMain"">
                        <Setter.Value>
                            <SolidColorBrush>{DisabledForeground}</SolidColorBrush>
                        </Setter.Value>
                    </Setter>
                </Trigger>

            </ControlTemplate.Triggers>

            </ControlTemplate>
        </Setter.Value>
    </Setter>

</Style>";



                // Replace values
                mainButtonStyleXAML = mainButtonStyleXAML.Replace("{CornerRadius}", cornerRadius.ToString());

                mainButtonStyleXAML = mainButtonStyleXAML.Replace("{MouseOverBackground}", mouseOverBackground);
                mainButtonStyleXAML = mainButtonStyleXAML.Replace("{MouseOverBorderBrush}", mouseOverBorderBrush);
                mainButtonStyleXAML = mainButtonStyleXAML.Replace("{MouseOverForeground}", mouseOverForeground);

                mainButtonStyleXAML = mainButtonStyleXAML.Replace("{PressedBackground}", pressedBackground);
                mainButtonStyleXAML = mainButtonStyleXAML.Replace("{PressedBorderBrush}", pressedBorderBrush);
                mainButtonStyleXAML = mainButtonStyleXAML.Replace("{PressedForeground}", pressedForeground);

                mainButtonStyleXAML = mainButtonStyleXAML.Replace("{DisabledBackground}", disabledBackground);
                mainButtonStyleXAML = mainButtonStyleXAML.Replace("{DisabledBorderBrush}", disabledBorderBrush);
                mainButtonStyleXAML = mainButtonStyleXAML.Replace("{DisabledForeground}", disabledForeground);

                StringReader mainButtonStyleXAMLStringReader = new StringReader(mainButtonStyleXAML);
                XmlReader mainButtonStyleXAMLXMLReader = XmlReader.Create(mainButtonStyleXAMLStringReader);
                Style mainButtonStyle = (Style)XamlReader.Load(mainButtonStyleXAMLXMLReader);

                toStyle.Style = mainButtonStyle;
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    "Error at 'SetButtonCornerRadiusAndTriggerStyling'" +
                        Environment.NewLine + Environment.NewLine +
                        ex.Message,
                    "Error",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
            }
        }

所以我不得不将XAML放入代码中,因为显然不推荐使用FrameworkElementFactory。

MSDN:

https://msdn.microsoft.com/en-us/library/system.windows.frameworkelementfactory(v=vs.110).aspx

在评论中:

  

”该类是通过编程方式创建模板的不赞成使用的方法,   它们是FrameworkTemplate的子类,例如ControlTemplate或   DataTemplate;在以下情况下,并非所有模板功能都可用   您可以使用此类创建模板。 推荐的方法   以编程方式创建模板是要从字符串或   XamlReader类的Load方法访问内存流。