有谁知道如何在代码后面创建一个wpf样式,我在网络或MSDN文档上找不到任何东西。我试过这个但是没有用:
Style s = new Style(typeof(TextBlock));
s.RegisterName("Foreground", Brushes.Green);
s.RegisterName("Text", "Green");
breakInfoControl.dataTextBlock.Style = s;
答案 0 :(得分:74)
您需要在样式中添加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);
}
答案 1 :(得分:9)
这可以满足您的需求:
Style style = new Style
{
TargetType = typeof(Control)
};
style.Setters.Add(new Setter(Control.ForegroundProperty, Brushes.Green));
myControl.Style = style;