在代码后台创建样式

36

有人知道如何在WPF中通过代码创建样式吗?我在网上和MSDN文档中找不到任何信息。我已经尝试了下面的代码,但它不起作用:

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

breakInfoControl.dataTextBlock.Style = s;
2个回答

89

你需要给样式添加setter而不是使用RegisterName。下面的代码将在Window_Loaded事件中创建一个新的TextBlock样式,该样式将成为窗口内所有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);
}

我也在想怎么做这件事。谢谢你的解决方案,这对我有用。 - Ron Todosichuk

11

这应该可以帮你得到你需要的:

Style style = new Style
{
    TargetType = typeof(Control)
};
style.Setters.Add(new Setter(Control.ForegroundProperty, Brushes.Green));
myControl.Style = style;

2
这个答案也是来自5年前的,所以事情可能已经发生了变化。 - oltman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接