4

如何触发嵌套在 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>
4

2 回答 2

1

尝试这个

<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>

我还没有测试过,但希望这会对你有所帮助。虽然这似乎是一个非常复杂的问题。

于 2014-08-23T18:12:28.073 回答
0

我遇到了这个问题并了解到我必须为我的用户控件层次结构中的每个用户控件注册一个命令类型依赖属性。

我在本网站上的另一个链接中了解到这一点。

于 2014-11-14T14:51:30.027 回答