简体   繁体   English

在wpf中的列表框中更新后,“列表框选定项”始终为null

[英]Listbox Selected Item is always null after an update in the list box in wpf

In my WPF application I have a list box which have list of quiz match am playing. 在我的WPF应用程序中,我有一个列表框,其中包含正在播放的测验比赛列表。 Each time a match is created by me / any other opponent am reloading the list. 每次我/任何其他对手创造比赛时,都会重新加载列表。

Current Scenario: Am playing a match, my current match is highlighted based on its ID. 当前场景:我正在玩比赛,我的当前比赛会根据其ID突出显示。 While playing itself some other person sends me an invite and it automatically refreshes the list and selected Item turns null. 在玩自己的游戏时,其他人向我发送了邀请,它会自动刷新列表,并且所选项目变为空。 It affects the match which am currently playing. 它会影响当前正在播放的比赛。

I need the selectedItem to be same unless the user clicks on other match. 除非用户单击其他匹配项,否则我需要selectedItem是相同的。 So I maintain the ID in the variable and even after reloading the list , with that old ID I want that item to be selected. 因此,我将ID保留在变量中,甚至在重新加载列表之后,也要使用该旧ID来选择该项目。

List<ChallengePlayerLists> ChallengerLists;
var filteredlistfortest2 = ChallengerList.Where(x => x.challengeID == Convert.ToString(challengeID) && (x.challengeStatus == "Your turn")).ToList().FirstOrDefault();
                lstChallengeGrid.SelectedItem =  ChallengerList.Where(x => x.challengeID == Convert.ToString(challengeID) && (x.challengeStatus == "Your turn")).ToList().FirstOrDefault();

public class ChallengePlayerLists
{ 
    public string challengeID { get; set; }
    public string challengeType { get; set; }
    public string challengerID { get; set; }
    public string opponentID { get; set; }
    public string fullName { get; set; }
    public string userName { get; set; }
    public string challengeStatus { get; set; }
}

First line of code works as expected, I can get the match I want to be selected using the LINQ query. 第一行代码按预期工作,我可以使用LINQ查询获得要选择的匹配项。 But while assigning it to listbox.SelectedItem it remains as NULL. 但是,在将其分配给listbox.SelectedItem它仍然为NULL。

I am not sure why it is null while assigning the same LINQ to selectedItem . 我不确定为什么将相同的LINQ分配给selectedItem时为null。

If you are changing the list bound to the ListBox then this will make the SelectedItem invalid. 如果要更改绑定到ListBox的列表,则将使SelectedItem无效。 You will need to store a way of finding the currently selected item - it's Id or a unique code and then reselect it once the list has been updated: 您将需要存储一种查找当前选定项目的方法-它是ID或唯一代码,然后在列表更新后重新选择它:

int selectedItemId = SelectedItem.Id;
ChallengerLists = updatedList;
SelectedItem = ChallengerLists.FirstOrDefault(i => i.Id == selectedItemId);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM