简体   繁体   中英

Selected index of listpicker in wp7

I have silverlight listpicker control in my page and Its Binded With List<Countries> Let Say

United States

United Kingdom

Pakistan

Denmark

I Bind This list with my listpickercountries I want that default selected value will be Pakistan

I can set selected item In this way

listpickercountries.selectedindex = 2;

is there any way I can find the index of Pakistan From code behind and set this selectedietm of this listpicker Like This Way

listpickercountries.selectedindex.Contain("Pakistan"); 

Or Something like that ???

You will have to search List for the country you want, check which index it is and then set the selected index on the picker itself.

Indexes will be the same.

I assumed your Countries class as,

public class Countries
    {
        public string name { get; set; }
    }

And then you can do,

listpickercountries.ItemsSource = countriesList;
listpickercountries.SelectedIndex = countriesList.IndexOf( countriesList.Where(country => country.name == "Pakistan").First());

I would recommend binding both the ItemsSource AND the SelectedItem as such

<toolkit:ListPicker x:Name="listpickercountries" 
                ItemsSource="{Binding Countries}"
                SelectedItem="{Binding SelectedCountry, Mode=TwoWay}">

In your code behind, set a viewmodel

public SettingsPage()
{
    ViewModel = new ViewModel();
    InitializeComponent();
}

private ViewModel ViewModel
{
    get { return DataContext as ViewModel; }
    set { DataContext = value; }
}

And in the viewmodel

public class ViewModel : INotifyPropertyChanged
{
    public IList<Country> Countries
    {
        get { return _countries; }
        private set
        {
            _countries = value;
            OnPropertyChanged("Countries");
        }
    }

    public Country SelectedCountry
    {
        get { return _selectedCountry; }
        private set
        {
            _selectedCountry= value;
            OnPropertyChanged("SelectedCountry");
        }
    }

}

From there you can set the value of the SelectedCountry at any time and it will set the selected item within the picker eg:

// from code behind
ViewModel.SelectedCountry = ViewModel.Countries.FirstOrDefault(c => c.Name == "Pakistan");

// From ViewModel
this.SelectedCountry = this.Countries.FirstOrDefault(c => c.Name == "Pakistan");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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