尝试在app.xaml中应用样式。我的app.xaml如下:
<Application x:Class="TestApp.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Application.Resources>
<Style x:Key="TestStyle" TargetType="Button">
<Setter Property="Background" Value="Red"/>
</Style>
</Application.Resources>
</Application>
<Button Content="Click Me!" Style="{StaticResource TestStyle}" />
在设计师中一切看起来都很正常,但当我运行代码时它失败并显示以下错误信息:
Provide value on 'System.Windows.StaticResourceExtension' threw an exception.
我已经盯着这个问题很久了,但是找不到问题所在!
编辑
似乎与整个应用程序有关。如果我将我的代码复制到另一个新项目中,它可以正常工作。唯一的区别是加载窗口时使用了“StartupUri = MainWindow.xaml”。在不起作用的那个中,我在App.Startup期间加载窗口,如下所示:
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
new TestWindow().Show();
}
解决方案
找到了问题所在——我没有调用InitializeComponent。现在样式在最终产品中起作用,但在设计师中不起作用。我将另外提出一个问题。