コンテンツ コントロールにさまざまなユーザー コントロールを表示するメイン ウィンドウを作成しました。このウィンドウには、ユーザー コントロールとそれに付随するビュー モデルが DataTemplate リソースとして XAML に含まれています。このウィンドウには、コンテンツ コントロールにユーザー コントロールを表示し、そのビュー モデルをインスタンス化する必要があるボタンがあります。どのユーザー コントロールとビュー モデルを使用するかをコマンドに指示できるように、RelayCommand にリソースを渡すにはどうすればよいですか? ハードコーディングされた文字列をコマンド パラメーターとして渡す方法を理解しましたが、x:Name を渡したいので、このコマンドなどを複数の View-ViewModel で再利用できます。
メイン ウィンドウの XAML スニペット:
<Window.Resources>
<!--User Controls and Accompanying View Models-->
<DataTemplate DataType="{x:Type EmployerSetupVM:EmployerSetupVM}" x:Key="EmployerSetup" x:Name="EmployerSetup">
<EmployerSetupView:EmployerSetupView />
</DataTemplate>
<DataTemplate DataType="{x:Type VendorSetupVM:VendorSetupVM}">
<VendorSetupView:VendorSetupView />
</DataTemplate>
</Window.Resources>
<Button Style="{StaticResource LinkButton}" Command="{Binding ShowCommand}" CommandParameter="{StaticResource EmployerSetup}">
... メイン ウィンドウの ViewModel で、ここまでの関連コード:
public RelayCommand<DataTemplate> ShowCommand
{
get;
private set;
}
ShowCommand = new RelayCommand<string>((s) => ShowExecuted(s));
private void ShowExecuted(DataTemplate s)
{
var fred = (s.DataType); //how do i get the actual name here, i see it when i hover with intellisense, but i can't access it!
if (!PageViewModels.Contains(EmployerSetupVM))
{
EmployerSetupVM = new EmployerSetupVM();
PageViewModels.Add(EmployerSetupVM);
}
int i = PageViewModels.IndexOf(EmployerSetupVM);
ChangeViewModel(PageViewModels[i]);
}
... つまり、XAML で x:Key="EmployerSetup" を使用して DataTemplate の名前を取得するにはどうすればよいですか? それが問題なら、私もMVVMLightを使用しています