【问题标题】:Why doesn't my WPF style work?为什么我的 WPF 样式不起作用?
【发布时间】: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 调用。现在这些样式在最终产品中起作用,但在设计师中不起作用。我要问一个单独的问题。

【问题讨论】:

    标签: wpf resources styles


    【解决方案1】:

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

    它对我有用!

    【讨论】:

    • 这很有趣,因为它确实有效!知道为什么吗?对我来说没有任何意义......
    • 非常迷人!
    【解决方案2】:

    根据您的编辑:如果您在原始 xaml 中有 StartupUri="MainWindow.xaml",但是(正如您的代码 sn-p 建议的那样)您实际上有一个名为 TestWindow.xaml 的文件,这可能是问题所在!尝试在原始项目中将其更改为StartupUri="TestWindow.xaml"....

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • 运行但未应用样式。
      【解决方案4】:

      试试这个...

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

      通常,在 WPF 中,您希望 TargetType 的格式为 {x:Type ...}
      在 silverlight 中,您将使用 TargetType="Button"

      【讨论】:

      • 两者在运行时是等价的。使用 x:Type 会增加一些编译时间检查。
      猜你喜欢
      • 2017-10-02
      • 1970-01-01
      • 2016-01-14
      • 2014-01-29
      • 2011-01-16
      • 1970-01-01
      • 2011-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多