我如何触发路由命令实现在一个UserControl是嵌套在一个ContentControl?
我基本上有一个外部视图(从UserControl派生),它包含:
1)触发命令MyCommand的按钮:CommandTarget在这里显然是错误的,因为它应该是在ContentControl中托管的视图,而不是内容控件本身,因为CommandBinding被添加到InnerView的CommandBinding集合中。
<Button Command="{x:Static Commands:MyCommands.MyCommand}" CommandTarget="{Binding ElementName=ViewHost}">
Trigger Command
</Button>
2) A内容控制。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是错误的。如何将CommandTarget绑定到由ContentControl承载的控件?
如果我把InnerView直接放到OuterView,并设置按钮的CommandTarget到InnerView实例,它工作:
<Views:InnerView x:Name="InnerViewInstance" />
<Button Command="{x:Static Commands:MyCommands.MyCommand}" CommandTarget="{Binding ElementName=InnerViewInstance}">
Trigger Command
</Button>
试试这个
<UserControl.Resources>
<ResourceDictionary>
<Views:InnerView x:Key="innerView"/>
<DataTemplate DataType="{x:Type ViewModels:InnerViewModel}">
<ContentControl Content="{StaticResource innerView}" />
</DataTemplate>
</ResourceDictionary>
<Button Command="{x:Static Commands:MyCommands.MyCommand}" CommandTarget="{StaticResource innerView}">
Trigger Command
</Button>
我还没有测试过,但希望这能帮助你。虽然这似乎是一个非常复杂的问题。
我遇到了这个问题,并了解到我必须为用户控件层次结构中的每个用户控件注册一个命令类型依赖属性。