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; }
}
我收到错误:"国家"名称在当前上下文中不存在
我做错了什么?有人有工作的例子吗
以下是我的写法(使用 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];
}
}