Jam*_*mes 31 .net c# wpf styles code-behind
有谁知道如何在代码背后创建一个wpf样式,我在网络或MSDN文档上找不到任何东西.我试过这个,但它不起作用:
Style s = new Style(typeof(TextBlock));
s.RegisterName("Foreground", Brushes.Green);
s.RegisterName("Text", "Green");
breakInfoControl.dataTextBlock.Style = s;
Run Code Online (Sandbox Code Playgroud)
mje*_*nes 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);
}
Run Code Online (Sandbox Code Playgroud)
这应该可以满足您的需求:
Style style = new Style
{
TargetType = typeof(Control)
};
style.Setters.Add(new Setter(Control.ForegroundProperty, Brushes.Green));
myControl.Style = style;
Run Code Online (Sandbox Code Playgroud)