Set the StaticResource style of the control in code

Let's say I have something like this (in MainPage.xaml):

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

Then I would like to apply this StaticResource style to a dynamically created TextBlock (MainPage.xaml.cs file).

Is there any way to do this instead of doing something like this:

 myTextBlock.FontFamily = new FontFamily("Segoe UI Light"); myTextBlock.Background = new SolidColorBrush(Color.FromArgb(255,0,0,128)); 
+6
source share
2 answers

You can install something like this,

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

You can use this:

 Style textBlockStyle; try { textBlockStyle = FindResource("TextBlockStyle") as Style; } catch(Exception ex) { // exception handling } if(textBlockStyle != null) { myTextBlock.Style = textBlockStyle; } 

or TryFindResource :

 myTextBlock.Style = (Style)TryFindResource("TextBlockStyle"); 
+1
source

Source: https://habr.com/ru/post/974589/


All Articles