问题是CanExecute传递的参数第一次调用时为NULL,因此我无法运行启用/禁用命令的逻辑。但是,如果我始终启用它,然后单击按钮执行命令,CommandParameter将被正确传递。这意味着与CommandParameter的绑定正在工作。
ItemsControl和DataTemplate的XAML如下:
<ItemsControl
x:Name="commentsList"
ItemsSource="{Binding Path=SharedDataItemPM.Comments}"
Width="Auto" Height="Auto">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Button
Content="Delete"
FontSize="10"
Command="{Binding Path=DataContext.DeleteCommentCommand, ElementName=commentsList}"
CommandParameter="{Binding}" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
可以看到我有一个Comments对象列表,我想将DeleteCommentCommand的CommandParameter绑定到Command对象。
所以我的问题是:有人之前遇到过这个问题吗?CanExecute在我的Command上被调用,但是第一次参数总是为NULL - 这是为什么?
更新:我能够稍微缩小问题的范围。我添加了一个空的Debug ValueConverter,以便在数据绑定时输出消息。结果问题是在将CommandParameter绑定到按钮之前就执行了CanExecute方法。我尝试在Command之前设置CommandParameter(如建议的那样)-但仍然不起作用。有关如何控制它的任何提示。
更新2:有没有办法检测绑定何时“完成”,以便我可以强制重新评估命令?另外,是否存在多个按钮(每个项在ItemsControl中都有一个)绑定到同一个Command对象实例的问题?
更新3:我已经将演示错误上传到我的SkyDrive:http://cid-1a08c11c407c0d8e.skydrive.live.com/self.aspx/Code%20samples/CommandParameterBinding.zip