SelectedListIndex property of a databound ListBox

2019-08-01 16:15发布

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?

2条回答
一夜七次
2楼-- · 2019-08-01 16:57

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

查看更多
趁早两清
3楼-- · 2019-08-01 17:06

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();
查看更多
登录 后发表回答