为什么我的WPF样式不起作用?

Bil*_*ves 5 wpf resources styles

尝试在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>
Run Code Online (Sandbox Code Playgroud)

我的按钮XAML如下:

<Button Content="Click Me!" Style="{StaticResource TestStyle}" />
Run Code Online (Sandbox Code Playgroud)

在设计器中,一切看起来都不错,但是当我运行代码时,它失败了:

Provide value on 'System.Windows.StaticResourceExtension' threw an exception.
Run Code Online (Sandbox Code Playgroud)

我已经盯着它看了好多年了,但是找不到问题!

编辑

这似乎与整个应用程序有关。如果我将代码复制到另一个新项目中,则可以正常工作。唯一的区别是使用“ StartupUri =” MainWindow.xaml“加载了窗口。在不起作用的窗口中,我在App.Startup期间按如下方式加载了窗口:

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);
    new TestWindow().Show();
}
Run Code Online (Sandbox Code Playgroud)

找到了问题-我错过了InitializeComponent调用。现在,样式可以在最终产品中使用,而不能在设计师中使用。我要问一个单独的问题。

Ehs*_*adi 5

解决方法:只需为 Application 对象定义一个名称:

< 应用程序 x:Name="应用程序" ...

它对我有用!

  • 这很有趣,因为它确实有效!知道为什么吗?对我来说没有任何意义... (2认同)

gga*_*ber 0

您可以尝试使用{DynamicResource TestStyle}。当您将 TestStyle 应用到 Button 时,可能尚未创建 TestStyle。