wpf イベントセッター ハンドラーのスタイルでのバインディング 質問する

wpf イベントセッター ハンドラーのスタイルでのバインディング 質問する

スタイルがあり、を使用して のEventSetterにコマンドをバインドしたいと考えています。 コマンドは viewModel にあります。HandlerRelativeSource

<Style x:Key="ItemTextBlockEventSetterStyle" TargetType="{x:Type TextBlock}">
    <EventSetter Event="MouseLeftButtonDown" 
                 Handler="{Binding TextBlockMouseLeftButtonDownCommand, 
                           RelativeSource={RelativeSource Self}}"/>
</Style>

問題は、何かが間違っているためにエラーが発生することです(おそらく、これほど簡単な方法でこれを行うことはできないでしょう)

これまで何度もグーグル検索して、 を見つけたのですAttachedCommandBehaviourが、スタイルが合わない気がします。

この問題を解決する方法についてヒントを教えていただけますか?

2011年10月13日更新

MVVM Light Toolkit のEventToCommandサンプル プログラムで次のものを見つけました:

        <Button Background="{Binding Brushes.Brush1}"
            Margin="10"
            Style="{StaticResource ButtonStyle}"
            Content="Simple Command"
            Grid.Row="1"
            ToolTipService.ToolTip="Click to activate command">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="Click">
                <cmd:EventToCommand Command="{Binding SimpleCommand}" />
            </i:EventTrigger>
            <i:EventTrigger EventName="MouseLeave">
                <cmd:EventToCommand Command="{Binding ResetCommand}" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </Button>

しかし、ここではバインディングがスタイルにありません。これをEventToCommandボタンのスタイルにするにはどうすればよいでしょうか?

ベストアンサー1

現在、MouseLeftButtonDownイベントを にバインドしていますTextBlock.TextBlockMouseLeftButtonDownCommandTextBlockMouseLeftButtonDownCommandは TextBlock の有効なプロパティではなく、イベント ハンドラーでもないようです。

私は添付コマンドの動作コマンドをイベントに接続するためのスタイルでは常に使用されます。構文は通常次のようになります (DataContextコマンド バインディングの に注意してください)。

<Style x:Key="ItemTextBlockEventSetterStyle" TargetType="{x:Type TextBlock}">
    <Setter Property="local:CommandBehavior.Event" Value="MouseLeftButtonDown" />
    <Setter Property="local:CommandBehavior.Command"
            Value="{Binding DataContext.TextBlockMouseLeftButtonDownCommand, 
                            RelativeSource={RelativeSource Self}}" />
</Style>

別の方法としては、コード ビハインド内のイベントに EventSetter をフックし、そこからコマンドを処理する方法があります。

<Style x:Key="ItemTextBlockEventSetterStyle" TargetType="{x:Type TextBlock}">
    <EventSetter Event="MouseLeftButtonDown" 
                 Handler="TextBlockMouseLeftButtonDown"/>
</Style>

コード ビハインド内のイベント ハンドラー...

void TextBlockMouseLeftButtonDown(object sender, MouseEventArgs e)
{
    var tb = sender as TextBlock;
    if (tb != null)
    {
        MyViewModel vm = tb.DataContext as MyViewModel;

        if (vm != null && TextBlockMouseLeftButtonDownCommand != null
            && TextBlockMouseLeftButtonDownCommand.CanExecute(null))
        {
            vm.TextBlockMouseLeftButtonDownCommand.Execute(null)
        }
    }
}

おすすめ記事