创建于code样式的背后 [英] Creating a Style in code behind

查看:169
本文介绍了创建于code样式的背后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道如何落后创造code WPF的风格,我无法找到网页或MSDN文档上的任何东西。我曾经试过,但它不工作:

 样式S =新样式(typeof运算(TextBlock中));
s.RegisterName(前景,Brushes.Green);
s.RegisterName(文本,绿);

breakInfoControl.dataTextBlock.Style =秒;
 

解决方案

您需要制定者添加到样式,而不是使用RegisterName。下面code,在Window_Loaded事件,将创建一个新的TextBlock风格,将成为默认的窗口中TextBlock的所有实例。如果您想明确地在一个特定的TextBlock设置,您可以设置控件的样式属性,而不是添加样式的资源字典。

 私人无效Window_Loaded(对象发件人,RoutedEventArgs E)
{
    款式风格=新样式(typeof运算(TextBlock中));
    style.Setters.Add(新二传手(TextBlock.ForegroundProperty,Brushes.Green));
    style.Setters.Add(新二传手(TextBlock.TextProperty,绿色));
    Resources.Add(typeof运算(TextBlock中),样式);
}
 

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;

解决方案

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

这篇关于创建于code样式的背后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆