【问题标题】:Passing control as CommandParameter with Binding is null使用 Binding 作为 CommandParameter 传递控制是 null
【发布时间】:2015-11-05 06:50:36
【问题描述】:

我编写了一个自定义的ICommand 实现,它可以作为静态属性使用:

public class GridViewCommands
{
    public GridViewCommands()
    {

    }

    /// <summary>
    /// Toggle Selection-Command
    /// </summary>
    public static ICommand ToggleSelection
    {
        get
        {
            return new GridViewToggleSelectionCommand();
        }
    }
}

我尝试将此属性绑定到一个简单的Button-Command

<ui:GridViewControl x:Name="gridView" Grid.Row="1" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" />

<Button HorizontalAlignment="Left" Width="100" Margin="220,0,0,0" Content="Toggle" x:Name="toggleButton" Command="{x:Static  ui:GridViewCommands.ToggleSelection}" CommandParameter="{Binding ElementName=gridView}"></Button>

但是如果我启动我的应用程序,GridViewToggleSelectionCommand 中的CanExecute 方法中的parameter-Parameter 始终为空。我的目标是将GridViewControl 的实例作为命令参数传递。

我在这里做错了什么:ui:GridViewCommands.ToggleSelection}" CommandParameter="{Binding ElementName=gridView"}

编辑

绑定不会抛出任何异常。

非常感谢!

【问题讨论】:

  • 您检查绑定是否有错误?如果没有尝试使用 Snoop 这样做。顺便说一句,很棒的应用程序。
  • 如果我打开异常抛出或使用这个:stackoverflow.com/a/4226038/2630261 我没有得到任何异常。

标签: c# wpf mvvm command commandparameter


【解决方案1】:

我认为您正在尝试这样做:

public static ICommand ToggleSelection { get { return new RelayCommand<GridViewControl>(GridViewToggleSelectionCommand); } }
private static void GridViewToggleSelectionCommand(GridViewControl theControl)
{
    // do something with the control here
}

我看到您已将其标记为 mvvm...这不是 mvvm。您的视图模型不应该对视图一无所知。我也无法理解为什么您将 ToggleSelection 设置为静态,这意味着您的命令处理程序也必须是静态的。

老实说,如果你继续走你正在走的路,你就是在为一个痛苦的世界做好准备。您的 GridViewControl 应该绑定到您的视图模型中的一个对象,并且您应该通过您的 ICommand 处理程序将这个对象传递回视图模型。

【讨论】:

  • 我尝试使用与 Telerik 相同的命令模式。我的网格视图有一个EcecuteCommand 方法,它将我的命令作为参数。所以静态的东西只是为了方便使用。
【解决方案2】:

其实点击按钮就可以得到参数。

【讨论】:

  • 不,按钮不可点击
  • 为什么?因为你把返回参数!= null;在 CanExecute 中?
  • 好吧对不起,我之前试过`return true,但是如果我点击按钮,Execute中的参数为空。
  • 也许你可以先试试 Grid 而不是 ui:GridViewControl 看看它是否工作。
猜你喜欢
  • 1970-01-01
  • 2016-04-10
  • 2014-04-22
  • 1970-01-01
  • 1970-01-01
  • 2012-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多