WPF通过按钮传递按钮内容吗? [英] WPF passing button content from button?
问题描述
假设我有两个定义如下的按钮:
Let's say I have two button defined as below:
<Button Content="ButtonA" Command="{Binding [SomeTerminal].SomeCommand}"/>
<Button Content="ButtonB" Command="{Binding [SomeTerminal].SomeCommand}"/>
我是否可以获取按钮的内容?意思是当用户单击第一个按钮时,我可以在我的 SomeCommand
方法中获得 ButtonA
吗?
May I know if it's possible to grab the content of the button? Meaning when user click the first button, I can get ButtonA
in my SomeCommand
method?
推荐答案
在纯 MVVM解决方案中,您需要将数据放入ViewModel中,并将按钮的内容绑定到该数据以显示它。然后,您还可以通过Command参数将绑定的数据传递给命令。
In a 'pure' MVVM solution you would need to put data in the ViewModel and bind the contents of the buttons to this data to display it. You could then also pass the bound data to the command through a Command parameter.
<Button Content="{Binding SomeDataA}"
Command="{Binding [SomeTerminal].SomeCommand}"
CommandParameter="{Binding SomeDataA}" />
<Button Content="{Binding SomeDataB}"
Command="{Binding [SomeTerminal].SomeCommand}"
CommandParameter="{Binding SomeDataB}" />
从视图获取UI数据被认为是不好的做法,因为它在视图上的ViewModel中创建了依赖项使得测试变得更加困难。
Getting UI data from a View is considered bad practice because it creates a dependency in the ViewModel on the View making it harder to test.
这篇关于WPF通过按钮传递按钮内容吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!