WPFのStaticResourceは動的に値を変更できないと書かれている記事が多いですが、アプリケーション起動時にstaticコンストラクタから変更できます。
国際化する必要があり、StaticResourceのパフォーマンスが求められる場合で、尚且つ、対応言語分のXAMLやResource.resxファイル以外に、xmlやdatの独自言語ファイルを用意する必要がある場合、アプリケーション起動時にstaticコンストラクタで言語ファイルを読み込んで、各WPF画面のStaticResourceに展開するということが可能です。
StaticResourceサンプル
MainWindow.xaml
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16  | 
						<Window x:Class="VSShowFontDemo.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:WpfApplication1"         mc:Ignorable="d"         Title="MainWindow" Height="150" Width="225">     <Grid>         <StackPanel Orientation="Vertical">             <TextBlock x:Name="textBlock" HorizontalAlignment="Left" Margin="13,14,0,0" TextWrapping="Wrap" Text="{x:Static local:Disp.str}" VerticalAlignment="Top"/>         </StackPanel>     </Grid> </Window>  | 
					
Disp.cs
| 
					 1 2 3 4 5 6 7 8 9 10 11  | 
						public static class Disp {     public static string str { get; private set; } = "あああ";     static Disp()     {         str = "いいい";     } }  | 
					
DynamicResourceサンプル
App.xaml
| 
					 1 2 3 4 5 6 7 8 9 10 11 12  | 
						<Application x:Class="WpfApplication1.App"              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"              xmlns:local="clr-namespace:WpfApplication1"              xmlns:system="clr-namespace:System;assembly=mscorlib"              StartupUri="MainWindow.xaml">     <Application.Resources>         <system:String x:Key="localizedMessage">test</system:String>     </Application.Resources> </Application>  | 
					
MainWindow.xaml
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14  | 
						<Window x:Class="WpfApplication1.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:WpfApplication1"         mc:Ignorable="d"         Title="MainWindow" Height="150" Width="225">     <Grid>         <TextBlock x:Name="textBlock" HorizontalAlignment="Left" Margin="13,14,0,0" TextWrapping="Wrap" Text="{DynamicResource localizedMessage}" VerticalAlignment="Top"/>     </Grid> </Window>  | 
					
MainWindow.xaml.cs
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14  | 
						/// <summary> /// MainWindow.xaml の相互作用ロジック /// </summary> public partial class MainWindow : Window {     public MainWindow()     {         InitializeComponent();                App.Current.Resources["localizedMessage"] = "テスト";     } }  | 
					
WPF開発 記事一覧
  
  
  
  

コメント