【问题标题】:WPF passing button content from button?WPF从按钮传递按钮内容?
【发布时间】:2014-03-07 07:06:44
【问题描述】:

假设我有两个按钮定义如下:

<Button Content="ButtonA" Command="{Binding [SomeTerminal].SomeCommand}"/>
<Button Content="ButtonB" Command="{Binding [SomeTerminal].SomeCommand}"/>

请问是否可以抓取按钮的内容?意思是当用户点击第一个按钮时,我可以在我的SomeCommand 方法中获得ButtonA

【问题讨论】:

  • 按钮没有名字,你想要内容吗?还有命令是什么样子的?
  • @ErnodeWeerd:感谢提醒误导信息
  • 可以使用CommandParameters,

标签: c# wpf xaml button


【解决方案1】:

在“纯”MVVM 解决方案中,您需要将数据放入 ViewModel 并将按钮的内容绑定到该数据以显示它。然后,您还可以通过 Command 参数将绑定的数据传递给命令。

<Button Content="{Binding SomeDataA}" 
        Command="{Binding [SomeTerminal].SomeCommand}" 
        CommandParameter="{Binding SomeDataA}" />
<Button Content="{Binding SomeDataB}" 
        Command="{Binding [SomeTerminal].SomeCommand}" 
        CommandParameter="{Binding SomeDataB}" />

从 View 获取 UI 数据被认为是不好的做法,因为它会在 ViewModel 中创建对 View 的依赖关系,从而使其更难测试。

【讨论】:

    【解决方案2】:

    您可以使用命令参数:

    <Button Content="ButtonA" Command="{Binding [SomeTerminal].SomeCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Content}" />
    <Button Content="ButtonB" Command="{Binding [SomeTerminal].SomeCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Content}" />
    

    【讨论】:

      【解决方案3】:

      你可以用这个,

      <Button x:Name="BtnA" Content="ButtonA" Command="{Binding [SomeTerminal].SomeCommand}" CommandParameter="{Binding ElementName=BtnA, Path=Content}" />
      

      <Button Content="ButtonA" Command="{Binding [SomeTerminal].SomeCommand}" CommandParameter="{Binding Path=Content, RelativeSource={RelativeSource Self}}" />
      

      【讨论】:

      • ButtonA 是内容,不是名字,问题也是错的。
      猜你喜欢
      • 1970-01-01
      • 2017-07-05
      • 1970-01-01
      • 2013-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多