https://blog.xamarin.com/new-bindable-picker-control-for-xamarin-forms/
我是xamarin和c#的新手 不知怎的,它对我不起作用......
public class RegistrationPageViewModel : INotifyPropertyChanged
{
List<string> _countries = new List<string>
{
"Afghanistan",
"Albania",
"Algeria",
"Andorra",
"Angola",
};
public List<string> Countries => _countries;
public event PropertyChangedEventHandler PropertyChanged;
}
public partial class RegistrationPage : ContentPage
{
RegistrationPageViewModel vm;
public RegistrationPage()
{
InitializeComponent();
this.BindingContext = vm = new RegistrationPageViewModel();
}
private void InitializeComponent()
{
throw new NotImplementedException();
}
}
int countriesSelectedIndex;
public int CountriesSelectedIndex
{
get
{
return countriesSelectedIndex;
}
set
{
if (countriesSelectedIndex != value)
{
countriesSelectedIndex = value;
// trigger some action to take such as updating other labels or fields
OnPropertyChanged(nameof(CountriesSelectedIndex));
SelectedCountry = Countries[countriesSelectedIndex];
}
}
}
public string SelectedCountry { get; private set; }
}
我收到错误:当前上下文中不存在“国家/地区”这个名称
我做错了什么?是否有人有一个有效的例子
答案 0 :(得分:0)
以下是我写它的方法(使用Fody而不是打扰INotifyPropertyChanged
):
public class Country
{
public string Name { get; }
public Country(string name) => Name = name;
public static Country Afghanistan = new Country("Afghanistan");
public static Country Albania = new Country("Albania");
public static Country Algeria = new Country("Algeria");
public static Country Andorra = new Country("Andorra");
public static Country Angola = new Country("Angola");
public static IList<Country> Countries = new List<Country> { Afghanistan, Albania, Algeria, Andorra, Andorra, Angola };
}
[ImplementPropertyChanged]
public class RegistrationPageViewModel
{
public Country SelectedCountry { get; set; }
}
public class RegistrationPage : ContentPage
{
public RegistrationPage()
{
var vm = new RegistrationPageViewModel();
BindingContext = vm;
var picker = new Picker();
foreach (var country in Country.Countries) picker.Items.Add(country.Name);
picker.SetBinding<RegistrationPageViewModel>(Picker.SelectedIndexProperty, x => x.SelectedCountry, converter: new PickerItemsToTypeConverter<Country>(Country.Countries));
Content = picker;
}
}
public class PickerItemsToTypeConverter<T> : IValueConverter
{
private readonly IList<T> _pickerItemsList;
public PickerItemsToTypeConverter(IList<T> pickerItemsList) => _pickerItemsList = pickerItemsList;
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var itemType = (T)value;
return _pickerItemsList.IndexOf(itemType);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var selectedIndex = value as int?;
if (selectedIndex == null) throw new Exception("No selection");
return _pickerItemsList[selectedIndex.Value];
}
}