質問

次のRoutedCommandの例は機能します。

ただし、コマンドを実行するボタンの処理は、ビューのコードビハインドにあります。私がMVVMを理解する方法は、 ViewModelにあるべきです

ただし、メソッドをViewModelに移動(およびパブリックに変更)すると、「 ManagedCustomersViewにはOnSaveの定義が含まれていません」というエラーが表示されます。 RoutedCommandの2番目のパラメーターをtypeof(ManageCustomersViewModel)に変更しても、同じエラーが発生します。

View-codebehindからViewModelにコマンドハンドラーを移動するにはどうすればよいですか

ManageCustomersView.xaml:

<UserControl.CommandBindings>
   <CommandBinding Command="local:Commands.SaveCustomer" Executed="OnSave"/>
</UserControl.CommandBindings>
...
<Button Style="{StaticResource formButton}" 
   Content="Save" 
   Command="local:Commands.SaveCustomer"
   CommandParameter="{Binding Id}"/>

ManageCustomersView.xaml.cs:

private void OnSave(object sender
                    , System.Windows.Input.ExecutedRoutedEventArgs e)
{
    int customerId = ((int)e.Parameter);
    MessageBox.Show(String.Format
        ("You clicked the save button for customer with id {0}.", customerId));
}

Commands.cs:

using System.Windows.Input;
using TestDynamicForm123.View;

namespace TestDynamicForm123
{
    public class Commands
    {
        public static RoutedCommand SaveCustomer = 
             new RoutedCommand("SaveCustomer", typeof(ManageCustomersView));
    }
}
役に立ちましたか?

解決

コマンドを参照するViewModelからプロパティを公開します。

class MyViewModel
{
    public RoutedCommand SaveCmd{ get{ return Commands.SaveCustomer; } }
}  

次にXAMLで

<Button Command="{Binding SaveCmd}" />

ただし、 RelayCommand を使用する方が簡単な場合があります。モデルで実際のコマンドロジックを定義することもできます。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top