在代码中设置按钮样式

3
我该如何设置按钮的样式?我使用Xceed.wpf.toolkit。
 Xceed.Wpf.Toolkit.MessageBox mbox = new Xceed.Wpf.Toolkit.MessageBox();
 System.Windows.Style style = new System.Windows.Style(typeof(System.Windows.Controls.Button));
 style.Setters.Add( new System.Windows.Setter(System.Windows.Controls.Button.ForegroundProperty, Brushes.DarkGreen));
 mbox.OkButtonStyle = style;

我遇到了错误

System.Windows.Markup.XamlParseException: ''System.Drawing.SolidBrush' is not a valid value for the 'System.Windows.Documents.TextElement.Foreground' property on a Setter.'

1
只是因为我感兴趣:为什么不在WPF中设置样式呢? - Mighty Badaboom
2个回答

5

请务必使用WPF库,而不是WindowsForms或GDI+库...

您应该使用System.Windows.Media.Brushes,其中包含DarkGreen作为System.Windows.Media.SolidColorBrush(在PresentationCore.dll中)。

您当前正在使用的是System.Drawing.BrushesSystem.Drawing.SolidBrush


2

TextElement.ForegroundSystem.Windows.Media.Brush类型的。这就是它的“数据类型”。您必须为其分配该类型的值或该类型的某个子类的值。

System.Drawing.Brushes.DarkGreenSystem.Drawing.Brush类型的,不是System.Windows.Media.Brushes的子类。那是来自Windows Forms或其他什么东西,而不是WPF。您需要使用WPF刷子对象来控制WPF。

在C#文件顶部去掉using System.Drawing;。在WPF项目中,这会给您带来麻烦。改用System.Windows.Media.Brushes.DarkGreen

style.Setters.Add( new System.Windows.Setter(System.Windows.Controls.Button.ForegroundProperty, 
    System.Windows.Media.Brushes.DarkGreen));

您还可以将样式创建为XAML资源,并使用FindResource()进行加载。然后,您只需说"DarkGreen",让XAML解析器担心要创建何种画笔:

<Style 
    x:Key="XCeedMBoxButtonStyle" 
    TargetType="{x:Type Button}" 
    BasedOn="{StaticResource {x:Type Button}}"
    >
    <Setter Property="TextElement.Foreground" Value="DarkGreen" />
</Style>

C#

var style = FindResource("XCeedMBoxButtonStyle") as Style;

但是,接下来你需要担心在某个地方定义它,以便可以找到它,并且如果只使用正确的Brush类,那么你所做的工作将会工作得不错。

我们拥有多个名为Brush的类存在于多个.NET命名空间中,名称并不具有信息性,例如"System.Windows.Media"与"System.Drawing",这真的很可怕,但不幸的是,它就是这样发展起来的。


1
啊,你比我快了8秒 xD - grek40

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接