Set button style in code

How do I set the style of a button? I am using 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;

      

I am getting the error

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

      

+3


source to share


2 answers


Make sure to use WPF Libraries, not WindowsForms or GDI + files ...

What should you use: System.Windows.Media.Brushes

which contains DarkGreen

both System.Windows.Media.SolidColorBrush

(in PresentationCore.dll).



You are currently using System.Drawing.Brushes

and System.Drawing.SolidBrush

.

+4


source


TextElement.Foreground

has a typeSystem.Windows.Media.Brush

. What is this "data type". You must assign it a value of this type or some subclass of this type.

System.Drawing.Brushes.DarkGreen

is of a type System.Drawing.Brush

that is not a subclass System.Windows.Media.Brushes

. This is from Windows Forms or something, not WPF. You need to use the WPF Brush Object for the WPF control.

Get rid of using System.Drawing;

at the top of your C # file. In a WPF project, this will only cause trouble. Use instead System.Windows.Media.Brushes.DarkGreen

.

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

      

You can also create a style as a XAML resource and load it using FindResource()

. Then you just say "DarkGreen" and let the XAML parser worry about which brush to create:



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

      

FROM#

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

      

But then you have to worry about defining it somewhere where you can find it, and what you are doing will work fine as long as you just use the correct Brush class.

It's pretty awful that we have multiple named classes Brush

in multiple .NET namespaces with uninformative names like "System.Windows.Media" and "System.Drawing", but unfortunately it all just grew this way,

+2


source







All Articles