2010-08-06 108 views
4

尝试在app.xaml中添加样式。我的App.xaml中写道:是为什么我的WPF样式不工作? [已解决]

<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(); 
} 

SOLUTION

发现了问题 - 我是缺少一个InitializeComponent调用现在的风格在最终产品中工作,但不是在设计师,我要问一个单独的问题吧

回答

0

你可以用一试。 {DynamicResource TestStyle}。当你将它应用到Button时,TestStyle可能还没有创建。

+0

即将运行但不适用样式。 – 2010-08-06 16:32:24

0

试试这个...

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

,在WPF中,你希望你的TargetType是形式的{x:Type ...}
在Silverlight中,你可以使用TargetType="Button"

+0

没有帮助:( – 2010-08-06 16:43:01

+0

这两个在运行时是等价的,使用x:Type会增加一些编译时间检查 – 2010-08-06 17:11:16

1

根据您的修改:如果你”在原始的xaml中得到了StartupUri="MainWindow.xaml",但是(正如你的代码片断所暗示的),你实际上有一个名为TestWindow.xaml的文件,这可能是问题!尝试将其更改为原项目StartupUri="TestWindow.xaml" ....

4

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

<应用X:NAME = “应用程序” ......

它为我工作!

+1

这很吸引人,因为它真的有效!任何想法为什么这样?对我没有任何意义.. 。 – walther 2013-09-09 17:42:54

+0

可笑的迷人! – dotNET 2014-02-07 06:14:25

相关问题