0

コンテンツ コントロールにさまざまなユーザー コントロールを表示するメイン ウィンドウを作成しました。このウィンドウには、ユーザー コントロールとそれに付随するビュー モデルが 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を使用しています

4

1 に答える 1

1

クラスTypeのNameプロパティを使用してみてください。

private void ShowExecuted(DataTemplate s) {
  var typeName = s.DataType as Type;
  if (typeName == null)
    return;
  var className = typeName.Name;  // className will be EmployerSetupVM or VendorSetupVM
  ...
}

をVMに渡すのDataTemplateは奇妙に思えます。Button.Style2 つのコマンドを用意し、条件に応じて使用するコマンドを切り替えるだけです。

単一のものを使用する必要がある場合、または世界が終了する可能性がある場合は、オブジェクト全体を渡すよりもRelayCommand、xaml から参照できる静的な列挙型を使用する傾向があります。CommandParameterDataTemplate

于 2013-06-10T13:25:30.197 に答える