Creating a Style in code behind
Asked Answered
R

2

37

Does anyone know how to create a wpf Style in code behind, I can't find anything on the web or MSDN docs. I have tried this but it is not working:

Style s = new Style(typeof(TextBlock));
s.RegisterName("Foreground", Brushes.Green);
s.RegisterName("Text", "Green");

breakInfoControl.dataTextBlock.Style = s;
Ripe answered 13/11, 2009 at 14:0 Comment(0)
C
90

You need to add setters to the style rather than using RegisterName. The following code, in the Window_Loaded event, will create a new TextBlock style which will become the default for all instances of a TextBlock within the Window. If you'd rather set it explicitly on one particular TextBlock, you can set the Style property of that control rather than adding the style to the Resources dictionary.

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    Style style = new Style(typeof (TextBlock));
    style.Setters.Add(new Setter(TextBlock.ForegroundProperty, Brushes.Green));
    style.Setters.Add(new Setter(TextBlock.TextProperty, "Green"));
    Resources.Add(typeof (TextBlock), style);
}
Cruciferous answered 13/11, 2009 at 14:31 Comment(1)
I was wondering how to do this as well. Thank for the solution this worked for me.Dann
D
12

This should get you what you need:

Style style = new Style
{
    TargetType = typeof(Control)
};
style.Setters.Add(new Setter(Control.ForegroundProperty, Brushes.Green));
myControl.Style = style;
Deliver answered 13/11, 2009 at 14:31 Comment(1)
This answer is also from 5 years ago, so things may have changed since thenDeliver

© 2022 - 2024 — McMap. All rights reserved.