我有一个样式,我想使用 RelativeSource
将命令绑定(bind)到 EventSetter
的 Handler
。命令在 viewModel 中。
<Style x:Key="ItemTextBlockEventSetterStyle" TargetType="{x:Type TextBlock}">
<EventSetter Event="MouseLeftButtonDown"
Handler="{Binding TextBlockMouseLeftButtonDownCommand,
RelativeSource={RelativeSource Self}}"/>
</Style>
问题是我得到一个错误,因为这有问题(也许不可能以这种简单的方式做到这一点)
我之前用 google 搜索了很多,我找到了 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>
但在这里,绑定(bind)不在样式中。如何将此 EventToCommand
设置为按钮的样式?
最佳答案
现在您正在将 MouseLeftButtonDown
事件绑定(bind)到 TextBlock.TextBlockMouseLeftButtonDownCommand
。 TextBlockMouseLeftButtonDownCommand
不是 TextBlock 的有效属性,也不像事件处理程序。
我使用 AttachedCommandBehavior始终采用将命令连接到事件的样式。语法通常如下所示(注意命令绑定(bind)中的 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)
}
}
}
关于c# - wpf 事件 setter 处理程序绑定(bind)样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7755003/