简体   繁体   English

WP7中Listpicker的选定索引

[英]Selected index of listpicker in wp7

I have silverlight listpicker control in my page and Its Binded With List<Countries> Let Say 我的页面中有silverlight listpicker控件,其与List<Countries>绑定

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 有什么办法可以从后面的代码中找到巴基斯坦的索引,并设置此列表选择器的selectedietm?

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 我建议像这样绑定ItemsSource和SelectedItem

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

In your code behind, set a viewmodel 在后面的代码中,设置一个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: 从那里您可以随时设置SelectedCountry的值,它将在选择器中设置所选项目,例如:

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

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

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

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