Here we will see that how to use Resources.Add
to add static resource from code in WPF and XAML.
Creating Static resource
We create a static resource for the TextBlock
control and static resource has the key name brushGradient and also we make a
StaticResource thicknessMargin to show the margin between both TextBlock text.
<Window.Resources>
<LinearGradientBrush
x:Key="brushGradient"
StartPoint="0, 0"
EndPoint="1, 1">
<LinearGradientBrush.GradientStops>
<GradientStop
Offset="0"
Color="Black"
/>
<GradientStop
Offset="0.5"
Color="Green"
/>
<GradientStop
Offset="1"
Color="Gold"
/>
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>
</Window.Resources>
<StackPanel>
<TextBlock
Margin="{StaticResource
thicknessMargin}"
Foreground="{StaticResource
brushGradient}">
This is a TextBlock control.
</TextBlock>
<TextBlock
Margin="{StaticResource
thicknessMargin}"
Foreground="{StaticResource
brushGradient}">
This is a another TextBlock control.
</TextBlock>
</StackPanel>
The form looks like the below Figure.

Figure1.gif
Now using Resources.Add
method to add the static resource from code.
Imports
System
Imports
System.Windows
Imports
System.Windows.Controls
Imports
System.Windows.Data
Imports
System.Windows.Documents
Imports
System.Windows.Media
Imports
System.Windows.Media.Imaging
Imports
System.Windows.Shapes
Class
MainWindow
Public Sub
New()
Resources.Add("thicknessMargin",
New Thickness(24,
12, 24, 23))
InitializeComponent()
End Sub
End
Class
Now run the application and test the application.
Figure2.gif.