gpt4 book ai didi

c# - ListView mvvm中的WPF删除按钮

转载 作者:太空狗 更新时间:2023-10-29 20:46:45 26 4
gpt4 key购买 nike

我在 ListView 中有一个按钮,用于删除所选项目。当我单击按钮时,RemoveSubjectCommand 未触发。如果我将按钮放在 ListView 之外,它工作正常。 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>

最佳答案

那是因为按钮的DataContext是ListBoxItem DataContext。因此,您需要转到父 ListView DataContext。

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

<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# - ListView mvvm中的WPF删除按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13584643/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com