カスタムWPFコマンドを実装したかったのですが、次のコードを検索して見つけました。
public static class CustomCommands
{
public static readonly RoutedUICommand Exit = new RoutedUICommand
(
"Exit",
"Exit",
typeof(CustomCommands),
new InputGestureCollection()
{
new KeyGesture(Key.F4, ModifierKeys.Alt)
}
);
//Define more commands here, just like the one above
}
私が理解できないことが2つあります。
コマンドが必要static readonly
ですか?使用して宣言することはできconst
ませんか?
正確にnew InputGestureCollection() { new KeyGesture(Key.F4, ModifierKeys.Alt) }
は何ですか?デフォルトのコンストラクターを呼び出してプロパティを初期化している場合は、割り当てるプロパティがあるはずですが、割り当てるものはありません。InputGestureCollection
中かっこがありますが、中かっこ内ではプロパティを初期化していません。どうやって?このタイプのステートメントは何ですか?
いいえ、それは良い方法ではありません。
まず、MVVMを使用したWPFの基本的な理解を得る必要があります。UIにバインドするクラスがあります。そのクラスは.xaml.csではありません
ビューから完全に独立しています。クラスのインスタンスをウィンドウのDataContextに配置する必要があります。これは、.xaml.csで次のようにsthを呼び出すことで実行できます。
this.DataContext = new MyViewModel();
これで、クラスMyViewModelにはタイプICommandのプロパティが必要になります。ベストプラクティスは、ICommandを実装するクラスを作成することです。通常、これをDelegateCommandまたはRelayCommandと呼びます。例:
public class DelegateCommand : ICommand
{
private readonly Predicate<object> _canExecute;
private readonly Action<object> _execute;
public event EventHandler CanExecuteChanged;
public DelegateCommand(Action<object> execute)
: this(execute, null)
{
}
public DelegateCommand(Action<object> execute,
Predicate<object> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
if (_canExecute == null)
{
return true;
}
return _canExecute(parameter);
}
public void Execute(object parameter)
{
_execute(parameter);
}
public void RaiseCanExecuteChanged()
{
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, EventArgs.Empty);
}
}
}
次に、ViewModelで、そのクラスのインスタンスを含むプロパティを作成します。そのように:
public class MyViewModel{
public DelegateCommand AddFolderCommand { get; set; }
public MyViewModel(ExplorerViewModel explorer)
{
AddFolderCommand = new DelegateCommand(ExecuteAddFolderCommand, (x) => true);
}
public void ExecuteAddFolderCommand(object param)
{
MessageBox.Show("this will be executed on button click later");
}
}
ビューで、ボタンのコマンドをそのプロパティにバインドできるようになりました。
<Button Content="MyTestButton" Command="{Binding AddFolderCommand}" />
ルーティングされたコマンドは、デフォルトでフレームワークにすでに存在するものです(コピー、貼り付けなど)。MVVMの初心者の場合は、「通常の」コマンドの基本を理解する前に、ルーティングされたコマンドを作成することを考えるべきではありません。
最初の質問に答えるには:コマンドを静的または定数、あるいはその両方にする必要はまったくありません。(クラスMyViewModelを参照)
2番目の質問:{
-bracketsに入れたデフォルト値でリストを初期化できます。例:
var Foo = new List<string>(){ "Asdf", "Asdf2"};
プロパティを初期化するオブジェクトがありません。初期化するリストがありAdd()
、{
-bracketsに入力したパラメーターを使用してが呼び出されます。
それはあなたの場合にも基本的に起こることです。いくつかの値で初期化するコレクションがあります。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加