本文介绍了您如何知道 ItemsControl 的哪个元素在 MVVM 中发送事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我目前有一个 ItemsControl,它的 DataTemplate 是一堆按钮.我正在连接这些按钮的点击事件,但我怎么知道点击了哪个按钮?我不应该使用 ItemsControl 吗?

Let's say I currently have an ItemsControl whose DataTemplate is a bunch of buttons. I'm wiring up these buttons' click events, but how am I to know which button was clicked? Should I not use a ItemsControl?

我试图没有代码隐藏,但务实可能是必要的.

I'm trying to have no code-behind, but being pragmatic may be necessary.

<ItemsControl>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button Margin="10">
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="Click">
                        <GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding ItemsControlButtonClicked, Mode=OneWay}"/>
                    </i:EventTrigger>
                </i:Interaction.Triggers>
            </Button>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

推荐答案

如果你想知道什么Item被点击了,那么把{Binding }作为>CommandParameter 并将选定的对象传递给您的命令

If you want to know what Item was clicked, then pass {Binding } as the CommandParameter and it will pass the selected object to your Command

如果您想知道点击了什么 Button,我会在代码隐藏中这样做,因为 ViewModel 不需要了解任何关于 UI 的信息,包括按钮.

If you want to know what Button was clicked, I would do that in the code-behind since ViewModels do not need to know anything about the UI, and that includes buttons.

此外,由于您的控件是一个按钮,您应该使用 Command 属性而不是 Click 触发器.

Also since your control is a Button, you should use the Command property instead of a Click trigger.

<Button Command="{Binding ItemsControlButtonClicked}" />

这篇关于您如何知道 ItemsControl 的哪个元素在 MVVM 中发送事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 20:00