对于我的Xamarin Forms应用程序,我正在使用选择器来选择测验类别的子类别。
<Picker x:Name="subCategory" Title="SUBCategory" ItemsSource="{Binding SubCategories}" ItemDisplayBinding="{Binding Subcategory}" SelectedItem="{Binding selSubCategories, Mode=TwoWay}" />
默认情况下,选择器的文本标题为SUBCategory,但我想将其更改为我从api调用中获得的一项。
首先,我从视图中加载了ItemSource,并尝试设置了SelectedItem,但没有成功。
然后,根据不同的网站,将其更改为ViewModel以加载数据并设置所选项目。已从ViewModel正确加载了项目,但是SelectedItem仍然没有成功。我也尝试过用不起作用的SelectedIndex,但是我更喜欢SelectedItem,因为这是我从字面上得到的值。
public class QuizPageViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
CheetahApi api = new CheetahApi();
public QuizPageViewModel()
{
GetSubCategories();
}
SubCategory countries =
new SubCategory() { Subcategory="Olympische Spelen"}
;
public SubCategory selSubCategories;
private ObservableCollection<SubCategory> _subCategories = new ObservableCollection<SubCategory>();
public ObservableCollection<SubCategory> SubCategories
{
get { return _subCategories; }
set
{
_subCategories = value;
OnPropertyChanged(nameof(SubCategories));
}
}
private async void GetSubCategories()
{
var subCat = await api.GetSubCategories("sport");
foreach (var sub in subCat)
{
SubCategories.Add(sub);
}
selSubCategories = subCat.FirstOrDefault(a => a.Subcategory == "Olympische Spelen");
}
protected virtual void OnPropertyChanged(string propertyName)
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
型号
public class SubCategory
{
public int Id { get; set; }
public string Category { get; set; }
public string Subcategory { get; set; }
}
有人知道如何将选择器的默认文本设置为“源”中的一项吗?
答案 0 :(得分:2)
您需要为SelectedItem字段实现OnPropertyChanged,例如:
private SubCategory _selSubCategories;
public SubCategory selSubCategories
{
get { return _selSubCategories; }
set
{
_selSubCategories = value;
OnPropertyChanged(nameof(selSubCategories));
}
}