gpt4 book ai didi

c# - 有项目时,SelectionChanged 中的 Items.Count = 0

转载 作者:行者123 更新时间:2023-12-03 11:02:50 26 4
gpt4 key购买 nike

我想在按钮单击时显示一些自定义内容(使用数据模板):

<ContentControl x:Name="content" />
<Button Content="Test" Click="button_Click" />

按钮显示/隐藏这样的内容
VM _vm = new VM();
void button_Click(object sender, RoutedEventArgs e) =>
content.Content = content.Content == null ? _vm : null;

这是数据模板:
<DataTemplate DataType="{x:Type local:VM}">
<ListBox ItemsSource="{Binding Items}" SelectionChanged="listBox_SelectionChanged">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="IsSelected" Value="{Binding IsSelected}" />
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
</DataTemplate>

事件处理程序:
void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e) =>
Title = "Items: " + ((ListBox)sender).Items.Count;

View 模型:
public class VM
{
public List<Item> Items { get; } = new List<Item> { new Item(), new Item(), new Item() };
}
public class Item
{
public bool IsSelected { get; set; }
}

问题 : 当数据模板被卸载时, SelectionChanged对于 ListBox事件在没有项目的情况下上升。

我不想要这个事件。选择某些内容并卸载数据模板后,我不想看到“项目:0”。



问题 : 发生了什么,我该如何防止这种情况发生?

注意:这是非常简短和简化的 MCVE,即并非一切都很漂亮,尽管有关键点:带有 ListBox 的数据模板里面,它使用 IsSelected绑定(bind),我需要摆脱它 SelectionChanged卸货时的事件。

调用堆栈:

最佳答案

这完全按照设计工作。您通过单击列表框中的项目进行了选择。卸载模板时,ItemsSource绑定(bind)断开,项目源为空。此时,当前选择不再有效(项目源中不存在该项目),因此选择被清除。这是一个选择变化:选择从有到无。预计该事件将在这种情况下引发。

很少需要订阅 SelectionChanged .通常最好绑定(bind) SelectedItem到您的 View 模型上的属性。 Whenever the selection changes, that property will be updated.而不是响应SelectionChanged事件,您可以响应该属性的更改。

这种方法很好地避免了您看到的问题。卸载模板后,SelectedItem绑定(bind)将被断开,因此您的 View 模型将不再更新。因此,在清除选择时,您不会看到最终更改。

多项选择的替代解决方案

如果您的 ListBox支持多选,可以继续订阅SelectionChanged .但是,不要查询 listBoxItems ;相反,扫描 _vm.Items并查看哪些项目有 IsSelected设置为 true .这应该告诉您实际的选择,并且结果不应受到正在卸载的模板的影响。

您还可以通过检查 (sender as ListBox)?.ItemsSource 是否已卸载该模板。在您的处理程序中为空。但是,这应该不是必需的。

关于c# - 有项目时,SelectionChanged 中的 Items.Count = 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48405800/

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