尝试在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>
我针对该按钮的XAML如下:
<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调用。现在,样式可以在最终产品中使用,而不能在设计师中使用。我要问一个单独的问题。
最佳答案
解决方法:只需为应用程序对象定义一个名称:
它为我工作!