有人知道如何在WPF中通过代码创建样式吗?我在网上和MSDN文档中找不到任何信息。我已经尝试了下面的代码,但它不起作用:
Style s = new Style(typeof(TextBlock));
s.RegisterName("Foreground", Brushes.Green);
s.RegisterName("Text", "Green");
breakInfoControl.dataTextBlock.Style = s;
有人知道如何在WPF中通过代码创建样式吗?我在网上和MSDN文档中找不到任何信息。我已经尝试了下面的代码,但它不起作用:
Style s = new Style(typeof(TextBlock));
s.RegisterName("Foreground", Brushes.Green);
s.RegisterName("Text", "Green");
breakInfoControl.dataTextBlock.Style = s;
你需要给样式添加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);
}
这应该可以帮你得到你需要的:
Style style = new Style
{
TargetType = typeof(Control)
};
style.Setters.Add(new Setter(Control.ForegroundProperty, Brushes.Green));
myControl.Style = style;