Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set button style in code behind

Tags:

c#

wpf

xceed

How can I set the style of a Button? I use 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 get 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.'
like image 977
daniel Avatar asked Nov 28 '25 06:11

daniel


2 Answers

Be sure to use the WPF libraries and not the WindowsForms or GDI+ ones...

What you should use: System.Windows.Media.Brushes which contains DarkGreen as System.Windows.Media.SolidColorBrush (in PresentationCore.dll).

What you currently use is System.Drawing.Brushes and System.Drawing.SolidBrush.

like image 97
grek40 Avatar answered Nov 30 '25 19:11

grek40


TextElement.Foreground is of type System.Windows.Media.Brush. That's it's "data type". You have to assign it a value of that type, or some subclass of that type.

System.Drawing.Brushes.DarkGreen is of type System.Drawing.Brush, which is not a subclass of System.Windows.Media.Brushes. That's from Windows Forms or something, not WPF. You need to use a WPF brush object for a WPF control.

Get rid of using System.Drawing; at the top of your C# file. In a WPF project, that'll cause you nothing but trouble. Use System.Windows.Media.Brushes.DarkGreen instead.

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

You could also create the Style as a XAML resource and load it with FindResource(). Then you'd just say "DarkGreen" and let the XAML parser worry about what kind of brush to create:

<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;

But then you've got to worry about defining it someplace where it can be found, and what you're doing will work OK anyhow if you just use the right Brush class.

It's pretty gruesome that we've got multiple classes called Brush in multiple .NET namespaces with uninformative names like "System.Windows.Media" vs "System.Drawing", but unfortunately it all just sort of grew that way.

like image 37
15ee8f99-57ff-4f92-890c-b56153 Avatar answered Nov 30 '25 20:11

15ee8f99-57ff-4f92-890c-b56153



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!