WPF默认窗口样式覆盖

时间:2012-04-04 14:27:27

标签: wpf styles

有没有办法在WPF应用程序中创建一个样式,它将覆盖所有窗口的Window类型的样式?

即;

<Style x:Key="{x:Type Window}"
   TargetType="{x:Type Window}" >
    <Setter Property="Background" Value="Black" />
</Style>

在App.xaml中或App.xaml中引用的资源字典。

1 个答案:

答案 0 :(得分:1)

简短的回答是:这是不可能的。

解释 有很多类似的问题: WPF Window Style not working at runtime
WPF window style not being applied
How to set default WPF Window Style in app.xaml?

  

样式中的TargetType不管理派生类型。

您不是在创建Window类,而是从它派生的类。如果您创建了Window类的实例,则应该应用该样式。

Dim frm As New Window
frm.Show()

但是,它不起作用(至少在4.0中),我的Application.xaml中的样式不会在运行时应用。解决方法是:

在运行时加载资源字典:

Dim app As Application = New Application()
Application.Current.Resources.MergedDictionaries.Add(Application.LoadComponent(New Uri("/MyProject;component/MainDictionary.xaml", UriKind.Relative)))

在运行时创建样式

Sub Main()
 Dim app As Application = New Application()
 Dim sty As Style
 sty = New Style With {.TargetType = GetType(Window)}
 sty.Setters.Add(New Setter With {.Property = Control.BackgroundProperty, .Value = Brushes.Red})
 Application.Current.Resources.Add(GetType(Window), sty)
 Dim frm As New Window
 frm.ShowDialog()
End Sub

窗口有所需的背景。我认为这是一个错误。

相关问题