我遇到了WPF和命令的问题,这些问题绑定到ItemsControl的DataTemplate中的Button.这种情况很简单.ItemsControl绑定到一个对象列表,我希望能够通过单击一个Button删除列表中的每个对象.Button执行命令,Command负责删除.CommandParameter绑定到我要删除的Object.这样我知道用户点击了什么.用户应该只能删除他们的"自己的"对象 - 所以我需要在Command的"CanExecute"调用中进行一些检查,以验证用户是否具有正确的权限.
问题是传递给CanExecute的参数在第一次被调用时是NULL - 所以我无法运行逻辑来启用/禁用命令.但是,如果我启用了allways,然后单击按钮执行命令,则会正确传入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>
Run Code Online (Sandbox Code Playgroud)
所以你可以看到我有一个评论对象列表.我希望将DeleteCommentCommand的CommandParameter绑定到Command对象.
所以我想我的问题是:以前有没有人遇到过这个问题?我的命令会调用CanExecute,但第一次参数总是为NULL - 为什么会这样?
更新:我能够将问题缩小一点.我添加了一个空的Debug ValueConverter,以便在CommandParameter是数据绑定时输出消息.事实证明,在CommandParameter绑定到按钮之前执行CanExecute方法.我试图在Command之前设置CommandParameter(如建议的那样) - 但它仍然不起作用.有关如何控制它的任何提示.
Update2:有没有办法检测绑定何时"完成",以便我可以强制重新评估命令?另外 - 我有一个问题,我有多个按钮(ItemsControl中的每个项目一个)绑定到Command对象的同一个实例?
Update3:我已经将错误的副本上传到我的SkyDrive:http://cid-1a08c11c407c0d8e.skydrive.live.com/self.aspx/Code%20samples/CommandParameterBinding.zip
我有一个 DataGrid,它的每一行都包含一个删除按钮,如下所示:
<Button Command="{Binding DeleteRowCriterionCommand}">Delete</Button>
Run Code Online (Sandbox Code Playgroud)
但我不知道如何在不使用 DataGrid.Name 的情况下获取 currentItem 属性
<!-- 2ND : CRITERIA -->
<Grid>
<DataGrid ItemsSource="{Binding UserCriteria, Mode=TwoWay}" SelectedItem="{Binding SelectedItemDG, Mode=TwoWay}" AutoGenerateColumns="False">
<DataGrid.Columns>
<!--TEXTBOX FOR SQL VALUES-->
<DataGridTemplateColumn Header="SQLValue" Width="600">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<!-- BUTTON FOR DELETING -->
<DataGridTemplateColumn Width="*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Command="{Binding DeleteRowCriterionCommand}">Delete</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
Run Code Online (Sandbox Code Playgroud)
我正在使用 MVVMLight,所以我知道如何将我的命令连接到我的 ViewModel,但唯一缺少的是获取我单击按钮所在行的索引。
这是使用 DataGrid.Name 的功能:
public void DeleteRowCriterion()
{
// I would like to replace the first line by not using DataGridName …Run Code Online (Sandbox Code Playgroud)