7

我在列表视图中有一个按钮来删除选定的项目。当我单击按钮时,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>
4

3 回答 3

14

那是因为按钮的DataContext是ListBoxItem DataContext。所以你需要去父ListView DataContext。

一种方法是给 ListView 一个名称,并与元素名称绑定

<ListView Name="lv" 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 ElementName=lv,Path=DataContext.RemoveSubjectCommand}"  />
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
        </GridView>
    </ListView.View>
</ListView>

于 2012-11-27T12:57:43.657 回答
8

您需要将 Command 绑定到使用FindAncestor。否则,它将尝试RemoveSubjectCommand使用ListViewItem的数据上下文绑定到 a,而不是 ViewModel 的。

试试这个:

<Button Content="X" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListView}, Path=DataContext.RemoveSubjectCommand}"  />
于 2012-11-27T12:54:17.457 回答
2

如果我将按钮放在列表视图之外,它工作正常

因为RemoveSubjectCommand属性是在 的数据上下文中定义的ListView,而不是在item的数据上下文中。

于 2012-11-27T12:56:53.407 回答