如何在 DataTemplate Button 中同时使用 Command 和 EventTrigger? [英] How to use both Command and EventTrigger in DataTemplate Button?

查看:28
本文介绍了如何在 DataTemplate Button 中同时使用 Command 和 EventTrigger?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 DataTemplate 中有一个按钮,它绑定到我的 ViewModel 中的命令.该按钮还有一个 EventTrigger,它启动一个隐藏编辑控件(按钮是其中一部分)的 Storyboard.

I have a Button in a DataTemplate that is bound to a Command in my ViewModel. The button also has an EventTrigger that kicks off a Storyboard that hides the edit controls (of which the button is a part.)

如果我选择 PreviewMouseDown 事件,情节提要可以正常工作,但命令永远不会被调用.如果我在 EventTrigger 中选择 MouseDown 事件,则命令有效,但情节提要不执行.

The Storyboard works fine if I pick up the PreviewMouseDown event, but the Command never gets called. If I pick up the MouseDown event in my EventTrigger, the Command works, but the Storyboard doesn't execute.

如何在单击按钮时同时执行命令和情节提要?

<Button Content="Save" Command="{Binding SaveCommand}" >
    <Button.Triggers>
        <EventTrigger RoutedEvent="Button.PreviewMouseDown">
            <EventTrigger.Actions>
                <BeginStoryboard Storyboard="{DynamicResource sbCloseTitleEdit}"/>
            </EventTrigger.Actions>
        </EventTrigger>
    </Button.Triggers>
</Button>

推荐答案

我最终通过为包含 DataTemplate 的 ResourceDictionary 添加一个代码隐藏文件来解决我的问题.我不知道这是可能的,但找到了这个解释:

I ended up inelegantly solving my problem by adding a code-behind file for my ResourceDictionary that contains the DataTemplate. I wasn't aware that this was possible, but found this explanation:

是否可以在 WPF 中的资源字典后面设置代码以进行事件处理?

我没有使用 EventTrigger 来开始隐藏编辑控件的 Storyboard,而是在代码隐藏中添加了 Click 处理程序.这有点笨拙,因为我必须相对于单击的按钮来定位面板,因为这是唯一可用的参考,但它可以工作.

Instead of using the EventTrigger to begin a Storyboard that hides the edit controls I added a Click handler to the code-behind. It's a bit kludgy as I have to locate the panels relative to the button clicked as that is the only reference available, but it works.

如果有人有的话,仍在寻找更好的解决方案.

Still looking for a better solution if anyone has one.

这篇关于如何在 DataTemplate Button 中同时使用 Command 和 EventTrigger?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆