0

ここでは、AttachedCommandBehavior ライブラリの後にアタッチされたコマンド パターンをモデル化しています。私のボタンは次のようになります。

<Button>
    <Button.Style>
        <Style TargetType="{x:Type Button}">
            <Setter Property="vms:Attached.Behaviors">
                <Setter.Value>
                    <vms:Behaviors>
                        <vms:Behavior Event="Click" 
                                      Command="{Binding ClickCommand}" />
                    </vms:Behaviors>
                </Setter.Value>
            </Setter>
        </Style>
    </Button.Style>
</Button>

すべてがうまく機能しますが、 のセッターBehaviorが実行されると、コマンドはnull.

Behavior は でFreezable、Behaviors はFreezableCollection<Behavior>です。ボタンから DataContext を継承していないようです。

一方、これは正しく機能します。

<Button>
    <vms:Attached.Behaviors>
        <vms:Behavior Event="Click" Command="{Binding ClickCommand}" />
    </vms:Attached.Behaviors>
</Button>

ListViewItem残念ながら、を使用して生成された をターゲットにする必要があるため、この方法では実行できませんItemContainerStyle

スタイルで DataContext を取得する方法はありますか?

4

2 に答える 2

1

Attached Command Behaviorライブラリは、BlendBehaviorsになったアイデアの芽です。ブレンド動作ははるかに強力で標準化されているため、使用に切り替えることをお勧めします。ただし、アタッチされたコマンドビヘイビアーを使用している場合でもブレンドビヘイビアーを使用している場合でも、問題は本質的に同じです。スタイルを使用して設定しようとすると、期待どおりに機能しません。このStackOverflowの回答で、バインディングを完全にサポートすることで、BlendBehaviorsのこの問題を解決しました。

x:Shared="False"テストせずに、バインディングを機能させるには、ACBの動作をでマークされたリソースに移動する必要があると思います。

于 2011-02-05T23:58:17.470 に答える
0

私は同じ問題を抱えていましたが、RelativeSource を使用するとうまくいきました。前後のコードをお見せします...

前:(これはうまくいきませんでした)

<DataTemplate x:Key="MenuNodeWithChildrenTemplate">
    <StackPanel Orientation="Horizontal"
            behaviors:EventCommand.CommandToRun="{Binding OpenMenuItem}"
            behaviors:EventCommand.EventName="MouseLeftButtonUp">
        <Label Content="{Binding Title}"/>
        <Label Content="{Binding Description}"/>
    </StackPanel>
</DataTemplate>

後:(これは機能します)

<DataTemplate x:Key="MenuNodeWithChildrenTemplate">
    <StackPanel Orientation="Horizontal"
            behaviors:EventCommand.CommandToRun="{Binding Path=DataContext.OpenMenuItem, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ItemsControl}}}"
            behaviors:EventCommand.EventName="MouseLeftButtonUp">
        <Label Content="{Binding Title}"/>
        <Label Content="{Binding Description}"/>
    </StackPanel>
</DataTemplate>

明らかに、特定の状況に合わせて相対ソースのパラメーターを微調整する必要があります。なんらかの理由で、添付プロパティはデータ コンテキストを継承しないようです。

于 2012-02-20T05:11:33.923 に答える