2012-05-21 37 views
53

在App.xaml中,我有以下代碼:在代碼中設置WPF標籤的Style屬性?

<Application.Resources> 
    <Style x:Key="LabelTemplate" TargetType="{x:Type Label}"> 
     <Setter Property="Height" Value="53" /> 
     <Setter Property="Width" Value="130" /> 
     <Setter Property="HorizontalAlignment" Value="Left" /> 
     <Setter Property="Margin" Value="99,71,0,0" /> 
     <Setter Property="VerticalAlignment" Value= "Top" /> 
     <Setter Property="Foreground" Value="#FFE75959" /> 
     <Setter Property="FontFamily" Value="Calibri" /> 
     <Setter Property="FontSize" Value="40" /> 
    </Style> 
</Application.Resources> 

這是爲了我的標籤提供一個通用模板。

在主XAML代碼,我有下面的代碼行:

<Label Content="Movies" Style="{StaticResource LabelTemplate}" Name="label1" /> 

不過,我想通過代碼來初始化樣式屬性。我曾嘗試:

label1.Style = new Style("{StaticResource LabelTemplate}"); 

label1.Style = "{StaticResource LabelTemplate}"; 

無論解決方案是有效的。

任何幫助將不勝感激:)。

+0

是否有任何理由從UserControl的代碼隱藏中做到這一點?也許有更優雅的解決方案。 – csteinmueller

回答

127

代碼中的哪個位置試圖獲得樣式?代碼後面?如果你在其它地方

Style style = Application.Current.FindResource("LabelTemplate") as Style; 
label1.Style = style; 

底部注

Style style = this.FindResource("LabelTemplate") as Style; 
label1.Style = style; 

:如果您在代碼隱藏是

你應該這樣寫:不會用關鍵字命名StyleTemplate,你最終會混淆StyleTemplate,你不應該認爲這是兩個不同的概念。

+1

不錯的一個繼續發佈很好的建議.... –

+0

我發現使用「應用程序」.Current.FindResource()而不是「應用程序」。 – Seva

+0

我沒有找到FindResource找不到 –

2

請檢查零風格的結果,否則你會傷心... ... if(style!= null) this.Style = style;

+5

當它爲空時,您可以哭泣或修理並糾正問題。 – Allen

0

也許一個老問題,但如果你想W10 UWP應用程序必須使用應用程序對象的每個對象或資源集合的資源集合

KeyValuePair<object,object> styl = this.Resources 
    .Where(x => x.Key.ToString() == "MyStyleTemplateName") 
    .FirstOrDefault(); 
if (styl.Value != null) 
    Style MyStyle = (Style)styl.Value; 

MyStyleTemplateName必須被定義爲這個資源