4

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>
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 に答える