如何触发嵌套在 ContentControl 内的 UserControl 内实现的路由命令?
我基本上拥有的是一个外部视图(源自 UserControl),其中包含:
1) 应该触发命令 MyCommand 的按钮:CommandTarget 在这里显然是错误的,因为它应该是托管在 ContentControl 内的视图,而不是内容控件本身,因为 CommandBinding 已添加到 InnerView 的 CommandBindings 集合中。
<Button Command="{x:Static Commands:MyCommands.MyCommand}" CommandTarget="{Binding ElementName=ViewHost}">
Trigger Command
</Button>
2) 内容控件。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; }
}
我怎样才能得到这个工作?问题可能是 Button 上的 CommandTarget 错误。如何将 CommandTarget 绑定到 ContentControl 托管的控件?
如果我将 InnerView 直接放入 OuterView 并将 Button 的 CommandTarget 设置为 InnerView 实例,它可以工作:
<Views:InnerView x:Name="InnerViewInstance" />
<Button Command="{x:Static Commands:MyCommands.MyCommand}" CommandTarget="{Binding ElementName=InnerViewInstance}">
Trigger Command
</Button>