私は最もクリーンな方法は、親が設定するUserControlこのようにそれを行うことにより
public partial class PlayingGameScreen : UserControl
{
public ICommand Command { get; set; }
public void SomeMethod()
{
this.Command?.Execute(null);
}
}
//parent code, define the command with the logic to run
var command = new DelegateCommand(...);
var control = new Views.PlayingGameScreen
{
Command = command
};
this.ContentControl.Content = control;
は、親がコマンドを設定し、ユーザーコントロールをホストしている親であるとUserContolが使用するグローバルなクラスが存在しないかを知る必要はありません。これは完全に分離されたソリューションです。
ボーナスでは、コマンドをDependencyPropertyとして設定し、xamlでも割り当てることができます。コマンドをViewModelにバインドすると、ViewModelがページのViewModelになります。
<uc:PlayingGameScreen Command="{x:Bind SomeCommand}"/>
私はたくさんの方法を試しましたが、これは私のお気に入りです。
コンテンツコントロールのコンテンツプロパティをViews.PlayingGameScreenにキャストし、キャストされたオブジェクトのメソッドを呼び出すことができます –