【问题标题】:Use DataContext as CommandParameter in WPF在 WPF 中使用 DataContext 作为 CommandParameter
【发布时间】:2011-01-20 03:45:43
【问题描述】:

我想将当前 DataContext(它是 ViewModel 的一个实例)作为 WPF 按钮上的 CommandParameter 传递。我应该使用什么语法?

<Button 
  x:Name="btnMain"
  Command="infra:ApplicationCommands.MyCommand"
  CommandParameter="{Binding ???}"
 />

【问题讨论】:

  • 请注意这里的顺序很重要。 CommandParameter 必须在 Command 之前,否则您只会看到 null 作为参数传递。

标签: wpf xaml binding datacontext


【解决方案1】:

一个空的Binding,没有路径,直接绑定到DataContext,所以

{Binding}

足以让它工作!你的例子:

<Button 
  x:Name="btnMain"
  Command="infra:ApplicationCommands.MyCommand"
  CommandParameter="{Binding}"
 />

【讨论】:

  • 这太简单了,太棒了。不错:)
【解决方案2】:
<Button 
   x:Name="btnMain"
   Command="infra:ApplicationCommands.MyCommand"
   CommandParameter="{Binding}" 
/>

只要按钮位于带有 DataContext 的项目的可视化树中

【讨论】:

    猜你喜欢
    • 2016-02-05
    • 2012-12-14
    • 2015-01-18
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    • 2012-04-02
    • 1970-01-01
    • 2019-06-29
    相关资源
    最近更新 更多