使用Binding将控制作为CommandParameter传递为null

时间:2015-08-12 15:04:52

标签: c# wpf mvvm command commandparameter

我已经编写了一个自定义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>

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

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

修改

绑定不会抛出任何异常。

非常感谢!

2 个答案:

答案 0 :(得分:0)

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

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处理程序将该对象传递回视图模型。

答案 1 :(得分:0)

单击按钮时,您实际上可以获取参数。