C# 在后面的代码中创建样式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1729368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating a Style in code behind
提问by James
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:
有谁知道如何在后面的代码中创建 wpf 样式,我在网络或 MSDN 文档上找不到任何内容。我试过这个,但它不起作用:
Style s = new Style(typeof(TextBlock));
s.RegisterName("Foreground", Brushes.Green);
s.RegisterName("Text", "Green");
breakInfoControl.dataTextBlock.Style = s;
采纳答案by mjeanes
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.
您需要向样式添加 setter 而不是使用 RegisterName。以下代码在 Window_Loaded 事件中将创建一个新的 TextBlock 样式,该样式将成为 Window 中所有 TextBlock 实例的默认样式。如果您更愿意在一个特定的 TextBlock 上显式设置它,您可以设置该控件的 Style 属性,而不是将样式添加到 Resources 字典中。
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);
}
回答by oltman
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;