为什么';这不是我的WPF风格的作品吗?

为什么';这不是我的WPF风格的作品吗?,wpf,resources,styles,Wpf,Resources,Styles,正在尝试在app.xaml中添加样式。My 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.Reso

正在尝试在app.xaml中添加样式。My 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>
我已经盯着它看了很久了,但还是没发现问题

编辑

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

<Button Content="Click Me!" Style="{StaticResource TestStyle}" />
protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);
    new TestWindow().Show();
}

解决方案


发现问题-我缺少InitializeComponent调用。现在样式在最终产品中有效,但在设计器中无效。我将单独询问一个问题。

您可以尝试使用{DynamicSource TestStyle}。当您将其应用于按钮时,可能尚未创建TestStyle。

尝试此

<Style x:Key="TestStyle" TargetType="{x:Type Button}">
   <Setter Property="Background" Value="Red"/>
</Style>

通常,在WPF中,您希望TargetType的格式为
{x:Type…}


在silverlight中,您可以根据您的编辑使用
TargetType=“Button”

:如果原始xaml中有
StartupUri=“MainWindow.xaml”
,但(正如代码片段所示)实际上有一个名为
TestWindow.xaml的文件,这可能是问题所在!请尝试将其更改为
StartupUri=“TestWindow.xaml>“
在原始项目中….

解决方法:只需定义应用程序对象的名称:


这对我有用

运行,但不应用样式。这两者在运行时是等效的。使用x:Type添加了一些编译时检查。这很有趣,因为它实际上可以工作!知道为什么吗?对我来说没有任何意义…可笑的迷人!
<Style x:Key="TestStyle" TargetType="{x:Type Button}">
   <Setter Property="Background" Value="Red"/>
</Style>