UserControlで部分テンプレートを作る
生のC#で行う方法とprismライブラリを使用した場合で比較しました。
基本の方法
- 以下のディレクトリ構成にてMainWindow.xamlにRingo.xamlを表示する
Solution'Item'
Item(project)
View
MainWindow.xaml
Fruit
Ringo.xaml
MainWindow.xaml
<Window
x:Class="Fruit.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Fruit">
<StackPanel>
//「local」は表示したいxaml(xaml.cs)のnamespace
<local:Ringo/>
<TextBox Text="ここはMainWindow">
</StackPanel>
</Window>
Ringo.xaml
<UserControl
x:Class="Fruit.SimpleUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel Orientation="Horizontal">
<TextBox Text="ここはりんご">
</StackPanel>
</UserControl>
PrismのRegionManagerを使った場合
- ディレクトリを変更
Solution'Item'
Item(project)
View
Fruit
Ringo.xaml
MainWindow.xaml
MainWindow.xaml.cs //New!
RegionNames.cs //New!
RegionNames.cs
//文字列を変数として扱うクラス
//なくてもできるけどintelisenceが働くからあった方が良い
namespace Item
{
public static class RegionName
{
public static readonly string Ringo = "Ringo";
}
}
MainWindow.xaml.cs
//コードビハインドでRegionManagerを登録
namespace Item.View
{
public partial class MainWindow : Window
{
public MainWindow(IRegionManager regionManager)
{
InitializeComponent();
regionManager.RegisterViewWithRegion(RegionName.Ringo, typeof(Ringo));
}
}
}
MainWindow.xaml
<Window x:Class="Item.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/" //New!
prism:ViewModelLocator.AutoWireViewModel="True" //New!
xmlns:Item="clr-namespace:Item" //New!
Title="Item">
<Grid>
//prismのRegionNameに文字列を登録している
//文字列はx:static
//xmlns:ItemというnamespaceのRegionNameクラスにあるRingoプロパティ
<ContentControl prism:RegionManager.RegionName="{x:Static Item:RegionName.Ringo}">
</ContentControl>
</Grid>
</Window>
- xamlマークアップ拡張(x:staticなど)
「マークアップ拡張」は、「{」と「}」の2つの中括弧を使用することでXAMLパーサに対し、拡張されたプロパティ指定方法を指示する。
https://techinfoofmicrosofttech.osscons.jp/index.php?XAML%E3%81%AE%E6%9B%B8%E3%81%8D%E6%96%B9%EF%BC%88%EF%BC%91%EF%BC%89#ad009a58