c# – 列表视图mvvm中的WPF删除按钮

前端之家收集整理的这篇文章主要介绍了c# – 列表视图mvvm中的WPF删除按钮前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在listview中有一个按钮来删除所选项目.当我点击按钮RemoveSubjectCommand没有触发时.如果我把按钮放在列表视图之外它工作正常.这只是因为嵌套项目.我怎么解决这个问题?
<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>

解决方法

那是因为按钮的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>

猜你在找的C#相关文章