SelectedListIndex property of a databound ListBox

2019-08-01 17:00发布

问题:

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();