WPFにおけるPrism集中講座(5) ViewModelとCommandを使う

08-ViewModelLocator Descriptionには using the ViewModelLocator と書かれています。 このサンプルでは、アプリケーションのタイトルが変更されます。 Views\MainWindow.xaml <Window x:Class="ViewModelLocator.Views.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:prism="http://prismlibrary.com/" Title="{Binding Title}" Width="525" Height="350" prism:ViewModelLocator.AutoWireViewModel="True"> <Grid> <ContentControl prism:RegionManager.RegionName="ContentRegion" /> </Grid> </Window> ViewModels\MainWindowViewModel.cs namespace ViewModelLocator.ViewModels { public class MainWindowViewModel : BindableBase { private string _title = "Prism Unity Application"; public string Title { get { return _title; } set { SetProperty(ref _title, value); } } public MainWindowViewModel() { } } } まあ、これ CommunityToolkit.Mvvm の覚え書き をきちんと読んでくれた人なら「ほとんど同じ」となりますよね? CommunityToolkit.Mvvm では ObservableObject だったところが BindingBase になっているだけです。 違いは、View…ここでは MainWindow.xaml.cs に当たりますが、 ここで DataContext に設定しなくても動くことでしょうか? ...

2025年01月17日 · (0001年01月01日 更新) · 7 分 · ☨もりゃき.xyz☨

WPFにおけるPrism集中講座(4) ソリューション内のプロジェクトを利用する

07-Modules-AppConfig Description には Load modules using an App.config file と書かれています。 さて、これは何でしょうね?実行したら「View A」と表示されます。 ソリューションを見てみると、プロジェクト「Modules」と「ModuleA」があります。 おそらく「Modules」から「ModuleA」のView を使っているのでしょう。 App.config <?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <section name="modules" type="Prism.Modularity.ModulesConfigurationSection, Prism.Wpf" /> </configSections> <startup> </startup> <modules> <module assemblyFile="ModuleA.dll" moduleType="ModuleA.ModuleAModule, ModuleA, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" moduleName="ModuleAModule" startupLoaded="True" /> </modules> </configuration> 更新されたファイル単体では分かりにくいので、06-ViewActivationDeactivation の App.config を引用してみます。 <?xml version="1.0" encoding="utf-8"?> <configuration> <startup> </startup> </configuration> はい、見事に空っぽですね。 実際 ModuleA フォルダを bin を基準に掘っていくと ModuleA.dll があります。 では ModuleA にある肝心の変更部分を見てみましょう。 ModuleA\ModuleAModule.cs using ModuleA.Views; namespace ModuleA { public class ModuleAModule : IModule { public void OnInitialized(IContainerProvider containerProvider) { var regionManager = containerProvider.Resolve<IRegionManager>(); regionManager.RegisterViewWithRegion("ContentRegion", typeof(ViewA)); } public void RegisterTypes(IContainerRegistry containerRegistry) { } } } 他の変更は些細なものなので省略します。 ...

2025年01月16日 · (0001年01月01日 更新) · 3 分 · ☨もりゃき.xyz☨

WPFにおけるPrism集中講座(3) 試しにViewのサンプルを書いてみる

プロジェクトの下準備 まず、MainWindow からメニューで「設定」を開いて、設定画面から「設定終了」ボタンで MainWindow に戻るサンプルです。 新規ソリューションを「WPFアプリケーション」で作成します。.NET 9 を利用すれば良いでしょう。 ここでは SimplePrismViewSample という名前にしています。 そして、NuGet から Prism.Unity をインストールします。自分は Visual Studio の NuGet 管理から入れていますが、dotnet 等を扱える人に、改めての説明は不要でしょう。 App.xaml 周辺の設定 Views の設定 ソリューションエクスプローラで Views フォルダを作り、MainWindow.xaml を Views フォルダに移動します。 デフォルトのソリューション直下に MainWindow.xaml を置いていたら、以下の書き換えでエラーを吐きます。 …一体どこに Views が含まれてるんですかね?ブラックボックス臭い… MainWindow.xaml の修正 <Window x:Class="SimplePrismViewSample.Views.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:prism="http://prismlibrary.com/" Title="SimplePrismViewSample" Width="525" Height="350"> <Grid> <ContentControl prism:RegionManager.RegionName="ContentRegion" /> </Grid> </Window> MainWindow.xaml の位置を移動したので、x:Class="SimplePrismViewSample.MainWindow" を x:Class="SimplePrismViewSample.Views.MainWindow" に書き換える必要があります。 App.xaml の記述 App.xaml を以下のように書き換えます。 <prism:PrismApplication x:Class="SimplePrismViewSample.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:SimplePrismViewSample" xmlns:prism="http://prismlibrary.com/"> <Application.Resources /> </prism:PrismApplication> App.xaml.cs の記述 App.xaml.cs を以下のように書き換えます。 ...

2025年01月15日 · (0001年01月01日 更新) · 2 分 · ☨もりゃき.xyz☨

WPFにおけるPrism集中講座(2) region の謎

04-ViewDiscovery Descriptionには Automatically inject views with View Discovery とあります。 やっと動きがありました。とはいえ、アプリケーションを動かしても「View A」と表示されるだけですけどね… App.xaml <prism:PrismApplication x:Class="ViewDiscovery.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:ViewDiscovery" xmlns:prism="http://prismlibrary.com/"> <Application.Resources /> </prism:PrismApplication> App.xaml.cs using System.Windows; using ViewDiscovery.Views; namespace ViewDiscovery { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : PrismApplication { protected override Window CreateShell() { return Container.Resolve<MainWindow>(); } protected override void RegisterTypes(IContainerRegistry containerRegistry) { } } } MainWindow.xaml <Window x:Class="ViewDiscovery.Views.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:prism="http://prismlibrary.com/" Title="Shell" Width="525" Height="350"> <Grid> <ContentControl prism:RegionManager.RegionName="ContentRegion" /> </Grid> </Window> MainWindow.xaml.cs using System.Windows; namespace ViewDiscovery.Views { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow(IRegionManager regionManager) { InitializeComponent(); //view discovery regionManager.RegisterViewWithRegion("ContentRegion", typeof(ViewA)); } } } ここで、ContentRegion にリージョン ViewA を割りあてているのでしょう。 ...

2025年01月14日 · (0001年01月01日 更新) · 3 分 · ☨もりゃき.xyz☨

WPFにおけるPrism集中講座(1) 序盤のサンプルについて

Prismについて 正直、この記事を読んでいる方には、今さら説明は不要でしょう。 特にこの記事はWPFを中心に書いているため、WPFとPrismといえばMVVMのためのライブラリ。そのPrismについて徹底解説をしていこうと思います。 PrismLibrary/Prism-Samples-Wpf 01-BootstrapperShell 正直、このサンプルに戸惑った人は多いのではないでしょうか? Descriptionoには Create a basic bootstrapper and shell と書かれています。 初期プロジェクトから書き換え、追記されているのは以下の通りです。 App.xaml <Application x:Class="BootstrapperShell.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:BootstrapperShell"> <Application.Resources /> </Application> App.xaml.cs using System.Windows; namespace BootstrapperShell { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); var bootstrapper = new Bootstrapper(); bootstrapper.Run(); } } } MainWindow.xaml <Window x:Class="BootstrapperShell.Views.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Shell" Width="525" Height="350"> <Grid> <ContentControl Content="Hello from Prism" /> </Grid> </Window> Bootstrapper.cs using System.Windows; using BootstrapperShell.Views; namespace BootstrapperShell { class Bootstrapper : PrismBootstrapper { protected override DependencyObject CreateShell() { return Container.Resolve<MainWindow>(); } protected override void RegisterTypes(IContainerRegistry containerRegistry) { } } } ざっくり言うと App.xaml.cs から Bootstrapper インスタンスを生成して、それを走らせ Run するわけですね。 で Bootstrapper.cs では PrismBootstrapper という、よく分からないブートストラッパが継承されています。 ...

2025年01月13日 · (0001年01月01日 更新) · 2 分 · ☨もりゃき.xyz☨

カップ麺シリーズ:一から学べる、WPFでの多言語対応方法

多言語対応をしよう 今やグローバル時代!世界を相手にしなければ勝てない! そう、東京弁だけでなく大阪弁、名古屋弁、博多弁など…ごめんなさい調子に乗りました、単純に「日本語」「英語」「ロシア語」対応について語ります。 真面目な話、ソフトウェアで最低限英語対応すると、ターゲットが英語圏の人にまで届く可能性が高まります。 もちろん、ドキュメントも英語化が必要ですけど、今ならDeepLとか使えば便利にそれっぽく翻訳してくれますからね。 さらにChatGPTで添削とかさせれば、ニュアンス踏まえて指摘してくれますよ! 今回は、WPFにおいてViewとViewModelだけを使った、極めてシンプルな多言語対応サンプルを示したいと思います。 プロジェクト作成 今回は「WPFアプリケーション」で MultiLanguageTest というプロジェクトを作りましょう。フレームワークは「.NET 9.0」を使用します。 そして開かれた MainWindow.xaml を以下のようにしましょう。 「Language」の中に「Japanese」「English」「Russian」として、ウィンドウ内全域にボタンを貼り付けているだけです。 <Window x:Class="MultiLanguageTest.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:MultiLanguageTest" mc:Ignorable="d" Title="MultiLanguageTest" Height="450" Width="800"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <Menu> <MenuItem Header="Language"> <MenuItem Header="Japanese" Command="{Binding ToJapanese}"/> <MenuItem Header="English" Command="{Binding ToEnglish}"/> <MenuItem Header="Russian" Command="{Binding ToRussian}"/> </MenuItem> </Menu> <Button Grid.Row="1" Margin="5" Content="{Binding Greetings}" Command="{Binding ExecuteGreetings}"/> </Grid> </Window> シンプルなテストなので、UIに関しては最低限の実装になっています。画面とかは本題じゃないからいいよね? 下準備に CommunityToolkit.Mvvm の導入 利便性のため、NuGetで CommunityToolkit.Mvvm を導入します。 メニューの「ツール」-「NuGetパッケージマネージャ」-「ソリューションのNuGetパッケージの管理」から、 「参照」タブをクリックして CommunityToolkit.Mvvm を検索してプロジェクトにインストールします。 ライセンスが不安かも知れませんが CommunityToolkit.Mvvm はMITライセンスという、オープンソースライセンスの中で最も緩いライセンスです。 CommunityToolkit.Mvvm 自体を配布しないのであれば、商用とかクローズドソースもOKなので心配は要らないでしょう。 ほら、あの Xamarin で使われていた(もう過去形なんだよな…) Mono と同じライセンスです。 っていうか、これは CommunityToolkit.Mvvm 覚え書きに書くべき内容だったか…? 自分の目で確認したい方は.NET Community Toolkitをどうぞ。 ...

2024年11月12日 · (2025年05月20日 更新) · 3 分 · ☨もりゃき.xyz☨

カップ麺シリーズ:C#でSHGetFileInfoをDllImportからLibraryImportに書き換え

最低限DllImportの使い方を理解している方を対象にしています。この記事をコピペで利用した際の責任は一切負いません あの、C# で Windowsのファイルアイコンやら色々な情報を獲得する SHGetFileInfo の宣言を、DllImportからLibraryImportに書き換えて、憎きSYSLIB1054を一つ撲滅する方法をお伝えします。 まず、C# での DllImportのパターンは、よく見るのはこういう宣言ですね。 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct SHFILEINFO { public IntPtr hIcon; public int iIcon; public uint dwAttributes; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string szDisplayName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] public string szTypeName; }; [DllImport("shell32.dll", CharSet = CharSet.Unicode)] private static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttribs, ref SHFILEINFO psfi, uint cbFileInfo, SHGFI uFlags); そして SHGETFILEINFO の使い方はこんな感じですよね? SHFILEINFO shinfo = new(); IntPtr shFileInfoResult; // ここ shFileInfoResult = SHGetFileInfo(path, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), SHGFI.SHGFI_ICON | SHGFI.SHGFI_SMALLICON | SHGFI.SHGFI_TYPENAME); if (shFileInfoResult == IntPtr.Zero || shinfo.hIcon == IntPtr.Zero) { int lastError = Marshal.GetLastWin32Error(); throw new Exception($"SHGetFileInfo Failed with error code {lastError}"); } BitmapSource icon = Imaging.CreateBitmapSourceFromHIcon(shinfo.hIcon, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); DestroyIcon(shinfo.hIcon); // あとはiconとshinfo.szTypeNameでアイコンとファイル種類が手に入る で、今となっては C# の DllImport を使った SHGetFileInfo に警告 SYSLIB1054 が出てくる、という状況です。 ...

2023年12月14日 · (0001年01月01日 更新) · 2 分 · ☨もりゃき.xyz☨