c# - wpf 事件 setter 处理程序绑定(bind)样式

标签 c# wpf binding

我有一个样式,我想使用 RelativeSource 将命令绑定(bind)到 EventSetterHandler。命令在 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.TextBlockMouseLeftButtonDownCommandTextBlockMouseLeftButtonDownCommand 不是 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/

相关文章:

c# - 如何在代码隐藏的 ListItem 中添加元素?

c# - 创建原始图形元素(无 Windows chrome)

c# - ICollectionView获取特定对象

java - 如何从JavaFX中的二级线程获取更新消息/属性?

c# - TextBox 不遵守 Get 返回的值

c# - 异步加载 BitmapSource 图像时内存泄漏

c# - 如何使对象/层忽略附近的裁剪平面?

c# - 无法从 UWP 应用程序中看到本地主机

c# - 如何使用 "current"值绑定(bind)到 WPF 中的枚举

c - 接口(interface) Go 与 C 库