样式的WPF事件setter处理程序绑定
本文关键字:处理 程序 绑定 setter 事件 WPF 样式 | 更新日期: 2023-09-27 18:11:05
我有一个样式,我想用RelativeSource
绑定一个命令到EventSetter
的Handler
。命令在viewModel中。
<Style x:Key="ItemTextBlockEventSetterStyle" TargetType="{x:Type TextBlock}">
<EventSetter Event="MouseLeftButtonDown"
Handler="{Binding TextBlockMouseLeftButtonDownCommand,
RelativeSource={RelativeSource Self}}"/>
</Style>
问题是,我得到一个错误,因为这是错误的(也许这是不可能做到这一点,以这样简单的方式)
我以前在谷歌上搜索过很多次,我发现了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>
但是在这里,绑定不在样式中。我怎么能把这个EventToCommand
按钮的样式?
现在您正在将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>
另一种方法是将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)
}
}
}
当您使用MVVM时,我建议您使用Galasoft MVVM轻量级工具包EventToCommand
我对这个问题的回答没有任何外部工具包/库。但是,它不使用RelativeSource
,也不是100% MVVM。它需要在代码隐藏事件处理程序中使用一行代码。