One, what is the resource
WPF resources are typically used as a simple way to reuse commonly defined objects and values. For example, define a brush object that can be reused, and the background of the button and the fill color of the rectangle use this brush:
1: <Window x:Class="WPFResource.WinBasicResource"
2: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation& quot;
3: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4: Title="Basic Resource" Height="200" Width="300">
5: <Window.Resources>
6: <SolidColorBrush x:Key="myBrush" Color="Gold" />
7: </Window.Resources>
8: <StackPanel>
9: <Button Margin="5" Content="Sample Button" Background="{StaticResource myBrush}" />
10: <Rectangle Margin="5" Width="100" Height="100" Fill=" {StaticResource myBrush}" />
11: </StackPanel>
12: </Window>
Resources in WPF are often used as style, style templates, data templates, and so on.
Ii. definition of resources and references in XAML
Resources can be defined in several locations:
Application-level resources: defined in the App.xaml file as a resource that is shared by the entire application
Defined in the App.xaml file:
1: <Application x:Class="WPFResource.App"
2: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation& quot;
3: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4: StartupUri="Window1.xaml">
5: <Application.Resources>
6: <SolidColorBrush Color="Gold" x:Key="myGoldBrush" />
7: </Application.Resources>
8: </Application>
Use the resource defined in App.xaml in the Applicationresourcedemo.xaml file (form)
1: <Window x:Class="WPFResource.ApplicationResourceDemo"
2: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation& quot;
3: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4: Title="Application Resource Demo" Height="300" Width="300">
5: <StackPanel>
6: <Button Margin="5" Background="{StaticResource myGoldBrush}">Sample Button</Button>
7: </StackPanel>
8: </Window>
Form-level resources: defined as a resource that is shared as a form or page in Windows or pages
1: <Window x:Class="WPFResource.WindowResourceDemo"
2: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation& quot;
3: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4: Title="WindowResourceDemo" Height="300" Width="300">
5: <Window.Resources>
6: <SolidColorBrush x:Key="myRedBrush" Color="Red" />
7: </Window.Resources>
8: <StackPanel>
9: <Button Margin="5" Background="{StaticResource myRedBrush} ">Sample Button</Button>
10: </StackPanel>
11: </Window>