2010-08-06 41 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

相關問題