スタイルがあり、を使用して のEventSetter
にコマンドをバインドしたいと考えています。 コマンドは viewModel にあります。Handler
RelativeSource
<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.TextBlockMouseLeftButtonDownCommand
。TextBlockMouseLeftButtonDownCommand
は 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)
}
}
}