SelectedListIndex property of a databound ListBox cannot be set, why?

限于喜欢 提交于 2019-12-11 09:55:18

问题


I avoided to ask this question, but the ListBox's selected index can no be set. I have read the other threads and applied the settings, but it doesn't work.

            <ListBox  ItemsSource="{Binding}" 
                      HorizontalAlignment="Right" 
                      Name="lstReading" Height="Auto" 
                      SelectedIndex="{Binding BookmarkSelectedIndex}">

In the something.xaml.cs, I am settings

            lstReading.DataContext = IQText;

Where, IQText is an IEnumerable<dictIQ> and includes the BookmarkSelectedIndex as data element. Other data elements from IQText can be used but the listindex can't be set. Could someone please let me know why?


回答1:


Are you have BookmarkSelectedIndex inside of dictIQ class? So, you have one BookmarkSelectedIndex per item, not per collection!

You can create separate property BookmarkSelectedIndex outside of dictIQ or create class that inherited from ObservalbeCollection<dictIQ> and have additional property BookmarkSelectedIndex:

public class CollectionWithIndex: ObservalbeCollection<dictIQ>
{
    public int BookmarkSelectedIndex { get; set; }
}

I hope you choose best solution suitable for you




回答2:


use this code for select item at runtime...

List<Audio> lst = Audio.GetAudioFiles();
            Audio aufile = new Audio { FileDisplayName = "Select Audio File" };
            lst.Insert(0, aufile);
            lstPickAudio.ItemsSource = lst;
           string FileDisplayName="your condition"
            lstPickAudio.SelectedItem = lst.Where(p => p.FileName == FileDisplayName).First();


来源:https://stackoverflow.com/questions/10094524/selectedlistindex-property-of-a-databound-listbox-cannot-be-set-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!