我建议同时绑定 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");