Posted on 2025/05/04, 11:46 AM By admin22
Windows Presentation Foundation (WPF) のマークアップ言語XAMLをアプリケーションの外部ファイルとして編集するテストをしてみました。
アプリケーションをリビルドすることなく、またコードを変更することなく、レイアウト、文字列などを変更することが目的です。
アプリケーションの信頼性が下がるので、推奨されるやり方ではないようですが、できるということは利用価値があります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
using System.Text; 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; using System.IO; using System.Windows.Markup; namespace WpfApp4 { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); LoadLooseXaml("Views/HelloView.xaml"); } private void LoadLooseXaml(string path) { if (!File.Exists(path)) { MessageBox.Show($"XAMLファイルが見つかりません: {path}"); return; } using var stream = new FileStream(path, FileMode.Open, FileAccess.Read); var content = (UIElement)XamlReader.Load(stream); MainGrid.Children.Clear(); MainGrid.Children.Add(content); } } } |
HelloView.xaml
1 2 3 4 5 6 7 |
<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center"> <TextBlock Text="Hello from Loose XAML!" FontSize="24" HorizontalAlignment="Center"/> <Button Content="Click me" Width="100" Margin="10"/> </StackPanel> </Grid> |
上記をテキストエディタで編集するだけで表示が変更されました。
昔のMacOSは、リソースエディタというものが標準で備わっており、アプリケーションの文字列などのリソースを改変することが簡単にできました。ローカリゼーションにはうってつけですね。
アプリの改変が今の時代、セキュリティリスクになることを考えると当たり前ですが、そんないい時代があったものだと、(みんないい人だったね)懐かしい気持ちになります。
Categories: 未分類 タグ: XAML