【发布时间】:2012-11-27 12:50:57
【问题描述】:
我在列表视图中有一个用于删除所选项目的按钮。当我单击按钮时,RemoveSubjectCommand 没有触发。如果我将按钮放在列表视图之外,它工作正常。 hopw 这只是因为嵌套项目。我该如何解决这个问题?
<ListView HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
HorizontalContentAlignment="Stretch" Grid.ColumnSpan="3" Grid.Row="2"
ItemsSource="{Binding AssignedSubjects}">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Center" />
</Style>
</ListView.ItemContainerStyle>
<ListView.View>
<GridView>
<GridViewColumn Width="140" Header="Subjects" DisplayMemberBinding="{Binding Name}" />
<GridViewColumn Width="auto">
<GridViewColumn.CellTemplate>
<DataTemplate>
<Button Content="X" Command="{Binding RemoveSubjectCommand}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
查看模型,
private ICommand removeSubjectCommand;
**
public ICommand RemoveSubjectCommand
{
get { return removeSubjectCommand ?? (removeSubjectCommand = new RelayCommand(param => this.RemoveSubject(), null)); }
}
**
private void RemoveSubject()
{ ***
}
如果我输入以下代码,它将正常工作。
<ListView.InputBindings>
<KeyBinding Key="Delete" Command="{Binding RemoveSubjectCommand}" />
</ListView.InputBindings>
【问题讨论】:
-
嗨。如果没有将参数发送到命令,如何删除该行?
-
@Javidan,为此您可以使用按钮
CommandParameter。例如。使用CommandParameter="{Binding}"将其绑定到您的ListViewItem 的DataContext,即项目本身。然后,在您的 ViewModel 中,您可以定义DelegateCommand以接受参数,例如如public DelegateCommand<object> RemoveSubjectCommand{ get; }(注意我添加的<object>,顺便说一下,它可以是任何其他类型,只要一切保持一致)。