I'm trying to create a custom picker with 3 components. I followed the tutorial on the Xamarin site here. I got the control to work, except when I click the Done button on the picker (This is the default done button). I get the following exception:
System.InvalidCastException: Unable to cast object of type 'myproj.iOS.MyPickerModel' to type 'Xamarin.Forms.Platform.iOS.PickerRenderer+PickerSource'.
Here is my code:
In the shared proj:
public class MyPicker: Picker {}
In the iOS proj:
[assembly: ExportRenderer(typeof(MyPicker), typeof(MyPickerRenderer))]
public class MyPickerRenderer: PickerRenderer
{
// Override the OnElementChanged method so we can tweak this renderer post-initial setup
protected override void OnElementChanged(ElementChangedEventArgs e)
{
base.OnElementChanged(e);
if (Control != null)
{
var picker = (UIPickerView)this.Control.InputView;
picker.BackgroundColor = UIColor.White;
picker.Model = new MyPickerModel();
}
And the Model:
public class MyPickerModel : UIPickerViewModel
{
private string[] array1 = new string [] {
"1","2","3","4"
};
private string[] array2 = new string [] {
"1a","2a","3a","4a"
};
private string[] array3 = new string [] {
"a","b","c","d"
};
public override nint GetComponentCount (UIPickerView pickerView)
{
return 3;
}
public override nint GetRowsInComponent (UIPickerView pickerView, nint component)
{
// Returns
switch (component) {
case 0: return array1.Length;
case 1: return array2.Length;
case 2: return array3.Length;
default:break;
}
return 0;
}
public override string GetTitle (UIPickerView pickerView, nint row, nint component)
{
// Returns
switch (component)
{
case 0: return array1[row];
case 1: return array2[row];
case 2: return array3[row];
default: break;
}
return null;
}
public override nfloat GetComponentWidth (UIPickerView pickerView, nint component)
{
switch (component)
{
case 0: return 100.0f;
case 1: return 100.0f;
case 2: return 100.0f;
default: break;
}
return 0;
}
public override nfloat GetRowHeight (UIPickerView pickerView, nint component)
{
return 40f;
}
}
And lastly my page:
public class MyPage : ContentPage
{
public MyPage()
{
MyPicker picker = new MyPicker
{
Title = "Color",
VerticalOptions = LayoutOptions.CenterAndExpand
};
picker.SelectedIndexChanged += (sender, args) =>
{
};
var mainLayout = new StackLayout
{
Orientation = StackOrientation.Vertical,
Children =
{
picker
}
};
// Accomodate iPhone status bar.
this.Padding = new Thickness(0, Device.OnPlatform(20, 0, 0), 0, 0);
this.BackgroundImage = "background.png";
// Build the page.
this.Content = mainLayout;
}
}
I don't understand why its trying to cast MyPickerModel to PickerRenderer+PickerSource
Thanks!