我有一个风格,我希望将命令绑定到EventSetter的Handler用RelativeSource.该命令位于viewModel中.
<Style x:Key="ItemTextBlockEventSetterStyle" TargetType="{x:Type TextBlock}">
<EventSetter Event="MouseLeftButtonDown"
Handler="{Binding TextBlockMouseLeftButtonDownCommand,
RelativeSource={RelativeSource Self}}"/>
</Style>
Run Code Online (Sandbox Code Playgroud)
问题是我得到一个错误,因为这有什么问题(也许不可能以这么简单的方式做到这一点)
我之前搜索了很多,我发现了AttachedCommandBehaviour,但我认为它不适用于风格.
你能给出一些如何解决这个问题的提示吗?
更新13/10/2011
我在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>
Run Code Online (Sandbox Code Playgroud)
但在这里,绑定不是风格.我怎么能把它放到EventToCommand按钮的样式?
Rac*_*hel 25
现在你将MouseLeftButtonDown事件绑定到TextBlock.TextBlockMouseLeftButtonDownCommand.TextBlockMouseLeftButtonDownCommand不是TextBlock的有效属性,也不是它的事件处理程序.
我一直在样式中使用AttachedCommandBehavior将命令连接到事件.语法通常如下所示(注意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>
Run Code Online (Sandbox Code Playgroud)
另一种方法是将EventSetter挂钩到代码隐藏中的事件,并从那里处理命令:
<Style x:Key="ItemTextBlockEventSetterStyle" TargetType="{x:Type TextBlock}">
<EventSetter Event="MouseLeftButtonDown"
Handler="TextBlockMouseLeftButtonDown"/>
</Style>
Run Code Online (Sandbox Code Playgroud)
代码中的事件处理程序...
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)
}
}
}
Run Code Online (Sandbox Code Playgroud)