2014-08-30 9 views
6

Lassen Sie uns sagen, ich so etwas wie diese haben (in MainPage.xaml):Set Static Stil einer Kontrolle in Code hinter

<Page.Resources> 
    <Style TargetType="TextBlock" x:Key="TextBlockStyle"> 
     <Setter Property="FontFamily" Value="Segoe UI Light" /> 
     <Setter Property="Background" Value="Navy" /> 
    </Style> 
</Page.Resources> 

Dann würde ich diesen Stil Static meiner dynamischen anwenden möchte erstellt TextBlock (Datei MainPage.xaml.cs).

Gibt es eine Möglichkeit, dies zu tun, anstatt so etwas wie dies zu tun:

myTextBlock.FontFamily = new FontFamily("Segoe UI Light"); 
myTextBlock.Background = new SolidColorBrush(Color.FromArgb(255,0,0,128)); 

Antwort

6

Sie können einstellen, so etwas wie dies,

TextBlock myTextBlock= new TextBlock() 
    { 
     FontFamily = new FontFamily("Segoe UI Light"); 
     Style = Resources["TextBlockStyle"] as Style, 
    }; 
+0

Ich sehe, das ist alt, aber weiß jemand genau wie mit FrameworkElementFactory (Typeof (TextBlock))? – grinder22

1

Sie können diese verwenden:

Style textBlockStyle; 
try 
{ 
    textBlockStyle = FindResource("TextBlockStyle") as Style; 
} 
catch(Exception ex) 
{ 
    // exception handling 
} 

if(textBlockStyle != null) 
{ 
    myTextBlock.Style = textBlockStyle; 
} 

oder TryFindResource Ansatz:

myTextBlock.Style = (Style)TryFindResource("TextBlockStyle");