ContentControl 内にネストされた UserControl 内に実装されたルーティング コマンドをトリガーするにはどうすればよいですか?
私が基本的に持っているのは、次を含む外部ビュー(UserControlから派生)です。
1) コマンド MyCommand をトリガーするボタン: CommandBinding が InnerView の CommandBindings コレクションに追加されるため、ContentControl 自体ではなく、ContentControl 内でホストされるビューであるため、CommandTarget は明らかに間違っています。
<Button Command="{x:Static Commands:MyCommands.MyCommand}" CommandTarget="{Binding ElementName=ViewHost}">
Trigger Command
</Button>
2) ContentControl。Content プロパティは、内側のビューで使用する必要がある ViewModel にバインドされます。
<ContentControl x:Name="ViewHost" Content="{Binding InnerViewModel}" />
3) 内部ビューのタイプを定義する DataTemplate:
<UserControl.Resources>
<ResourceDictionary>
<DataTemplate DataType="{x:Type ViewModels:InnerViewModel}">
<Views:InnerView />
</DataTemplate>
</ResourceDictionary>
</UserControl.Resources>
InnerView (UserControl から派生) は、その Loaded イベントで CommandBinding を設定します。
public partial class InnerView : UserControl
{
private void InnerViewLoaded(object sender, System.Windows.RoutedEventArgs e)
{
view.CommandBindings.Add(new CommandBinding(MyCommands.MyCommand, this.ExecuteMyCommand, this.CanExecuteMyCommand));
}
}
そしてもちろん、コマンドを定義するクラス:
internal class MyCommands
{
static MyCommands()
{
MyCommand = new RoutedCommand("MyCommand", typeof(MyCommands));
}
public static RoutedCommand MyCommand { get; private set; }
}
どうすればこれを機能させることができますか? 問題はおそらく、ボタンの CommandTarget が間違っていることです。ContentControl がホストするコントロールに CommandTarget をバインドするにはどうすればよいですか?
InnerView を OuterView に直接配置し、Button の CommandTarget を InnerView インスタンスに設定すると、次のように動作します。
<Views:InnerView x:Name="InnerViewInstance" />
<Button Command="{x:Static Commands:MyCommands.MyCommand}" CommandTarget="{Binding ElementName=InnerViewInstance}">
Trigger Command
</Button>