mirror of
https://github.com/Stone-Red-Code/docs-desktop.git
synced 2026-09-06 16:06:07 +02:00
WPF publish initial content (#1032)
* Add overview article for new WPF (#178) * Remove previous WPF .NET 5 content * Overview article * New article: Create new WPF project (#183) * Basic index file * Finish article for new project. * acro * markdown fix * Fix build errors * fix code lang * fix code lang * Add differences article for WPF (#186) * Fix VS version for create app * Add differences article * Minor * fix overview styles code * Add code langs for overview * Port Window Overview WPF article (#1011) * Add Window overview article * Add TOC * Remove temp code * Fix headers * Port final Windows related articles (#1015) * Initial test commit * Add system dialogs * 75% complete * Add images * Fix linter * Add to toc * Add more howto * Fix code * Add get/set main window * Add missing code * Add to toc * Fix warnings * Fix warnings * missing code * Update see also * fix xref * Migrate wpf net core controls-styles articles (#1023) * Migrate control-styles * Fix links * Fix links * Port databinding article. (#1022) * Migrated databinding overview * update toc * Fix links/snippets * fix links * Move to correct folder * Port initial resources docs (#1026) * initial resources docs * Build errors * Update dotnet-desktop-guide/net/wpf/systems/xaml-resources-overview.md Co-authored-by: Genevieve Warren <[email protected]> * Apply suggestions from code review Co-authored-by: Genevieve Warren <[email protected]> * Feedback * Add app article * Add system article * Minor * meta * fix toc * Apply suggestions from code review Co-authored-by: Genevieve Warren <[email protected]> Co-authored-by: Genevieve Warren <[email protected]> * Add xaml article * reformat redirect * Redirects * WPF update XAML article (#1031) * convert snippets * minor edits * minor * Fix warnings * Fixes #1028 * Fixes #1028 * Apply suggestions from code review Co-authored-by: Genevieve Warren <[email protected]> * update redirects Co-authored-by: Genevieve Warren <[email protected]> * minor updates to link * Readd migration article * Warning fixes * Fix lint * Minor updates * Fix warnings for TOC/YML * last warnings Co-authored-by: Genevieve Warren <[email protected]>
This commit is contained in:
co-authored by
Genevieve Warren
parent
a3b012ae99
commit
ea8529f082
BIN
Binary file not shown.
|
After Width: | Height: | Size: 6.3 KiB |
BIN
Binary file not shown.
|
After Width: | Height: | Size: 4.5 KiB |
@@ -0,0 +1,9 @@
|
||||
<Application x:Class="csharp.App"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:local="clr-namespace:csharp"
|
||||
StartupUri="MainWindow.xaml">
|
||||
<Application.Resources>
|
||||
|
||||
</Application.Resources>
|
||||
</Application>
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Configuration;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
|
||||
namespace csharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Interaction logic for App.xaml
|
||||
/// </summary>
|
||||
public partial class App : Application
|
||||
{
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
using System.Windows;
|
||||
|
||||
[assembly:ThemeInfo(
|
||||
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
|
||||
//(used if a resource is not found in the page,
|
||||
// or application resource dictionaries)
|
||||
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
|
||||
//(used if a resource is not found in the page,
|
||||
// app, or any theme specific resource dictionaries)
|
||||
)]
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
<Window x:Class="csharp.MainWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:local="clr-namespace:csharp"
|
||||
mc:Ignorable="d"
|
||||
Title="MainWindow" Height="450" Width="800">
|
||||
<Window.Resources>
|
||||
<LinearGradientBrush x:Key="RainbowBrush" StartPoint="0,0" EndPoint="1,1">
|
||||
<GradientStop Color="Red" Offset="0.0"/>
|
||||
<GradientStop Color="Orange" Offset="0.17"/>
|
||||
<GradientStop Color="Yellow" Offset="0.33"/>
|
||||
<GradientStop Color="Green" Offset="0.5"/>
|
||||
<GradientStop Color="Blue" Offset="0.67"/>
|
||||
<GradientStop Color="Indigo" Offset="0.83"/>
|
||||
<GradientStop Color="Violet" Offset="1.0"/>
|
||||
</LinearGradientBrush>
|
||||
</Window.Resources>
|
||||
<Grid>
|
||||
<Button x:Name="myButton" Click="myButton_Click">Click Me</Button>
|
||||
</Grid>
|
||||
</Window>
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Data;
|
||||
using System.Windows.Documents;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using System.Windows.Navigation;
|
||||
using System.Windows.Shapes;
|
||||
|
||||
namespace csharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Interaction logic for MainWindow.xaml
|
||||
/// </summary>
|
||||
public partial class MainWindow : Window
|
||||
{
|
||||
public MainWindow()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
//<ButtonBrush>
|
||||
private void myButton_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
Button button = (Button)sender;
|
||||
button.Background = (Brush)this.FindResource("RainbowBrush");
|
||||
}
|
||||
//</ButtonBrush>
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net5.0-windows</TargetFramework>
|
||||
<UseWPF>true</UseWPF>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="ResExample - Copy - Copy.xaml.cs">
|
||||
<SubType>Code</SubType>
|
||||
<DependentUpon>ResExample - Copy.xaml.cs</DependentUpon>
|
||||
</Compile>
|
||||
<Compile Update="ResExample - Copy.xaml.cs">
|
||||
<SubType>Code</SubType>
|
||||
<DependentUpon>ResExample.xaml.cs</DependentUpon>
|
||||
</Compile>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
<Application x:Class="Application"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:local="clr-namespace:vb"
|
||||
StartupUri="MainWindow.xaml">
|
||||
<Application.Resources>
|
||||
|
||||
</Application.Resources>
|
||||
</Application>
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
Class Application
|
||||
|
||||
' Application-level events, such as Startup, Exit, and DispatcherUnhandledException
|
||||
' can be handled in this file.
|
||||
|
||||
End Class
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
Imports System.Windows
|
||||
|
||||
'The ThemeInfo attribute describes where any theme specific and generic resource dictionaries can be found.
|
||||
'1st parameter: where theme specific resource dictionaries are located
|
||||
'(used if a resource is not found in the page,
|
||||
' or application resource dictionaries)
|
||||
|
||||
'2nd parameter: where the generic resource dictionary is located
|
||||
'(used if a resource is not found in the page,
|
||||
'app, and any theme specific resource dictionaries)
|
||||
<Assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)>
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
<Window x:Class="MainWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:local="clr-namespace:vb"
|
||||
mc:Ignorable="d"
|
||||
Title="MainWindow" Height="450" Width="800">
|
||||
<Window.Resources>
|
||||
<LinearGradientBrush x:Key="RainbowBrush" StartPoint="0,0" EndPoint="1,1">
|
||||
<GradientStop Color="Red" Offset="0.0"/>
|
||||
<GradientStop Color="Orange" Offset="0.17"/>
|
||||
<GradientStop Color="Yellow" Offset="0.33"/>
|
||||
<GradientStop Color="Green" Offset="0.5"/>
|
||||
<GradientStop Color="Blue" Offset="0.67"/>
|
||||
<GradientStop Color="Indigo" Offset="0.83"/>
|
||||
<GradientStop Color="Violet" Offset="1.0"/>
|
||||
</LinearGradientBrush>
|
||||
</Window.Resources>
|
||||
<Grid>
|
||||
<Button x:Name="myButton" Click="myButton_Click">Click Me</Button>
|
||||
</Grid>
|
||||
</Window>
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
Class MainWindow
|
||||
'<ButtonBrush>
|
||||
Private Sub myButton_Click(sender As Object, e As RoutedEventArgs)
|
||||
Dim buttonControl = DirectCast(sender, Button)
|
||||
buttonControl.Background = DirectCast(Me.FindResource("RainbowBrush"), Brush)
|
||||
End Sub
|
||||
'</ButtonBrush>
|
||||
End Class
|
||||
@@ -0,0 +1,22 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net5.0-windows</TargetFramework>
|
||||
<RootNamespace>vb</RootNamespace>
|
||||
<UseWPF>true</UseWPF>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Import Include="System.Windows" />
|
||||
<Import Include="System.Windows.Controls" />
|
||||
<Import Include="System.Windows.Data" />
|
||||
<Import Include="System.Windows.Documents" />
|
||||
<Import Include="System.Windows.Input" />
|
||||
<Import Include="System.Windows.Media" />
|
||||
<Import Include="System.Windows.Media.Imaging" />
|
||||
<Import Include="System.Windows.Navigation" />
|
||||
<Import Include="System.Windows.Shapes" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
<Application x:Class="csharp.App"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:local="clr-namespace:csharp"
|
||||
StartupUri="MainWindow.xaml">
|
||||
<Application.Resources>
|
||||
|
||||
</Application.Resources>
|
||||
</Application>
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Configuration;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
|
||||
namespace csharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Interaction logic for App.xaml
|
||||
/// </summary>
|
||||
public partial class App : Application
|
||||
{
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
using System.Windows;
|
||||
|
||||
[assembly:ThemeInfo(
|
||||
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
|
||||
//(used if a resource is not found in the page,
|
||||
// or application resource dictionaries)
|
||||
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
|
||||
//(used if a resource is not found in the page,
|
||||
// app, or any theme specific resource dictionaries)
|
||||
)]
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
<Window x:Class="csharp.MainWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:local="clr-namespace:csharp"
|
||||
mc:Ignorable="d"
|
||||
Title="MainWindow" Height="200" Width="200">
|
||||
<!--<MainXaml>-->
|
||||
<StackPanel Margin="5">
|
||||
<Button Click="Button_Click">Explicitly Styled</Button>
|
||||
<Button>Unstyled</Button>
|
||||
<Button>Unstyled</Button>
|
||||
<Button Style="{DynamicResource ResourceKey=buttonStyle1}">Dynamically Styled</Button>
|
||||
</StackPanel>
|
||||
<!--</MainXaml>-->
|
||||
</Window>
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Data;
|
||||
using System.Windows.Documents;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using System.Windows.Navigation;
|
||||
using System.Windows.Shapes;
|
||||
|
||||
namespace csharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Interaction logic for MainWindow.xaml
|
||||
/// </summary>
|
||||
public partial class MainWindow : Window
|
||||
{
|
||||
public MainWindow()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
// <CreateStyleCode>
|
||||
private void Button_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
// Create colors
|
||||
Color purple = (Color)ColorConverter.ConvertFromString("#4E1A3D");
|
||||
Color white = Colors.White;
|
||||
Color salmon = Colors.Salmon;
|
||||
|
||||
// Create a new style for a button
|
||||
var buttonStyle = new Style(typeof(Button));
|
||||
|
||||
// Set the properties of the style
|
||||
buttonStyle.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(purple)));
|
||||
buttonStyle.Setters.Add(new Setter(Control.ForegroundProperty, new SolidColorBrush(white)));
|
||||
buttonStyle.Setters.Add(new Setter(Control.BorderBrushProperty, new LinearGradientBrush(purple, salmon, 45d)));
|
||||
buttonStyle.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(5)));
|
||||
|
||||
// <SetResource>
|
||||
// Set this style as a resource. Any DynamicResource tied to this key will be updated.
|
||||
this.Resources["buttonStyle1"] = buttonStyle;
|
||||
// </SetResource>
|
||||
|
||||
// <SetButtonStyle>
|
||||
// Set this style directly to a button
|
||||
((Button)sender).Style = buttonStyle;
|
||||
// </SetButtonStyle>
|
||||
}
|
||||
// </CreateStyleCode>
|
||||
|
||||
private void ButtonFind_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
Button myButton = (Button)sender;
|
||||
|
||||
// <FindResource>
|
||||
myButton.Style = myButton.TryFindResource("buttonStyle1") as Style;
|
||||
// </FindResource>
|
||||
}
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
<Window x:Class="resources.ResExample"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
Title="ResExample" Height="400" Width="300">
|
||||
<!--<ResDefine>-->
|
||||
<Window.Resources>
|
||||
<SolidColorBrush x:Key="MyBrush" Color="#05E0E9"/>
|
||||
<Style TargetType="Border">
|
||||
<Setter Property="Background" Value="#4E1A3D" />
|
||||
<Setter Property="BorderThickness" Value="5" />
|
||||
<Setter Property="BorderBrush">
|
||||
<Setter.Value>
|
||||
<LinearGradientBrush>
|
||||
<GradientStop Offset="0.0" Color="#4E1A3D"/>
|
||||
<GradientStop Offset="1.0" Color="Salmon"/>
|
||||
</LinearGradientBrush>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
<Style TargetType="TextBlock" x:Key="TitleText">
|
||||
<Setter Property="FontSize" Value="18"/>
|
||||
<Setter Property="Foreground" Value="#4E87D4"/>
|
||||
<Setter Property="FontFamily" Value="Trebuchet MS"/>
|
||||
<Setter Property="Margin" Value="0,10,10,10"/>
|
||||
</Style>
|
||||
<Style TargetType="TextBlock" x:Key="Label">
|
||||
<Setter Property="HorizontalAlignment" Value="Right"/>
|
||||
<Setter Property="FontSize" Value="13"/>
|
||||
<Setter Property="Foreground" Value="{StaticResource MyBrush}"/>
|
||||
<Setter Property="FontFamily" Value="Arial"/>
|
||||
<Setter Property="FontWeight" Value="Bold"/>
|
||||
<Setter Property="Margin" Value="0,3,10,0"/>
|
||||
</Style>
|
||||
</Window.Resources>
|
||||
<!--</ResDefine>-->
|
||||
<!--<ResUsed>-->
|
||||
<Border>
|
||||
<StackPanel>
|
||||
<TextBlock Style="{StaticResource TitleText}">Title</TextBlock>
|
||||
<TextBlock Style="{StaticResource Label}">Label</TextBlock>
|
||||
<TextBlock HorizontalAlignment="Right" FontSize="36" Foreground="{StaticResource MyBrush}" Text="Text" Margin="20" />
|
||||
<Button HorizontalAlignment="Left" Height="30" Background="{StaticResource MyBrush}" Margin="40">Button</Button>
|
||||
<Ellipse HorizontalAlignment="Center" Width="100" Height="100" Fill="{StaticResource MyBrush}" Margin="10" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
<!--</ResUsed>-->
|
||||
|
||||
</Window>
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Data;
|
||||
using System.Windows.Documents;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using System.Windows.Shapes;
|
||||
|
||||
namespace resources
|
||||
{
|
||||
/// <summary>
|
||||
/// Interaction logic for ResExample.xaml
|
||||
/// </summary>
|
||||
public partial class ResExample : Window
|
||||
{
|
||||
public ResExample()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net5.0-windows</TargetFramework>
|
||||
<UseWPF>true</UseWPF>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="ResExample - Copy - Copy.xaml.cs">
|
||||
<SubType>Code</SubType>
|
||||
<DependentUpon>ResExample - Copy.xaml.cs</DependentUpon>
|
||||
</Compile>
|
||||
<Compile Update="ResExample - Copy.xaml.cs">
|
||||
<SubType>Code</SubType>
|
||||
<DependentUpon>ResExample.xaml.cs</DependentUpon>
|
||||
</Compile>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
<Application x:Class="Application"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:local="clr-namespace:vb"
|
||||
StartupUri="MainWindow.xaml">
|
||||
<Application.Resources>
|
||||
|
||||
</Application.Resources>
|
||||
</Application>
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
Class Application
|
||||
|
||||
' Application-level events, such as Startup, Exit, and DispatcherUnhandledException
|
||||
' can be handled in this file.
|
||||
|
||||
End Class
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
Imports System.Windows
|
||||
|
||||
'The ThemeInfo attribute describes where any theme specific and generic resource dictionaries can be found.
|
||||
'1st parameter: where theme specific resource dictionaries are located
|
||||
'(used if a resource is not found in the page,
|
||||
' or application resource dictionaries)
|
||||
|
||||
'2nd parameter: where the generic resource dictionary is located
|
||||
'(used if a resource is not found in the page,
|
||||
'app, and any theme specific resource dictionaries)
|
||||
<Assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)>
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
<Window x:Class="MainWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:local="clr-namespace:vb"
|
||||
mc:Ignorable="d"
|
||||
Title="MainWindow" Height="200" Width="200">
|
||||
<!--<MainXaml>-->
|
||||
<StackPanel Margin="5">
|
||||
<Button Click="Button_Click">Explicitly Styled</Button>
|
||||
<Button Click="ButtonFind_Click">Unstyled</Button>
|
||||
<Button>Unstyled</Button>
|
||||
<Button Style="{DynamicResource ResourceKey=buttonStyle1}">Dynamically Styled</Button>
|
||||
</StackPanel>
|
||||
<!--</MainXaml>-->
|
||||
</Window>
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
Class MainWindow
|
||||
'<CreateStyleCode>
|
||||
Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
|
||||
|
||||
'Create colors
|
||||
Dim purple = DirectCast(ColorConverter.ConvertFromString("#4E1A3D"), Color)
|
||||
Dim white = Colors.White
|
||||
Dim salmon = Colors.Salmon
|
||||
|
||||
'Create a new style for a button
|
||||
Dim buttonStyle As New Style()
|
||||
|
||||
'Set the properties of the style
|
||||
buttonStyle.Setters.Add(New Setter(Control.BackgroundProperty, New SolidColorBrush(purple)))
|
||||
buttonStyle.Setters.Add(New Setter(Control.ForegroundProperty, New SolidColorBrush(white)))
|
||||
buttonStyle.Setters.Add(New Setter(Control.BorderBrushProperty, New LinearGradientBrush(purple, salmon, 45D)))
|
||||
buttonStyle.Setters.Add(New Setter(Control.BorderThicknessProperty, New Thickness(5)))
|
||||
|
||||
'<SetResource>
|
||||
'Set this style as a resource. Any DynamicResource looking for this key will be updated.
|
||||
Me.Resources("buttonStyle1") = buttonStyle
|
||||
'</SetResource>
|
||||
|
||||
'<SetButtonStyle>
|
||||
'Set this style directly to a button
|
||||
DirectCast(sender, Button).Style = buttonStyle
|
||||
'</SetButtonStyle>
|
||||
|
||||
End Sub
|
||||
'</CreateStyleCode>
|
||||
|
||||
Private Sub ButtonFind_Click(sender As Object, e As RoutedEventArgs)
|
||||
Dim myButton As Button = DirectCast(sender, Button)
|
||||
|
||||
'<FindResource>
|
||||
myButton.Style = myButton.TryFindResource("buttonStyle1")
|
||||
'</FindResource>
|
||||
End Sub
|
||||
|
||||
End Class
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net5.0-windows</TargetFramework>
|
||||
<RootNamespace>vb</RootNamespace>
|
||||
<UseWPF>true</UseWPF>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Import Include="System.Windows" />
|
||||
<Import Include="System.Windows.Controls" />
|
||||
<Import Include="System.Windows.Data" />
|
||||
<Import Include="System.Windows.Documents" />
|
||||
<Import Include="System.Windows.Input" />
|
||||
<Import Include="System.Windows.Media" />
|
||||
<Import Include="System.Windows.Media.Imaging" />
|
||||
<Import Include="System.Windows.Navigation" />
|
||||
<Import Include="System.Windows.Shapes" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
<Application x:Class="SampleApplication.App"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
StartupUri="MainWindow.xaml">
|
||||
<!--<AppResources>-->
|
||||
<Application.Resources>
|
||||
<Style TargetType="Border" x:Key="FancyBorder">
|
||||
<Setter Property="Background" Value="#4E1A3D" />
|
||||
<Setter Property="BorderThickness" Value="5" />
|
||||
<Setter Property="BorderBrush">
|
||||
<Setter.Value>
|
||||
<LinearGradientBrush>
|
||||
<GradientStop Offset="0.0" Color="#4E1A3D"/>
|
||||
<GradientStop Offset="1.0" Color="Salmon"/>
|
||||
</LinearGradientBrush>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
</Application.Resources>
|
||||
<!--</AppResources>-->
|
||||
</Application>
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Configuration;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
|
||||
namespace SampleApplication
|
||||
{
|
||||
/// <summary>
|
||||
/// Interaction logic for App.xaml
|
||||
/// </summary>
|
||||
public partial class App : Application
|
||||
{
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
using System.Windows;
|
||||
|
||||
[assembly:ThemeInfo(
|
||||
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
|
||||
//(used if a resource is not found in the page,
|
||||
// or application resource dictionaries)
|
||||
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
|
||||
//(used if a resource is not found in the page,
|
||||
// app, or any theme specific resource dictionaries)
|
||||
)]
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
<Window x:Class="SampleApplication.MainWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
Title="MainWindow" Height="200" Width="200">
|
||||
<!--<AppResourcesExample>-->
|
||||
<Border Style="{StaticResource FancyBorder}">
|
||||
<StackPanel Margin="5">
|
||||
<Button>Button 1</Button>
|
||||
<Button>Button 2</Button>
|
||||
<Button>Button 3</Button>
|
||||
<Button>Button 4</Button>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
<!--</AppResourcesExample>-->
|
||||
</Window>
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Data;
|
||||
using System.Windows.Documents;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using System.Windows.Navigation;
|
||||
using System.Windows.Shapes;
|
||||
|
||||
namespace SampleApplication
|
||||
{
|
||||
/// <summary>
|
||||
/// Interaction logic for MainWindow.xaml
|
||||
/// </summary>
|
||||
public partial class MainWindow : Window
|
||||
{
|
||||
public MainWindow()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
// <CreateStyleCode>
|
||||
private void Button_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
// Create colors
|
||||
Color purple = (Color)ColorConverter.ConvertFromString("#4E1A3D");
|
||||
Color white = Colors.White;
|
||||
Color salmon = Colors.Salmon;
|
||||
|
||||
// Create a new style for a button
|
||||
var buttonStyle = new Style(typeof(Button));
|
||||
|
||||
// Set the properties of the style
|
||||
buttonStyle.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(purple)));
|
||||
buttonStyle.Setters.Add(new Setter(Control.ForegroundProperty, new SolidColorBrush(white)));
|
||||
buttonStyle.Setters.Add(new Setter(Control.BorderBrushProperty, new LinearGradientBrush(purple, salmon, 45d)));
|
||||
buttonStyle.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(5)));
|
||||
|
||||
// <SetResource>
|
||||
// Set this style as a resource. Any DynamicResource tied to this key will be updated.
|
||||
this.Resources["buttonStyle1"] = buttonStyle;
|
||||
// </SetResource>
|
||||
|
||||
// <SetButtonStyle>
|
||||
// Set this style directly to a button
|
||||
((Button)sender).Style = buttonStyle;
|
||||
// </SetButtonStyle>
|
||||
}
|
||||
// </CreateStyleCode>
|
||||
|
||||
private void ButtonFind_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
Button myButton = (Button)sender;
|
||||
|
||||
// <FindResource>
|
||||
myButton.Style = myButton.TryFindResource("buttonStyle1") as Style;
|
||||
// </FindResource>
|
||||
}
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net5.0-windows</TargetFramework>
|
||||
<UseWPF>true</UseWPF>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="ResExample - Copy - Copy.xaml.cs">
|
||||
<SubType>Code</SubType>
|
||||
<DependentUpon>ResExample - Copy.xaml.cs</DependentUpon>
|
||||
</Compile>
|
||||
<Compile Update="ResExample - Copy.xaml.cs">
|
||||
<SubType>Code</SubType>
|
||||
<DependentUpon>ResExample.xaml.cs</DependentUpon>
|
||||
</Compile>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
<Application x:Class="Application"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:local="clr-namespace:SampleApplication"
|
||||
StartupUri="MainWindow.xaml">
|
||||
<Application.Resources>
|
||||
|
||||
</Application.Resources>
|
||||
</Application>
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
Class Application
|
||||
|
||||
' Application-level events, such as Startup, Exit, and DispatcherUnhandledException
|
||||
' can be handled in this file.
|
||||
|
||||
End Class
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
Imports System.Windows
|
||||
|
||||
'The ThemeInfo attribute describes where any theme specific and generic resource dictionaries can be found.
|
||||
'1st parameter: where theme specific resource dictionaries are located
|
||||
'(used if a resource is not found in the page,
|
||||
' or application resource dictionaries)
|
||||
|
||||
'2nd parameter: where the generic resource dictionary is located
|
||||
'(used if a resource is not found in the page,
|
||||
'app, and any theme specific resource dictionaries)
|
||||
<Assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)>
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
<Window x:Class="MainWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:local="clr-namespace:SampleApplication"
|
||||
mc:Ignorable="d"
|
||||
Title="MainWindow" Height="200" Width="200">
|
||||
<!--<MainXaml>-->
|
||||
<StackPanel Margin="5">
|
||||
<Button Click="Button_Click">Explicitly Styled</Button>
|
||||
<Button Click="ButtonFind_Click">Unstyled</Button>
|
||||
<Button>Unstyled</Button>
|
||||
<Button Style="{DynamicResource ResourceKey=buttonStyle1}">Dynamically Styled</Button>
|
||||
</StackPanel>
|
||||
<!--</MainXaml>-->
|
||||
</Window>
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
Class MainWindow
|
||||
'<CreateStyleCode>
|
||||
Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
|
||||
|
||||
'Create colors
|
||||
Dim purple = DirectCast(ColorConverter.ConvertFromString("#4E1A3D"), Color)
|
||||
Dim white = Colors.White
|
||||
Dim salmon = Colors.Salmon
|
||||
|
||||
'Create a new style for a button
|
||||
Dim buttonStyle As New Style()
|
||||
|
||||
'Set the properties of the style
|
||||
buttonStyle.Setters.Add(New Setter(Control.BackgroundProperty, New SolidColorBrush(purple)))
|
||||
buttonStyle.Setters.Add(New Setter(Control.ForegroundProperty, New SolidColorBrush(white)))
|
||||
buttonStyle.Setters.Add(New Setter(Control.BorderBrushProperty, New LinearGradientBrush(purple, salmon, 45D)))
|
||||
buttonStyle.Setters.Add(New Setter(Control.BorderThicknessProperty, New Thickness(5)))
|
||||
|
||||
'<SetResource>
|
||||
'Set this style as a resource. Any DynamicResource looking for this key will be updated.
|
||||
Me.Resources("buttonStyle1") = buttonStyle
|
||||
'</SetResource>
|
||||
|
||||
'<SetButtonStyle>
|
||||
'Set this style directly to a button
|
||||
DirectCast(sender, Button).Style = buttonStyle
|
||||
'</SetButtonStyle>
|
||||
|
||||
End Sub
|
||||
'</CreateStyleCode>
|
||||
|
||||
Private Sub ButtonFind_Click(sender As Object, e As RoutedEventArgs)
|
||||
Dim myButton As Button = DirectCast(sender, Button)
|
||||
|
||||
'<FindResource>
|
||||
myButton.Style = myButton.TryFindResource("buttonStyle1")
|
||||
'</FindResource>
|
||||
End Sub
|
||||
|
||||
End Class
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net5.0-windows</TargetFramework>
|
||||
<RootNamespace>SampleApplication</RootNamespace>
|
||||
<UseWPF>true</UseWPF>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Import Include="System.Windows" />
|
||||
<Import Include="System.Windows.Controls" />
|
||||
<Import Include="System.Windows.Data" />
|
||||
<Import Include="System.Windows.Documents" />
|
||||
<Import Include="System.Windows.Input" />
|
||||
<Import Include="System.Windows.Media" />
|
||||
<Import Include="System.Windows.Media.Imaging" />
|
||||
<Import Include="System.Windows.Navigation" />
|
||||
<Import Include="System.Windows.Shapes" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
<Application x:Class="SampleApplication.App"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
StartupUri="MainWindow.xaml">
|
||||
|
||||
</Application>
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Configuration;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
|
||||
namespace SampleApplication
|
||||
{
|
||||
/// <summary>
|
||||
/// Interaction logic for App.xaml
|
||||
/// </summary>
|
||||
public partial class App : Application
|
||||
{
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
using System.Windows;
|
||||
|
||||
[assembly:ThemeInfo(
|
||||
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
|
||||
//(used if a resource is not found in the page,
|
||||
// or application resource dictionaries)
|
||||
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
|
||||
//(used if a resource is not found in the page,
|
||||
// app, or any theme specific resource dictionaries)
|
||||
)]
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
<Window x:Class="SampleApplication.MainWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
Title="MainWindow" Height="200" Width="200">
|
||||
<!--<AppResourcesExample>-->
|
||||
<Border>
|
||||
<StackPanel Margin="5" x:Name="mainStackPanel">
|
||||
<!--<SystemFont>-->
|
||||
<TextBlock FontSize="{x:Static SystemFonts.SmallCaptionFontSize}"
|
||||
FontWeight="{x:Static SystemFonts.SmallCaptionFontWeight}"
|
||||
FontFamily="{x:Static SystemFonts.SmallCaptionFontFamily}"
|
||||
Text="Small Caption Font">
|
||||
</TextBlock>
|
||||
<!--</SystemFont>-->
|
||||
<!--<SystemFontDynamic>-->
|
||||
<TextBlock FontSize="{DynamicResource {x:Static SystemFonts.SmallCaptionFontSize}}"
|
||||
FontWeight="{DynamicResource {x:Static SystemFonts.SmallCaptionFontWeight}}"
|
||||
FontFamily="{DynamicResource {x:Static SystemFonts.SmallCaptionFontFamily}}"
|
||||
Text="Small Caption Font">
|
||||
</TextBlock>
|
||||
<!--</SystemFontDynamic>-->
|
||||
<Button Click="Button_Click_1">Test</Button>
|
||||
<!--<SystemParams>-->
|
||||
<Button FontSize="8"
|
||||
Height="{x:Static SystemParameters.CaptionHeight}"
|
||||
Width="{x:Static SystemParameters.IconGridWidth}"
|
||||
Content="System Parameters">
|
||||
</Button>
|
||||
<!--</SystemParams>-->
|
||||
<!--<SystemParamsDynamic>-->
|
||||
<Button FontSize="8"
|
||||
Height="{DynamicResource {x:Static SystemParameters.CaptionHeightKey}}"
|
||||
Width="{DynamicResource {x:Static SystemParameters.IconGridWidthKey}}"
|
||||
Content="System Parameters">
|
||||
</Button>
|
||||
<!--</SystemParamsDynamic>-->
|
||||
</StackPanel>
|
||||
</Border>
|
||||
<!--</AppResourcesExample>-->
|
||||
</Window>
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Data;
|
||||
using System.Windows.Documents;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using System.Windows.Navigation;
|
||||
using System.Windows.Shapes;
|
||||
|
||||
namespace SampleApplication
|
||||
{
|
||||
/// <summary>
|
||||
/// Interaction logic for MainWindow.xaml
|
||||
/// </summary>
|
||||
public partial class MainWindow : Window
|
||||
{
|
||||
public MainWindow()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
private void Button_Click_1(object sender, RoutedEventArgs e)
|
||||
{
|
||||
// <SystemFont>
|
||||
var myButton = new Button()
|
||||
{
|
||||
Content = "SystemFonts",
|
||||
Background = SystemColors.ControlDarkDarkBrush,
|
||||
FontSize = SystemFonts.IconFontSize,
|
||||
FontWeight = SystemFonts.MessageFontWeight,
|
||||
FontFamily = SystemFonts.CaptionFontFamily
|
||||
};
|
||||
|
||||
mainStackPanel.Children.Add(myButton);
|
||||
// </SystemFont>
|
||||
}
|
||||
|
||||
private void Button_Click_2(object sender, RoutedEventArgs e)
|
||||
{
|
||||
// <SystemParams>
|
||||
var myButton = new Button()
|
||||
{
|
||||
Content = "SystemParameters",
|
||||
FontSize = 8,
|
||||
Background = SystemColors.ControlDarkDarkBrush,
|
||||
Height = SystemParameters.CaptionHeight,
|
||||
Width = SystemParameters.CaptionWidth,
|
||||
};
|
||||
|
||||
mainStackPanel.Children.Add(myButton);
|
||||
// </SystemParams>
|
||||
}
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net5.0-windows</TargetFramework>
|
||||
<UseWPF>true</UseWPF>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="ResExample - Copy - Copy.xaml.cs">
|
||||
<SubType>Code</SubType>
|
||||
<DependentUpon>ResExample - Copy.xaml.cs</DependentUpon>
|
||||
</Compile>
|
||||
<Compile Update="ResExample - Copy.xaml.cs">
|
||||
<SubType>Code</SubType>
|
||||
<DependentUpon>ResExample.xaml.cs</DependentUpon>
|
||||
</Compile>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
<Application x:Class="Application"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:local="clr-namespace:SampleApplication"
|
||||
StartupUri="MainWindow.xaml">
|
||||
<Application.Resources>
|
||||
|
||||
</Application.Resources>
|
||||
</Application>
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
Class Application
|
||||
|
||||
' Application-level events, such as Startup, Exit, and DispatcherUnhandledException
|
||||
' can be handled in this file.
|
||||
|
||||
End Class
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
Imports System.Windows
|
||||
|
||||
'The ThemeInfo attribute describes where any theme specific and generic resource dictionaries can be found.
|
||||
'1st parameter: where theme specific resource dictionaries are located
|
||||
'(used if a resource is not found in the page,
|
||||
' or application resource dictionaries)
|
||||
|
||||
'2nd parameter: where the generic resource dictionary is located
|
||||
'(used if a resource is not found in the page,
|
||||
'app, and any theme specific resource dictionaries)
|
||||
<Assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)>
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
<Window x:Class="MainWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:local="clr-namespace:SampleApplication"
|
||||
mc:Ignorable="d"
|
||||
Title="MainWindow" Height="200" Width="200">
|
||||
<Border>
|
||||
<StackPanel Margin="5" x:Name="mainStackPanel">
|
||||
<!--<SystemFont>-->
|
||||
<TextBlock FontSize="{x:Static SystemFonts.SmallCaptionFontSize}"
|
||||
FontWeight="{x:Static SystemFonts.SmallCaptionFontWeight}"
|
||||
FontFamily="{x:Static SystemFonts.SmallCaptionFontFamily}"
|
||||
Text="Small Caption Font">
|
||||
</TextBlock>
|
||||
<!--</SystemFont>-->
|
||||
<!--<SystemFontDynamic>-->
|
||||
<TextBlock FontSize="{DynamicResource {x:Static SystemFonts.SmallCaptionFontSize}}"
|
||||
FontWeight="{DynamicResource {x:Static SystemFonts.SmallCaptionFontWeight}}"
|
||||
FontFamily="{DynamicResource {x:Static SystemFonts.SmallCaptionFontFamily}}"
|
||||
Text="Small Caption Font">
|
||||
</TextBlock>
|
||||
<!--</SystemFontDynamic>-->
|
||||
<Button Click="Button_Click_1">Test</Button>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</Window>
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
Class MainWindow
|
||||
Private Sub Button_Click_1(sender As Object, e As RoutedEventArgs)
|
||||
' <SystemFont>
|
||||
Dim myButton = New Button() With
|
||||
{
|
||||
.Content = "SystemFonts",
|
||||
.Background = SystemColors.ControlDarkDarkBrush,
|
||||
.FontSize = SystemFonts.IconFontSize,
|
||||
.FontWeight = SystemFonts.MessageFontWeight,
|
||||
.FontFamily = SystemFonts.CaptionFontFamily
|
||||
}
|
||||
|
||||
mainStackPanel.Children.Add(myButton)
|
||||
' </SystemFont>
|
||||
End Sub
|
||||
|
||||
Private Sub Button_Click_2(sender As Object, e As RoutedEventArgs)
|
||||
' <SystemParams>
|
||||
Dim myButton = New Button() With
|
||||
{
|
||||
.Content = "SystemParameters",
|
||||
.FontSize = 8,
|
||||
.Background = SystemColors.ControlDarkDarkBrush,
|
||||
.Height = SystemParameters.CaptionHeight,
|
||||
.Width = SystemParameters.CaptionWidth
|
||||
}
|
||||
|
||||
mainStackPanel.Children.Add(myButton)
|
||||
' </SystemParams>
|
||||
End Sub
|
||||
End Class
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net5.0-windows</TargetFramework>
|
||||
<RootNamespace>SampleApplication</RootNamespace>
|
||||
<UseWPF>true</UseWPF>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Import Include="System.Windows" />
|
||||
<Import Include="System.Windows.Controls" />
|
||||
<Import Include="System.Windows.Data" />
|
||||
<Import Include="System.Windows.Documents" />
|
||||
<Import Include="System.Windows.Input" />
|
||||
<Import Include="System.Windows.Media" />
|
||||
<Import Include="System.Windows.Media.Imaging" />
|
||||
<Import Include="System.Windows.Navigation" />
|
||||
<Import Include="System.Windows.Shapes" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,9 @@
|
||||
<Application x:Class="csharp.App"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:local="clr-namespace:csharp"
|
||||
StartupUri="MainWindow.xaml">
|
||||
<Application.Resources>
|
||||
|
||||
</Application.Resources>
|
||||
</Application>
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Configuration;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
|
||||
namespace csharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Interaction logic for App.xaml
|
||||
/// </summary>
|
||||
public partial class App : Application
|
||||
{
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
using System.Windows;
|
||||
|
||||
[assembly:ThemeInfo(
|
||||
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
|
||||
//(used if a resource is not found in the page,
|
||||
// or application resource dictionaries)
|
||||
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
|
||||
//(used if a resource is not found in the page,
|
||||
// app, or any theme specific resource dictionaries)
|
||||
)]
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
<Page x:Class="resources.ImplicitStyle"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:local="clr-namespace:resources"
|
||||
mc:Ignorable="d"
|
||||
d:DesignHeight="450" d:DesignWidth="800"
|
||||
Title="ImplicitStyle">
|
||||
<Page.Resources>
|
||||
<!--<ImplicitStyle>-->
|
||||
<Style TargetType="Button">
|
||||
<Setter Property="Background" Value="#4E1A3D" />
|
||||
<Setter Property="Foreground" Value="White" />
|
||||
<Setter Property="BorderThickness" Value="5" />
|
||||
<Setter Property="BorderBrush">
|
||||
<Setter.Value>
|
||||
<LinearGradientBrush>
|
||||
<GradientStop Offset="0.0" Color="#4E1A3D"/>
|
||||
<GradientStop Offset="1.0" Color="Salmon"/>
|
||||
</LinearGradientBrush>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
<!--</ImplicitStyle>-->
|
||||
</Page.Resources>
|
||||
<Grid>
|
||||
<Button>Hello</Button>
|
||||
</Grid>
|
||||
</Page>
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Data;
|
||||
using System.Windows.Documents;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using System.Windows.Navigation;
|
||||
using System.Windows.Shapes;
|
||||
|
||||
namespace resources
|
||||
{
|
||||
/// <summary>
|
||||
/// Interaction logic for ImplicitStyle.xaml
|
||||
/// </summary>
|
||||
public partial class ImplicitStyle : Page
|
||||
{
|
||||
public ImplicitStyle()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
<Window x:Class="csharp.MainWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:local="clr-namespace:csharp"
|
||||
mc:Ignorable="d"
|
||||
Title="MainWindow" Height="450" Width="800">
|
||||
<Grid>
|
||||
|
||||
</Grid>
|
||||
</Window>
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Data;
|
||||
using System.Windows.Documents;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using System.Windows.Navigation;
|
||||
using System.Windows.Shapes;
|
||||
|
||||
namespace csharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Interaction logic for MainWindow.xaml
|
||||
/// </summary>
|
||||
public partial class MainWindow : Window
|
||||
{
|
||||
public MainWindow()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
<Window x:Class="resources.ResExample"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
Title="ResExample" Height="400" Width="300">
|
||||
<Window.Resources>
|
||||
<SolidColorBrush x:Key="MyBrush" Color="#05E0E9"/>
|
||||
<Style TargetType="Border">
|
||||
<Setter Property="Background" Value="#4E1A3D" />
|
||||
<Setter Property="BorderThickness" Value="5" />
|
||||
<Setter Property="BorderBrush">
|
||||
<Setter.Value>
|
||||
<LinearGradientBrush>
|
||||
<GradientStop Offset="0.0" Color="#4E1A3D"/>
|
||||
<GradientStop Offset="1.0" Color="Salmon"/>
|
||||
</LinearGradientBrush>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
<Style TargetType="TextBlock" x:Key="TitleText">
|
||||
<Setter Property="FontSize" Value="18"/>
|
||||
<Setter Property="Foreground" Value="#4E87D4"/>
|
||||
<Setter Property="FontFamily" Value="Trebuchet MS"/>
|
||||
<Setter Property="Margin" Value="0,10,10,10"/>
|
||||
</Style>
|
||||
<Style TargetType="TextBlock" x:Key="Label">
|
||||
<Setter Property="HorizontalAlignment" Value="Right"/>
|
||||
<Setter Property="FontSize" Value="13"/>
|
||||
<Setter Property="Foreground" Value="{StaticResource MyBrush}"/>
|
||||
<Setter Property="FontFamily" Value="Arial"/>
|
||||
<Setter Property="FontWeight" Value="Bold"/>
|
||||
<Setter Property="Margin" Value="0,3,10,0"/>
|
||||
</Style>
|
||||
</Window.Resources>
|
||||
|
||||
<Border>
|
||||
<StackPanel>
|
||||
<TextBlock Style="{StaticResource TitleText}">Title</TextBlock>
|
||||
<TextBlock Style="{StaticResource Label}">Label</TextBlock>
|
||||
<TextBlock HorizontalAlignment="Right" FontSize="36" Foreground="{StaticResource MyBrush}" Text="Text" Margin="20" />
|
||||
<Button HorizontalAlignment="Left" Height="30" Background="{StaticResource MyBrush}" Margin="40">Button</Button>
|
||||
<Ellipse HorizontalAlignment="Center" Width="100" Height="100" Fill="{StaticResource MyBrush}" Margin="10" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
</Window>
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Data;
|
||||
using System.Windows.Documents;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using System.Windows.Shapes;
|
||||
|
||||
namespace resources
|
||||
{
|
||||
/// <summary>
|
||||
/// Interaction logic for ResExample.xaml
|
||||
/// </summary>
|
||||
public partial class ResExample : Window
|
||||
{
|
||||
public ResExample()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net5.0-windows</TargetFramework>
|
||||
<UseWPF>true</UseWPF>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="ResExample - Copy - Copy.xaml.cs">
|
||||
<SubType>Code</SubType>
|
||||
<DependentUpon>ResExample - Copy.xaml.cs</DependentUpon>
|
||||
</Compile>
|
||||
<Compile Update="ResExample - Copy.xaml.cs">
|
||||
<SubType>Code</SubType>
|
||||
<DependentUpon>ResExample.xaml.cs</DependentUpon>
|
||||
</Compile>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,57 @@
|
||||
---
|
||||
title: WPF resources in code
|
||||
description: Learn about how Windows Presentation Foundation (WPF) resources, typically defined and used in XAML, can be used in code. Resources can be accessed, created, and managed in code.
|
||||
author: adegeo
|
||||
ms.author: adegeo
|
||||
ms.date: 04/01/2021
|
||||
ms.topic: overview
|
||||
dev_langs:
|
||||
- "csharp"
|
||||
- "vb"
|
||||
helpviewer_keywords:
|
||||
- "keys [WPF], using objects as"
|
||||
- "resources [WPF], accessing from procedural code"
|
||||
- "procedural code [WPF], creating resources with"
|
||||
- "procedural code [WPF], accessing resources from"
|
||||
- "resources [WPF], creating with procedural code"
|
||||
---
|
||||
|
||||
# Resources in code (WPF .NET)
|
||||
|
||||
This overview concentrates on how Windows Presentation Foundation (WPF) resources can be accessed or created using code rather than XAML syntax. For more information on general resource usage and resources from a XAML syntax perspective, see [Overview of XAML resources](xaml-resources-overview.md).
|
||||
|
||||
## Accessing resources from code
|
||||
|
||||
The keys that identify XAML defined resources are also used to retrieve specific resources if you request the resource in code. The simplest way to retrieve a resource from code is to call either the <xref:System.Windows.FrameworkElement.FindResource%2A> or the <xref:System.Windows.FrameworkElement.TryFindResource%2A> method from framework-level objects in your application. The behavioral difference between these methods is what happens if the requested key isn't found. <xref:System.Windows.FrameworkElement.FindResource%2A> raises an exception. <xref:System.Windows.FrameworkElement.TryFindResource%2A> won't raise an exception but returns `null`. Each method takes the resource key as an input parameter, and returns a loosely typed object.
|
||||
|
||||
Typically, a resource key is a string, but there are [occasional nonstring usages](#using-objects-as-keys). The lookup logic for code resource resolution is the same as the dynamic resource reference XAML case. The search for resources starts from the calling element, then continues through parent elements in the logical tree. The lookup continues onwards into application resources, themes, and system resources if necessary. A code request for a resource will properly account for changes to those resources that happened during runtime.
|
||||
|
||||
The following code example demonstrates a <xref:System.Windows.Controls.Primitives.ButtonBase.Click> event handler that finds a resource by key, and uses the returned value to set a property.
|
||||
|
||||
:::code language="csharp" source="./snippets/xaml-resources-and-code/csharp/MainWindow.xaml.cs" id="ButtonBrush":::
|
||||
:::code language="vb" source="./snippets/xaml-resources-and-code/vb/MainWindow.xaml.vb" id="ButtonBrush":::
|
||||
|
||||
An alternative method for assigning a resource reference is <xref:System.Windows.FrameworkElement.SetResourceReference%2A>. This method takes two parameters: the key of the resource, and the identifier for a particular dependency property that's present on the element instance to which the resource value should be assigned. Functionally, this method is the same and has the advantage of not requiring any casting of return values.
|
||||
|
||||
Still another way to access resources programmatically is to access the contents of the <xref:System.Windows.FrameworkElement.Resources%2A> property as a dictionary. Resource dictionaries are used to add new resources to existing collections, check to see if a given key name is already used by the collection, and other operations. If you're writing a WPF application entirely in code, you can also create the entire collection in code, assign resources to it. The collection can then be assigned to the <xref:System.Windows.FrameworkElement.Resources%2A> property of an element. This is described in the next section.
|
||||
|
||||
You can index within any given <xref:System.Windows.FrameworkElement.Resources%2A> collection, using a specific key as the index. Resources accessed in this way don't follow the normal runtime rules of resource resolution. You're only accessing that particular collection. Resource lookup doesn't traverse the resource scope to the root or the application if no valid object was found at the requested key. However, this approach may have performance advantages in some cases precisely because the scope of the search for the key is more constrained. For more information about how to work with a resource dictionary directly, see the <xref:System.Windows.ResourceDictionary> class.
|
||||
|
||||
## Creating resources with code
|
||||
|
||||
If you want to create an entire WPF application in code, you might also want to create any resources in that application in code. To achieve this, create a new <xref:System.Windows.ResourceDictionary> instance, and then add all the resources to the dictionary using successive calls to <xref:System.Windows.ResourceDictionary.Add%2A?displayProperty=nameWithType>. Then, assign the created <xref:System.Windows.ResourceDictionary> to set the <xref:System.Windows.FrameworkElement.Resources%2A> property on an element that's present in a page scope, or the <xref:System.Windows.Application.Resources%2A?displayProperty=nameWithType>. You could also maintain the <xref:System.Windows.ResourceDictionary> as a standalone object without adding it to an element. However, if you do this, you must access the resources within it by item key, as if it were a generic dictionary. A <xref:System.Windows.ResourceDictionary> that's not attached to an element `Resources` property wouldn't exist as part of the element tree and has no scope in a lookup sequence that can be used by <xref:System.Windows.FrameworkElement.FindResource%2A> and related methods.
|
||||
|
||||
## Using objects as keys
|
||||
|
||||
Most resource usages will set the key of the resource to be a string. However, various WPF features deliberately use the object type as a key instead of a string. The capability of having the resource be keyed by an object type is used by the WPF style and theming support. The styles and themes that become the default for an otherwise non-styled control are each keyed by the <xref:System.Type> of the control that they should apply to.
|
||||
|
||||
Being keyed by type provides a reliable lookup mechanism that works on default instances of each control type. The type can be detected by reflection and used for styling derived classes even though the derived type otherwise has no default style. You can specify a <xref:System.Type> key for a resource defined in XAML by using the [x:Type Markup Extension](/dotnet/desktop-wpf/xaml-services/xtype-markup-extension). Similar extensions exist for other nonstring key usages that support WPF features, such as [ComponentResourceKey Markup Extension](../../../framework/wpf/advanced/componentresourcekey-markup-extension.md).
|
||||
|
||||
For more information, see [Styles, DataTemplates, and implicit keys](xaml-resources-overview.md#styles-datatemplates-and-implicit-keys).
|
||||
|
||||
## See also
|
||||
|
||||
- [Overview of XAML resources](xaml-resources-overview.md)
|
||||
- [How to define and reference a WPF resource](xaml-resources-how-to-define-and-reference.md)
|
||||
- [How to use system resources](xaml-resources-how-to-use-system.md)
|
||||
- [How to use application resources](xaml-resources-how-to-use-application.md)
|
||||
@@ -0,0 +1,104 @@
|
||||
---
|
||||
title: "How to define and reference a resource"
|
||||
description: Learn how to define and reference Windows Presentation Foundation (WPF) resources through XAML and code.
|
||||
author: adegeo
|
||||
ms.author: adegeo
|
||||
ms.date: 04/02/2021
|
||||
dev_langs:
|
||||
- "csharp"
|
||||
- "vb"
|
||||
helpviewer_keywords:
|
||||
- "resources [WPF], defining"
|
||||
- "defining resources [WPF]"
|
||||
- "resources [WPF], referencing"
|
||||
- "referencing resources [WPF]"
|
||||
#no-loc: [TextBlock, Setter]
|
||||
---
|
||||
|
||||
# How to define and reference a WPF resource (WPF .NET)
|
||||
|
||||
This example shows how to define a resource and reference it. A resource can be referenced through XAML or through code.
|
||||
|
||||
[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)]
|
||||
|
||||
## XAML example
|
||||
|
||||
The following example defines two types of resources: a <xref:System.Windows.Media.SolidColorBrush> resource, and several <xref:System.Windows.Style> resources.
|
||||
|
||||
:::code language="xaml" source="./snippets/xaml-resources-how-to-define-and-reference/csharp/ResExample.xaml" id="ResDefine":::
|
||||
|
||||
### Resources
|
||||
|
||||
The <xref:System.Windows.Media.SolidColorBrush> resource `MyBrush` is used to provide the value of several properties that each take a <xref:System.Windows.Media.Brush> type value. This resource is referenced through the `x:Key` value.
|
||||
|
||||
:::code language="xaml" source="./snippets/xaml-resources-how-to-define-and-reference/csharp/ResExample.xaml" id="ResUsed":::
|
||||
|
||||
In the previous example, the `MyBrush` resource is accessed with the [StaticResource Markup Extension](../../../framework/wpf/advanced/staticresource-markup-extension.md). The resource is assigned to a property that can accept the type of resource being defined. In this case the <xref:System.Windows.Controls.Control.Background%2A>, <xref:System.Windows.Controls.Control.Foreground%2A>, and <xref:System.Windows.Shapes.Shape.Fill> properties.
|
||||
|
||||
All resources in a resource diction must provide a key. When styles are defined though, they can omit the key, as explained in the [next section](#style-resources).
|
||||
|
||||
Resources are also requested by the order found within the dictionary if you use the [StaticResource Markup Extension](../../../framework/wpf/advanced/staticresource-markup-extension.md) to reference them from within another resource. Make sure that any resource that you reference is defined in the collection earlier than where that resource is requested. For more information, see [Static resources](xaml-resources-overview.md#static-resources).
|
||||
|
||||
If necessary, you can work around the strict creation order of resource references by using a [DynamicResource Markup Extension](../../../framework/wpf/advanced/dynamicresource-markup-extension.md) to reference the resource at runtime instead, but you should be aware that this `DynamicResource` technique has performance consequences. For more information, see [Dynamic resources](xaml-resources-overview.md#dynamic-resources).
|
||||
|
||||
### Style resources
|
||||
|
||||
The following example references styles implicitly and explicitly:
|
||||
|
||||
:::code language="xaml" source="./snippets/xaml-resources-how-to-define-and-reference/csharp/ResExample.xaml" id="ResUsed":::
|
||||
|
||||
In the previous code example, the <xref:System.Windows.Style> resources `TitleText` and `Label`, each target a particular control type. In this case, they both target a <xref:System.Windows.Controls.TextBlock>. The styles set a variety of different properties on the targeted controls when that style resource is referenced by its resource key for the <xref:System.Windows.FrameworkElement.Style%2A> property.
|
||||
|
||||
The style though that targets a <xref:System.Windows.Controls.Border> control doesn't define a key. When a key is omitted, the type of object being targeted by the <xref:System.Windows.Style.TargetType> property is implicitly used as the key for the style. When a style is keyed to a type, it becomes the default style for all controls of that type, as long as these controls are within scope of the style. For more information, see [Styles, DataTemplates, and implicit keys](xaml-resources-overview.md#styles-datatemplates-and-implicit-keys).
|
||||
|
||||
## Code examples
|
||||
|
||||
The following code snippets demonstrate creating and setting resources through code
|
||||
|
||||
### Create a style resource
|
||||
|
||||
Creating a resource and assigning it to a resource dictionary can happen at any time. However, only XAML elements that use the DynamicResource syntax will be automatically updated with the resource after it's created.
|
||||
|
||||
Take for example the following Window. It has four buttons. The forth button is using a [DynamicResource](xaml-resources-overview.md#dynamic-resources) to style itself. However, this resource doesn't yet exist, so it just looks like a normal button:
|
||||
|
||||
:::code language="xaml" source="./snippets/xaml-resources-how-to-define-and-reference/csharp/MainWindow.xaml" id="MainXaml":::
|
||||
|
||||
:::image type="content" source="media/xaml-resources-how-to-define-and-reference/before.png" alt-text="A window before a style is applied to a button":::
|
||||
|
||||
The following code is invoked when the first button is clicked and performs the following tasks:
|
||||
|
||||
- Creates some colors for easy reference.
|
||||
- Creates a new style.
|
||||
- Assigns setters to the style.
|
||||
- Adds the style as a resource named `buttonStyle1` to the window's resource dictionary.
|
||||
- Assigns the style directly to the button raising the `Click` event.
|
||||
|
||||
:::code language="csharp" source="./snippets/xaml-resources-how-to-define-and-reference/csharp/MainWindow.xaml.cs" id="CreateStyleCode":::
|
||||
:::code language="vb" source="./snippets/xaml-resources-how-to-define-and-reference/vb/MainWindow.xaml.vb" id="CreateStyleCode":::
|
||||
|
||||
After the code runs, the window is updated:
|
||||
|
||||
:::image type="content" source="media/xaml-resources-how-to-define-and-reference/after.png" alt-text="A window after a style is applied to a button":::
|
||||
|
||||
Notice that the forth button's style was updated. The style was automatically applied because the button used the [DynamicResource Markup Extension](../../../framework/wpf/advanced/dynamicresource-markup-extension.md) to reference a style that didn't yet exist. Once the style was created and added to the resources of the window, it was applied to the button. For more information, see [Dynamic resources](xaml-resources-overview.md#dynamic-resources).
|
||||
|
||||
### Find a resource
|
||||
|
||||
The following code traverses the logical tree of the XAML object in which is run, to find the specified resource. The resource might be defined on the object itself, it's parent, all the way to the root, the application itself. The following code searches for a resource, starting with the button itself:
|
||||
|
||||
:::code language="csharp" source="./snippets/xaml-resources-how-to-define-and-reference/csharp/MainWindow.xaml.cs" id="FindResource":::
|
||||
:::code language="vb" source="./snippets/xaml-resources-how-to-define-and-reference/vb/MainWindow.xaml.vb" id="FindResource":::
|
||||
|
||||
### Explicitly reference a resource
|
||||
|
||||
When you have reference to a resource, either by searching for it or by creating it, it can be assigned to a property directly:
|
||||
|
||||
:::code language="csharp" source="./snippets/xaml-resources-how-to-define-and-reference/csharp/MainWindow.xaml.cs" id="SetResource":::
|
||||
:::code language="vb" source="./snippets/xaml-resources-how-to-define-and-reference/vb/MainWindow.xaml.vb" id="SetResource":::
|
||||
|
||||
## See also
|
||||
|
||||
- [Overview of XAML resources](xaml-resources-overview.md)
|
||||
- [Styles and templates](../controls/styles-templates-overview.md)
|
||||
- [How to use system resources](xaml-resources-how-to-use-system.md)
|
||||
- [How to use application resources](xaml-resources-how-to-use-application.md)
|
||||
@@ -0,0 +1,34 @@
|
||||
---
|
||||
title: "How to use application resources"
|
||||
description: Learn how to define and reference Windows Presentation Foundation (WPF) application-scoped resources in XAML.
|
||||
author: adegeo
|
||||
ms.author: adegeo
|
||||
ms.date: 04/08/2021
|
||||
helpviewer_keywords:
|
||||
- "application resources [WPF]"
|
||||
- "resources [WPF], application resources"
|
||||
#no-loc: [App.xaml, Application.xaml]
|
||||
---
|
||||
|
||||
# How to use application resources (WPF .NET)
|
||||
|
||||
This example demonstrates how to use application-defined resources. Resources can be defined at the application level, generally through the _App.xaml_ or _Application.xaml_ file, whichever one your project uses. Resources that are defined by the application are globally scoped and accessible by all parts of the application.
|
||||
|
||||
[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)]
|
||||
|
||||
## Example
|
||||
|
||||
The following example shows an application definition file. The application definition file defines a resource section (a value for the <xref:System.Windows.Application.Resources%2A> property). Resources defined at the application level can be accessed by all other pages that are part of the application. In this case, the resource is a declared style. Because a complete style that includes a control template can be lengthy, this example omits the control template that is defined within the <xref:System.Windows.Controls.ContentControl.ContentTemplate%2A> property setter of the style.
|
||||
|
||||
:::code language="xaml" source="./snippets/xaml-resources-how-to-use-application/csharp/App.xaml" id="AppResources":::
|
||||
|
||||
The following example shows a XAML page that references an application-level resource from the previous example. The resource is referenced with a [StaticResource Markup Extension](../../../framework/wpf/advanced/staticresource-markup-extension.md) that specifies the unique resource key for the resource. The resource "FancyBorder" isn't found in the scope of the current object and window, so the resource lookup continues beyond the current page and into application-level resources.
|
||||
|
||||
:::code language="xaml" source="./snippets/xaml-resources-how-to-use-application/csharp/MainWindow.xaml" id="AppResourcesExample":::
|
||||
|
||||
## See also
|
||||
|
||||
- [Overview of XAML resources](xaml-resources-overview.md)
|
||||
- [Resources in code](xaml-resources-and-code.md)
|
||||
- [How to define and reference a WPF resource](xaml-resources-how-to-define-and-reference.md)
|
||||
- [How to use system resources](xaml-resources-how-to-use-system.md)
|
||||
@@ -0,0 +1,78 @@
|
||||
---
|
||||
title: "How to use system resources"
|
||||
description: Learn how to define and reference Windows Presentation Foundation (WPF) Windows Operating System resources in XAML.
|
||||
author: adegeo
|
||||
ms.author: adegeo
|
||||
ms.date: 04/09/2021
|
||||
dev_langs:
|
||||
- "csharp"
|
||||
- "vb"
|
||||
helpviewer_keywords:
|
||||
- "resource keys [WPF], SystemFonts class"
|
||||
- "resource keys [WPF], SystemParameters class"
|
||||
- "system fonts [WPF]"
|
||||
- "classes [WPF], SystemParameters"
|
||||
- "classes [WPF], SystemFonts"
|
||||
#no-loc: [App.xaml, Application.xaml]
|
||||
---
|
||||
|
||||
# How to use system resources (WPF .NET)
|
||||
|
||||
This example demonstrates how to use system-defined resources. System resources are provided by WPF and allow access to operating system resources, such as fonts, colors, and icons. System resources expose several system-defined values as both resources and properties to help you create visuals that are consistent with Windows.
|
||||
|
||||
[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)]
|
||||
|
||||
## Fonts
|
||||
|
||||
Use the <xref:System.Windows.SystemFonts> class to reference the fonts used by the operating system. This class contains system font values as static properties, and properties that reference resource keys that can be used to access those values dynamically at run time. For example, <xref:System.Windows.SystemFonts.CaptionFontFamily%2A> is a <xref:System.Windows.SystemFonts> value, and <xref:System.Windows.SystemFonts.CaptionFontFamilyKey%2A> is a corresponding resource key.
|
||||
|
||||
The following example shows how to access and use the properties of <xref:System.Windows.SystemFonts> as static values to style or customize a text block:
|
||||
|
||||
:::code language="xaml" source="./snippets/xaml-resources-how-to-use-system/csharp/MainWindow.xaml" id="SystemFont":::
|
||||
|
||||
To use the values of <xref:System.Windows.SystemFonts> in code, you don't have to use either a static value or a dynamic resource reference. Instead, use the non-key properties of the <xref:System.Windows.SystemFonts> class. Although the non-key properties are apparently defined as static properties, the run-time behavior of WPF as hosted by the system will reevaluate the properties in real time and will properly account for user-driven changes to system values. The following example shows how to specify the font settings of a button:
|
||||
|
||||
:::code language="csharp" source="./snippets/xaml-resources-how-to-use-system/csharp/MainWindow.xaml.cs" id="SystemFont":::
|
||||
:::code language="vb" source="./snippets/xaml-resources-how-to-use-system/vb/MainWindow.xaml.vb" id="SystemFont":::
|
||||
|
||||
### Dynamic fonts in XAML
|
||||
|
||||
System font metrics can be used as either static or dynamic resources. Use a dynamic resource if you want the font metric to update automatically while the application runs; otherwise, use a static resource.
|
||||
|
||||
> [!NOTE]
|
||||
> Dynamic resources have the keyword `Key` appended to the property name.
|
||||
|
||||
The following example shows how to access and use system font dynamic resources to style or customize a text block:
|
||||
|
||||
:::code language="xaml" source="./snippets/xaml-resources-how-to-use-system/csharp/MainWindow.xaml" id="SystemFontDynamic":::
|
||||
|
||||
## Parameters
|
||||
|
||||
Use the <xref:System.Windows.SystemParameters> class to reference system-level properties, such as the size of the primary display. This class contains both system parameter value properties, and resource keys that bind to the values. For example, <xref:System.Windows.SystemParameters.FullPrimaryScreenHeight%2A> is a <xref:System.Windows.SystemParameters> property value and <xref:System.Windows.SystemParameters.FullPrimaryScreenHeightKey%2A> is the corresponding resource key.
|
||||
|
||||
The following example shows how to access and use the static values of <xref:System.Windows.SystemParameters> to style or customize a button. This markup example sizes a button by applying <xref:System.Windows.SystemParameters> values to a button:
|
||||
|
||||
:::code language="xaml" source="./snippets/xaml-resources-how-to-use-system/csharp/MainWindow.xaml" id="SystemParams":::
|
||||
|
||||
To use the values of <xref:System.Windows.SystemParameters> in code, you don't have to use either static references or dynamic resource references. Instead, use the values of the <xref:System.Windows.SystemParameters> class. Although the non-key properties are apparently defined as static properties, the run-time behavior of WPF as hosted by the system will reevaluate the properties in real time, and will properly account for user-driven changes to system values. The following example shows how to set the width and height of a button by using <xref:System.Windows.SystemParameters> values:
|
||||
|
||||
:::code language="csharp" source="./snippets/xaml-resources-how-to-use-system/csharp/MainWindow.xaml.cs" id="SystemParams":::
|
||||
:::code language="vb" source="./snippets/xaml-resources-how-to-use-system/vb/MainWindow.xaml.vb" id="SystemParams":::
|
||||
|
||||
### Dynamic parameters in XAML
|
||||
|
||||
System parameter metrics can be used as either static or dynamic resources. Use a dynamic resource if you want the parameter metric to update automatically while the application runs; otherwise, use a static resource.
|
||||
|
||||
> [!NOTE]
|
||||
> Dynamic resources have the keyword `Key` appended to the property name.
|
||||
|
||||
The following example shows how to access and use system parameter dynamic resources to style or customize a button. This XAML example sizes a button by assigning <xref:System.Windows.SystemParameters> values to the button's width and height.
|
||||
|
||||
:::code language="xaml" source="./snippets/xaml-resources-how-to-use-system/csharp/MainWindow.xaml" id="SystemParamsDynamic":::
|
||||
|
||||
## See also
|
||||
|
||||
- [Overview of XAML resources](xaml-resources-overview.md)
|
||||
- [Resources in code](xaml-resources-and-code.md)
|
||||
- [How to define and reference a WPF resource](xaml-resources-how-to-define-and-reference.md)
|
||||
- [How to use application resources](xaml-resources-how-to-use-application.md)
|
||||
@@ -0,0 +1,82 @@
|
||||
---
|
||||
title: Merged resource dictionaries
|
||||
description: Learn about Windows Presentation Foundation (WPF) for .NET merged resource dictionaries. Define and reference XAML resources outside of a compiled WPF application.
|
||||
author: adegeo
|
||||
ms.author: adegeo
|
||||
ms.date: 03/30/2021
|
||||
ms.topic: conceptual
|
||||
helpviewer_keywords:
|
||||
- "merged resource dictionaries [WPF]"
|
||||
- "dictionaries [WPF], merged resources"
|
||||
---
|
||||
|
||||
# Merged resource dictionaries (WPF .NET)
|
||||
|
||||
Windows Presentation Foundation (WPF) resources support a merged resource dictionary feature. This feature provides a way to define the resources portion of a WPF application outside of the compiled XAML application. Resources can then be shared across applications and are also more conveniently isolated for localization.
|
||||
|
||||
[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)]
|
||||
|
||||
## Create a merged dictionary
|
||||
|
||||
In markup, you use the following syntax to introduce a merged resource dictionary into a page:
|
||||
|
||||
```xaml
|
||||
<Page.Resources>
|
||||
<ResourceDictionary>
|
||||
<ResourceDictionary.MergedDictionaries>
|
||||
<ResourceDictionary Source="myresourcedictionary.xaml"/>
|
||||
<ResourceDictionary Source="myresourcedictionary2.xaml"/>
|
||||
</ResourceDictionary.MergedDictionaries>
|
||||
</ResourceDictionary>
|
||||
</Page.Resources>
|
||||
```
|
||||
|
||||
The <xref:System.Windows.ResourceDictionary> element doesn't have an [x:Key Directive](../../../xaml-services/xkey-directive.md), which is generally required for all items in a resource collection. But another `ResourceDictionary` reference within the <xref:System.Windows.ResourceDictionary.MergedDictionaries%2A> collection is a special case, reserved for this merged resource dictionary scenario. Further, the `ResourceDictionary` that introduces a merged resource dictionary can't have an [x:Key Directive](../../../xaml-services/xkey-directive.md).
|
||||
|
||||
Typically, each <xref:System.Windows.ResourceDictionary> within the <xref:System.Windows.ResourceDictionary.MergedDictionaries%2A> collection specifies a <xref:System.Windows.ResourceDictionary.Source%2A> attribute. The value of `Source` should be a uniform resource identifier (URI) that resolves to the location of the resources file to be merged. The destination of that URI must be another XAML file, with `ResourceDictionary` as its root element.
|
||||
|
||||
> [!NOTE]
|
||||
> It's legal to define resources within a <xref:System.Windows.ResourceDictionary> that's specified as a merged dictionary, either as an alternative to specifying <xref:System.Windows.ResourceDictionary.Source%2A>, or in addition to whatever resources are included from the specified source. However, this isn't a common scenario. The main scenario for merged dictionaries is to merge resources from external file locations. If you want to specify resources within the markup for a page, define these in the main `ResourceDictionary` and not in the merged dictionaries.
|
||||
|
||||
## Merged dictionary behavior
|
||||
|
||||
Resources in a merged dictionary occupy a location in the resource lookup scope that's just after the scope of the main resource dictionary they are merged into. Although a resource key must be unique within any individual dictionary, a key can exist multiple times in a set of merged dictionaries. In this case, the resource that's returned will come from the last dictionary found sequentially in the <xref:System.Windows.ResourceDictionary.MergedDictionaries%2A> collection. If the <xref:System.Windows.ResourceDictionary.MergedDictionaries%2A> collection was defined in XAML, then the order of the merged dictionaries in the collection is the order of the elements as provided in the markup. If a key is defined in the primary dictionary and also in a dictionary that was merged, then the resource that's returned will come from the primary dictionary. These scoping rules apply equally for both static resource references and dynamic resource references.
|
||||
|
||||
## Merged dictionaries and code
|
||||
|
||||
Merged dictionaries can be added to a `Resources` dictionary through code. The default, initially empty <xref:System.Windows.ResourceDictionary> that exists for any `Resources` property also has a default, initially empty <xref:System.Windows.ResourceDictionary.MergedDictionaries%2A> collection property. To add a merged dictionary through code, you obtain a reference to the desired primary `ResourceDictionary`, get its `MergedDictionaries` property value, and call `Add` on the generic `Collection` that's contained in `MergedDictionaries`. The object you add must be a new `ResourceDictionary`.
|
||||
|
||||
In code, you don't set the <xref:System.Windows.ResourceDictionary.Source%2A> property. Instead, you must obtain a `ResourceDictionary` object by either creating one or loading one. One way to load an existing `ResourceDictionary` to call <xref:System.Windows.Markup.XamlReader.Load%2A?displayProperty=nameWithType> on an existing XAML file stream that has a `ResourceDictionary` root, then casting the return value to `ResourceDictionary`.
|
||||
|
||||
## Merged dictionary URIs
|
||||
|
||||
There are several techniques for how to include a merged resource dictionary, which are indicated by the uniform resource identifier (URI) format that you use. Broadly speaking, these techniques can be divided into two categories: resources that are compiled as part of the project, and resources that aren't compiled as part of the project.
|
||||
|
||||
For resources that are compiled as part of the project, you can use a relative path that refers to the resource location. The relative path is evaluated during compilation. Your resource must be defined as part of the project as a **Resource** build action. If you include a resource _.xaml_ file in the project as **Resource**, you don't need to copy the resource file to the output directory, the resource is already included within the compiled application. You can also use **Content** build action, but you must then copy the files to the output directory and also deploy the resource files in the same path relationship to the executable.
|
||||
|
||||
> [!NOTE]
|
||||
> Don't use the **Embedded Resource** build action. The build action itself is supported for WPF applications, but the resolution of <xref:System.Windows.ResourceDictionary.Source%2A> doesn't incorporate <xref:System.Resources.ResourceManager>, and thus cannot separate the individual resource out of the stream. You could still use **Embedded Resource** for other purposes so long as you also used <xref:System.Resources.ResourceManager> to access the resources.
|
||||
|
||||
<a name="packuri"></a>
|
||||
|
||||
A related technique is to use a **Pack URI** to a XAML file, and refer to it as **Source**. **Pack URI** enables references to components of referenced assemblies and other techniques. For more information on **Pack URIs**, see [WPF Application Resource, Content, and Data Files](../../../framework/wpf/app-development/wpf-application-resource-content-and-data-files.md).
|
||||
|
||||
For resources that aren't compiled as part of the project, the URI is evaluated at run time. You can use a common URI transport such as _file:_ or _http:_ to refer to the resource file. The disadvantage of using the non-compiled resource approach is that _file:_ access requires additional deployment steps, and _http:_ access implies the Internet security zone.
|
||||
|
||||
## Reusing merged dictionaries
|
||||
|
||||
You can reuse or share merged resource dictionaries between applications, because the resource dictionary to merge can be referenced through any valid uniform resource identifier (URI). Exactly how you do this depends on your application deployment strategy and which application model you follow. The [previously mentioned **Pack URI** strategy](#packuri) provides a way to commonly source a merged resource across multiple projects during development by sharing an assembly reference. In this scenario the resources are still distributed by the client, and at least one of the applications must deploy the referenced assembly. It's also possible to reference merged resources through a distributed URI that uses the _http:_ protocol.
|
||||
|
||||
Writing merged dictionaries as local application files or to local shared storage is another possible merged dictionary and application deployment scenario.
|
||||
|
||||
## Localization
|
||||
|
||||
If resources that need to be localized are isolated to dictionaries that are merged into primary dictionaries, and kept as loose XAML, these files can be localized separately. This technique is a lightweight alternative to localizing the satellite resource assemblies. For details, see [WPF Globalization and Localization Overview](../../../framework/wpf/advanced/wpf-globalization-and-localization-overview.md).
|
||||
|
||||
## See also
|
||||
|
||||
- <xref:System.Windows.ResourceDictionary>
|
||||
- [Overview of XAML resources](xaml-resources-overview.md)
|
||||
- [Resources in code](xaml-resources-and-code.md)
|
||||
- [WPF Application Resource, Content, and Data Files](../../../framework/wpf/app-development/wpf-application-resource-content-and-data-files.md)
|
||||
- [WPF Globalization and Localization Overview](../../../framework/wpf/advanced/wpf-globalization-and-localization-overview.md)
|
||||
@@ -0,0 +1,180 @@
|
||||
---
|
||||
title: XAML resources overview
|
||||
description: Learn what a Windows Presentation Foundation (WPF) resource is. WPF provides a resource system, both in XAML and in code, that allows to you create, reference, and reuse resources.
|
||||
author: adegeo
|
||||
ms.author: adegeo
|
||||
ms.date: 03/31/2021
|
||||
ms.topic: overview
|
||||
dev_langs:
|
||||
- "csharp"
|
||||
- "vb"
|
||||
---
|
||||
|
||||
# Overview of XAML resources (WPF .NET)
|
||||
|
||||
A resource is an object that can be reused in different places in your app. Examples of resources include brushes and styles. This overview describes how to use resources in Extensible Application Markup Language (XAML). You can also create and access resources by using code.
|
||||
|
||||
> [!NOTE]
|
||||
> XAML resources described in this article are different from *app resources*, which are generally files added to an app, such as content, data, or embedded files.
|
||||
|
||||
[!INCLUDE [desktop guide under construction](../../includes/desktop-guide-preview-note.md)]
|
||||
|
||||
## Use resources in XAML
|
||||
|
||||
The following example defines a <xref:System.Windows.Media.SolidColorBrush> as a resource on the root element of a page. The example then references the resource and uses it to set properties of several child elements, including an <xref:System.Windows.Shapes.Ellipse>, a <xref:System.Windows.Controls.TextBlock>, and a <xref:System.Windows.Controls.Button>.
|
||||
|
||||
:::code language="xaml" source="./snippets/xaml-resources-overview/csharp/ResExample.xaml":::
|
||||
|
||||
Every framework-level element (<xref:System.Windows.FrameworkElement> or <xref:System.Windows.FrameworkContentElement>) has a <xref:System.Windows.FrameworkElement.Resources%2A> property, which is a <xref:System.Windows.ResourceDictionary> type that contains defined resources. You can define resources on any element, such as a <xref:System.Windows.Controls.Button>. However, resources are most often defined on the root element, which is <xref:System.Windows.Window> in the example.
|
||||
|
||||
Each resource in a resource dictionary must have a unique key. When you define resources in markup, you assign the unique key through the [x:Key Directive](../../../xaml-services/xkey-directive.md). Typically, the key is a string; however, you can also set it to other object types by using the appropriate markup extensions. Non-string keys for resources are used by certain feature areas in WPF, notably for styles, component resources, and data styling.
|
||||
|
||||
You can use a defined resource with the resource markup extension syntax that specifies the key name of the resource. For example, use the resource as the value of a property on another element.
|
||||
|
||||
```xaml
|
||||
<Button Background="{StaticResource MyBrush}"/>
|
||||
<Ellipse Fill="{StaticResource MyBrush}"/>
|
||||
```
|
||||
|
||||
In the preceding example, when the XAML loader processes the value `{StaticResource MyBrush}` for the <xref:System.Windows.Controls.Control.Background%2A> property on <xref:System.Windows.Controls.Button>, the resource lookup logic first checks the resource dictionary for the `Button` element. If `Button` doesn't have a definition of the resource key `MyBrush` (in that example it doesn't; its resource collection is empty), the lookup next checks the parent element of `Button`. If the resource isn't defined on the parent, it continues to check the object's logical tree upward until it's found.
|
||||
|
||||
If you define resources on the root element, all the elements in the logical tree, such as the <xref:System.Windows.Window> or <xref:System.Windows.Controls.Page>, can access it. And you can reuse the same resource for setting the value of any property that accepts the same type that the resource represents. In the previous example, the same `MyBrush` resource sets two different properties: [Button.Background](xref:System.Windows.Controls.Control.Background%2A) and [Rectangle.Fill](xref:System.Windows.Shapes.Shape.Fill%2A).
|
||||
|
||||
## Static and dynamic resources
|
||||
|
||||
A resource can be referenced as either static or dynamic. References are created by using either the [StaticResource Markup Extension](../../../framework/wpf/advanced/staticresource-markup-extension.md) or the [DynamicResource Markup Extension](../../../framework/wpf/advanced/dynamicresource-markup-extension.md). A markup extension is a XAML feature that lets you specify an object reference by having the markup extension process the attribute string and return the object to a XAML loader. For more information about markup extension behavior, see [Markup Extensions and WPF XAML](../../../framework/wpf/advanced/markup-extensions-and-wpf-xaml.md).
|
||||
|
||||
When you use a markup extension, you typically provide one or more parameters in string form that are processed by that particular markup extension. The [StaticResource Markup Extension](../../../framework/wpf/advanced/staticresource-markup-extension.md) processes a key by looking up the value for that key in all available resource dictionaries. Processing happens during load, which is when the loading process needs to assign the property value. The [DynamicResource Markup Extension](../../../framework/wpf/advanced/dynamicresource-markup-extension.md) instead processes a key by creating an expression, and that expression remains unevaluated until the app runs, at which time the expression is evaluated to provide a value.
|
||||
|
||||
When you reference a resource, the following considerations can influence whether you use a static resource reference or a dynamic resource reference:
|
||||
|
||||
- When determining the overall design of how you create the resources for your app (per page, in the app, in loose XAML, or in a resource-only assembly), consider the following:
|
||||
|
||||
- The app's functionality. Are updating resources in real-time part of your app requirements?
|
||||
- The respective lookup behavior of that resource reference type.
|
||||
- The particular property or resource type, and the native behavior of those types.
|
||||
|
||||
## Static resources
|
||||
|
||||
Static resource references work best for the following circumstances:
|
||||
|
||||
- Your app design concentrates most of its resources into page or application-level resource dictionaries.
|
||||
|
||||
Static resource references aren't reevaluated based on runtime behaviors, such as reloading a page. So there can be some performance benefit to avoiding large numbers of dynamic resource references when they aren't necessary based on your resource and app design.
|
||||
|
||||
- You're setting the value of a property that isn't on a <xref:System.Windows.DependencyObject> or a <xref:System.Windows.Freezable>.
|
||||
|
||||
- You're creating a resource dictionary that's compiled into a DLL that's shared between apps.
|
||||
|
||||
- You're creating a theme for a custom control and are defining resources that are used within the themes.
|
||||
|
||||
For this case, you typically don't want the dynamic resource reference lookup behavior. Instead, use static resource reference behavior so that the lookup is predictable and self-contained to the theme. With a dynamic resource reference, even a reference within a theme is left unevaluated until run-time. And, there's a chance that when the theme is applied, some local element will redefine a key that your theme is trying to reference, and the local element will fall before the theme itself in the lookup. If that happens, your theme won't behave as expected.
|
||||
|
||||
- You're using resources to set large numbers of dependency properties. Dependency properties have effective value caching as enabled by the property system, so if you provide a value for a dependency property that can be evaluated at load time, the dependency property doesn't have to check for a reevaluated expression and can return the last effective value. This technique can be a performance benefit.
|
||||
|
||||
- You want to change the underlying resource for all consumers, or you want to maintain separate writable instances for each consumer by using the [x:Shared Attribute](../../../xaml-services/xshared-attribute.md).
|
||||
|
||||
### Static resource lookup behavior
|
||||
|
||||
The following describes the lookup process that automatically happens when a static resource is referenced by a property or element:
|
||||
|
||||
01. The lookup process checks for the requested key within the resource dictionary defined by the element that sets the property.
|
||||
|
||||
01. The lookup process then traverses the logical tree upward to the parent element and its resource dictionary. This process continues until the root element is reached.
|
||||
|
||||
01. App resources are checked. App resources are those resources within the resource dictionary that is defined by the <xref:System.Windows.Application> object for your WPF app.
|
||||
|
||||
Static resource references from within a resource dictionary must reference a resource that has already been defined lexically before the resource reference. Forward references cannot be resolved by a static resource reference. For this reason, design your resource dictionary structure such that resources are defined at or near the beginning of each respective resource dictionary.
|
||||
|
||||
Static resource lookup can extend into themes or into system resources, but this lookup is supported only because the XAML loader defers the request. The deferral is necessary so that the runtime theme at the time the page loads applies properly to the app. However, static resource references to keys that are known to only exist in themes or as system resources aren't recommended, because such references aren't reevaluated if the theme is changed by the user in real time. A dynamic resource reference is more reliable when you request theme or system resources. The exception is when a theme element itself requests another resource. These references should be static resource references, for the reasons mentioned earlier.
|
||||
|
||||
The exception behavior if a static resource reference isn't found varies. If the resource was deferred, then the exception occurs at runtime. If the resource wasn't deferred, the exception occurs at load time.
|
||||
|
||||
## Dynamic resources
|
||||
|
||||
Dynamic resources work best when:
|
||||
|
||||
- The value of the resource, including system resources, or resources that are otherwise user settable, depends on conditions that aren't known until runtime. For example, you can create setter values that refer to system properties as exposed by <xref:System.Windows.SystemColors>, <xref:System.Windows.SystemFonts>, or <xref:System.Windows.SystemParameters>. These values are truly dynamic because they ultimately come from the runtime environment of the user and operating system. You might also have application-level themes that can change, where page-level resource access must also capture the change.
|
||||
|
||||
- You're creating or referencing theme styles for a custom control.
|
||||
|
||||
- You intend to adjust the contents of a <xref:System.Windows.ResourceDictionary> during an app lifetime.
|
||||
|
||||
- You have a complicated resource structure that has interdependencies, where a forward reference may be required. Static resource references don't support forward references, but dynamic resource references do support them because the resource doesn't need to be evaluated until runtime, and forward references are therefore not a relevant concept.
|
||||
|
||||
- You're referencing a resource that is large from the perspective of a compile or working set, and the resource might not be used immediately when the page loads. Static resource references always load from XAML when the page loads. However, a dynamic resource reference doesn't load until it's used.
|
||||
|
||||
- You're creating a style where setter values might come from other values that are influenced by themes or other user settings.
|
||||
|
||||
- You're applying resources to elements that might be reparented in the logical tree during app lifetime. Changing the parent also potentially changes the resource lookup scope, so if you want the resource for a reparented element to be reevaluated based on the new scope, always use a dynamic resource reference.
|
||||
|
||||
### Dynamic resource lookup behavior
|
||||
|
||||
Resource lookup behavior for a dynamic resource reference parallels the lookup behavior in your code if you call <xref:System.Windows.FrameworkElement.FindResource%2A> or <xref:System.Windows.FrameworkElement.SetResourceReference%2A>:
|
||||
|
||||
01. The lookup checks for the requested key within the resource dictionary defined by the element that sets the property:
|
||||
|
||||
- If the element defines a <xref:System.Windows.FrameworkElement.Style%2A> property, the <xref:System.Windows.FrameworkElement.Style?displayProperty=fullName> of the element has its <xref:System.Windows.Style.Resources> dictionary checked.
|
||||
|
||||
- If the element defines a <xref:System.Windows.Controls.Control.Template%2A> property, the <xref:System.Windows.FrameworkTemplate.Resources?displayProperty=fullName> dictionary of the element is checked.
|
||||
|
||||
01. The lookup traverses the logical tree upward to the parent element and its resource dictionary. This process continues until the root element is reached.
|
||||
|
||||
01. App resources are checked. App resources are those resources within the resource dictionary that are defined by the <xref:System.Windows.Application> object for your WPF app.
|
||||
|
||||
01. The theme resource dictionary is checked for the currently active theme. If the theme changes at runtime, the value is reevaluated.
|
||||
|
||||
01. System resources are checked.
|
||||
|
||||
Exception behavior (if any) varies:
|
||||
|
||||
- If a resource was requested by a <xref:System.Windows.FrameworkElement.FindResource%2A> call and wasn't found, an exception is thrown.
|
||||
|
||||
- If a resource was requested by a <xref:System.Windows.FrameworkElement.TryFindResource%2A> call and wasn't found, no exception is thrown, and the returned value is `null`. If the property being set doesn't accept `null`, then it's still possible that a deeper exception will be thrown, depending on the individual property being set.
|
||||
|
||||
- If a resource was requested by a dynamic resource reference in XAML and wasn't found, then the behavior depends on the general property system. The general behavior is as if no property setting operation occurred at the level where the resource exists. For instance, if you attempt to set the background on an individual button element using a resource that could not be evaluated, then no value set results, but the effective value can still come from other participants in the property system and value precedence. For instance, the background value might still come from a locally defined button style or from the theme style. For properties that aren't defined by theme styles, the effective value after a failed resource evaluation might come from the default value in the property metadata.
|
||||
|
||||
### Restrictions
|
||||
|
||||
Dynamic resource references have some notable restrictions. At least one of the following conditions must be true:
|
||||
|
||||
- The property being set must be a property on a <xref:System.Windows.FrameworkElement> or <xref:System.Windows.FrameworkContentElement>. That property must be backed by a <xref:System.Windows.DependencyProperty>.
|
||||
|
||||
- The reference is for a value within a `StyleSetter`.
|
||||
|
||||
- The property being set must be a property on a <xref:System.Windows.Freezable> that is provided as a value of either a <xref:System.Windows.FrameworkElement> or <xref:System.Windows.FrameworkContentElement> property, or a <xref:System.Windows.Setter> value.
|
||||
|
||||
Because the property being set must be a <xref:System.Windows.DependencyProperty> or <xref:System.Windows.Freezable> property, most property changes can propagate to the UI because a property change (the changed dynamic resource value) is acknowledged by the property system. Most controls include logic that will force another layout of a control if a <xref:System.Windows.DependencyProperty> changes and that property might affect layout. However, not all properties that have a [DynamicResource Markup Extension](../../../framework/wpf/advanced/dynamicresource-markup-extension.md) as their value are guaranteed to provide real-time updates in the UI. That functionality still might vary depending on the property, and depending on the type that owns the property, or even the logical structure of your app.
|
||||
|
||||
## Styles, DataTemplates, and implicit keys
|
||||
|
||||
Although all items in a <xref:System.Windows.ResourceDictionary> must have a key, that doesn't mean that all resources must have an explicit `x:Key`. Several object types support an implicit key when defined as a resource, where the key value is tied to the value of another property. This type of key is known as an implicit key, and an `x:Key` attribute is an explicit key. You can overwrite any implicit key by specifying an explicit key.
|
||||
|
||||
One important scenario for resources is when you define a <xref:System.Windows.Style>. In fact, a <xref:System.Windows.Style> is almost always defined as an entry in a resource dictionary, because styles are inherently intended for reuse. For more information about styles, see [Styles and templates (WPF .NET)](../controls/styles-templates-overview.md).
|
||||
|
||||
Styles for controls can be both created with and referenced with an implicit key. The theme styles that define the default appearance of a control rely on this implicit key. From the standpoint of requesting it, the implicit key is the <xref:System.Type> of the control itself. From the standpoint of defining the resources, the implicit key is the <xref:System.Windows.Style.TargetType%2A> of the style. As such, if you're creating themes for custom controls or creating styles that interact with existing theme styles, you don't need to specify an [x:Key Directive](../../../xaml-services/xkey-directive.md) for that <xref:System.Windows.Style>. And if you want to use the themed styles, you don't need to specify any style at all. For instance, the following style definition works, even though the <xref:System.Windows.Style> resource doesn't appear to have a key:
|
||||
|
||||
:::code language="xaml" source="./snippets/xaml-resources-overview/csharp/ImplicitStyle.xaml" id="ImplicitStyle":::
|
||||
|
||||
That style really does have a key: the implicit key: the `System.Windows.Controls.Button` type. In markup, you can specify a <xref:System.Windows.Style.TargetType%2A> directly as the type name (or you can optionally use [{x:Type...}](../../../xaml-services/xtype-markup-extension.md) to return a <xref:System.Type>.
|
||||
|
||||
Through the default theme style mechanisms used by WPF, that style is applied as the runtime style of a <xref:System.Windows.Controls.Button> on the page, even though the <xref:System.Windows.Controls.Button> itself doesn't attempt to specify its <xref:System.Windows.FrameworkElement.Style%2A> property or a specific resource reference to the style. Your style defined in the page is found earlier in the lookup sequence than the theme dictionary style, using the same key that the theme dictionary style has. You could just specify `<Button>Hello</Button>` anywhere in the page, and the style you defined with <xref:System.Windows.Style.TargetType%2A> of `Button` would apply to that button. If you want, you can still explicitly key the style with the same type value as <xref:System.Windows.Style.TargetType%2A> for clarity in your markup, but that is optional.
|
||||
|
||||
Implicit keys for styles don't apply on a control if <xref:System.Windows.FrameworkElement.OverridesDefaultStyle%2A> is `true`. (Also note that <xref:System.Windows.FrameworkElement.OverridesDefaultStyle%2A> might be set as part of native behavior for the control class, rather than explicitly on an instance of the control.) Also, to support implicit keys for derived class scenarios, the control must override <xref:System.Windows.FrameworkElement.DefaultStyleKey%2A> (all existing controls provided as part of WPF include this override). For more information about styles, themes, and control design, see [Guidelines for Designing Stylable Controls](../../../framework/wpf/controls/guidelines-for-designing-stylable-controls.md).
|
||||
|
||||
<xref:System.Windows.DataTemplate> also has an implicit key. The implicit key for a <xref:System.Windows.DataTemplate> is the <xref:System.Windows.DataTemplate.DataType%2A> property value. <xref:System.Windows.DataTemplate.DataType%2A> can also be specified as the name of the type rather than explicitly using [{x:Type...}](../../../xaml-services/xtype-markup-extension.md). For details, see [Data Templating Overview](../../../framework/wpf/data/data-templating-overview.md).
|
||||
|
||||
## See also
|
||||
|
||||
- [Resources in code](xaml-resources-and-code.md)
|
||||
- [Merged resource dictionaries](xaml-resources-merged-dictionaries.md)
|
||||
- [How to define and reference a WPF resource](xaml-resources-how-to-define-and-reference.md)
|
||||
- [How to use system resources](xaml-resources-how-to-use-system.md)
|
||||
- [How to use application resources](xaml-resources-how-to-use-application.md)
|
||||
- [x:Type markup extension](../../../xaml-services/xtype-markup-extension.md)
|
||||
- <xref:System.Windows.ResourceDictionary>
|
||||
- [Application resources](../../../framework/wpf/advanced/optimizing-performance-application-resources.md)
|
||||
- [Define and reference a resource](../../../framework/wpf/advanced/how-to-define-and-reference-a-resource.md)
|
||||
- [Application management overview](../../../framework/wpf/app-development/application-management-overview.md)
|
||||
- [StaticResource markup extension](../../../framework/wpf/advanced/staticresource-markup-extension.md)
|
||||
- [DynamicResource markup extension](../../../framework/wpf/advanced/dynamicresource-markup-extension.md)
|
||||
Reference in New Issue
Block a user