ViewModelからWPFでコマンドを実行する2つの異なる方法を試しましたが、不足しています。一番上の方法は、ビューに入れるとうまく機能しますが、これは悪い習慣だと言われました。私が言われた2番目の方法は、MVVMでカスタムコマンドを実行する適切な方法ですが、ビューからコマンドを実際に呼び出す/バインドする方法に固執しています。
モデルの表示:
class MainViewModel : INotifyPropertyChanged
{
#region INPC
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
public readonly static RoutedUICommand myCommand;
static MainViewModel()
{
myCommand = new RoutedUICommand("customCommand","My Command",typeof(MainViewModel));
}
private void ExecutemyCommand(object sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show("textBox1 cleared");
}
private void myCommandCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
}
私のビューで私は私にエラーを与えるこれを持っています
<Window x:Class="ConfigManager2.View.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:con="clr-namespace:ConfigManager2.Converters"
xmlns:vm="clr-namespace:ConfigManager2.ViewModel"
xmlns:local="clr-namespace:ConfigManager2.View"
.
.
.
<Window.CommandBindings>
<CommandBinding
Command="{x:Static vm:MainViewModel.myCommand}"
CanExecute="myCommandCanExecute"
Executed="ExecutemyCommand" />
</Window.CommandBindings>
.
.
.
<Button Content="COMMAND ME" Height="50px" Command="{x:Static vm:MainViewModel.myCommand}" />
私が得ているエラーは「ConfigManager2.View.MainView」に「ExecutemyCommand」の定義が含まれておらず、タイプ「ConfigManager2.View.MainView」の最初の引数を受け入れる拡張メソッド「ExecutemyCommand」が見つかりませんでした(ディレクティブまたはアセンブリ参照を使用しますか?)
ICommandを使用して別の方法を試しましたが、これをXAMLから上記のボタンにバインドする方法に困惑しました
ViewModel:
public ICommand ClearCommand { get; private set; }
public MainViewModel()
{
ClearCommand= new ClearCommand(this);
}
class ClearCommand : ICommand
{
private MainViewModel viewModel;
public ClearCommand(MainViewModel viewModel)
{
this.viewModel = viewModel;
}
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
viewModel.vmTextBox1 = String.Empty;
MessageBox.Show("Textbox1 Cleared");
}
}