列表框.selecteindex = -1不会取消选中项的设置
本文关键字:设置 取消 selecteindex 列表 | 更新日期: 2023-09-27 18:03:02
我有一个在XAML中定义的列表框如下:
<ListBox x:Name="listLeagues" DisplayMemberPath="LeagueName"
SelectionChanged="listLeagues_SelectionChanged"
SelectedItem="{Binding SelectedObject, Mode=TwoWay}"
SelectionMode="Single"
BorderBrush="{StaticResource noBrush}" Background="{StaticResource noBrush}"
ScrollViewer.HorizontalScrollBarVisibility="Disabled">
</ListBox>
在代码中,我设置DataContext如下:listLeagues.ItemsSource = Leagues;
,其中'Leagues'是一个自定义集合。我试图用以下代码更改代码中选定的项目:
private void addButton_Click(object sender, MouseButtonEventArgs e)
{
FantasyLeague addedLeague = new FantasyLeague();
Random rnd = new Random();
addedLeague.LeagueName = "New Leauge " + rnd.Next(100).ToString();
Leagues.Add(addedLeague);
listLeagues.SelectedIndex = -1;
listLeagues.SelectedItem = addedLeague;
LeagueDetailsClickHelper();
}
我的列表框有SelectionMode = Single。行listLeagues.SelectedIndex = -1;
没有影响,当将SelectedItem更改为新值时,即使模式是单一的,它也将两个项目都作为SelectedItems。有人能解释一下哪里出了问题吗?
我已经从XAML中删除了SelectedItem="{Binding SelectedObject, Mode=TwoWay}"
,发现事情正常工作[大多数时候]。我正在更新ListBox的底层源,当改变影响==运算符评估的值与原始值不同时,我注意到SelectionChanged事件不包括RemovedItems中的任何内容。我将尝试对对象进行深度拷贝并更改深度拷贝,看看是否能解决问题。
我做了一个深拷贝的幻想联盟是在联赛收集。我将fantasy league的成员绑定到一个可以更改的表单中。当我对这个表单的源进行深度复制时,允许更改联赛集合而不是原始的,没有任何问题。我不确定为什么更改与==和. equals的评估相关联的值会导致这种行为,而不仅仅是正确更新目标/源,但是,我已经解决了这个问题。如果有人能告诉我是什么导致了这种行为,我将不胜感激。谢谢大家的建议。
listLeagues.SelectedIndex = -1;
listLeagues.SelectedItem = addedLeague;
**listLeagues.UpdateLayOut();**
好吧,第一件事是你应该使用ObservableCollection
绑定。
第二,您将实际的UI SelectedIndex
设置为-1(这完全违背了绑定的目的)。需要设置DataSource
的索引。
尝试一下,并可能发布您的代码的其余部分。
我意识到这是旧的,但由于它显示在我的搜索高我想更新的答案。我认为你应该使用。clearselected()方法,MSDN信息。这应该清除列表框c#或VBA (.net)中的任何选择。
欢呼,