创建于code样式的背后样式、创建于、code

2023-09-02 11:54:07 作者:累世情缘

有谁知道如何落后创造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中),样式);
}
 
vscode 编辑器样式 设置背景图片

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