在WP7

2012-06-05 37 views
1

listpicker選指數我有我的網頁的Silverlight listpicker控制及其綁定隨着List<Countries>讓說在WP7

美國

英國

巴基斯坦

丹麥

我綁定這個清單與我的listpickercountries我想默認選定的值將是巴基斯坦

我可以設置所選的項目,這樣

listpickercountries.selectedindex = 2; 

有什麼辦法,我可以找到巴基斯坦從代碼的指數後面,設置此listpicker這selectedietm喜歡這個方式

listpickercountries.selectedindex.Contain("Pakistan"); 

或類似的東西 ???

回答

0

您必須搜索所需國家/地區的列表,檢查它是哪個索引,然後在選取器上設置選定的索引。

索引將是相同的。

0

我假定你的國家類的,

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

然後你就可以做,

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

我會建議結合兩者的ItemsSource和的SelectedItem這樣

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

在你的代碼背後,設置一個視圖模型

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

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

並在視圖模型

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"); 
     } 
    } 

} 

從那裏,你可以在任何時候設置的SELECTEDCOUNTRY的價值,它會拾取器 如內設置所選項目:

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

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