【发布时间】:2010-08-06 16:20:19
【问题描述】:
尝试在 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 调用。现在这些样式在最终产品中起作用,但在设计师中不起作用。我要问一个单独的问题。
【问题讨论】: