In this article, I will explain how to change the text of the Done/Cancel button of the picker control that we use in our Xamarin.Forms project. We need to create a Custom Renderer to perform this operation. So let’s create our CustomPicker class, which inherits from the Picker class in the portable projects.
To be able to change these text dynamically, we have to defined two bindable properties named DoneButtonText and CancelButtonText. Now let’s write our renderers for each platform.
On iOS, the native control of the picker is UITextField. The Cancel and done buttons are defined as UIBarButtonItem. Then these items added to UIToolBar, and UIToolBar added to UITextField by setting InputAccessoryView.
object provides equal space between the controls if there is more than one. If only one has been added and there is a control next to it, the control occupies the space of its own, while this object fills the remaining space. We add this before the done button therefore it pushes button to the right side. If we didn’t put this object on, the done button would be align to the left.
On Android, the renderer looks a little different because the Done/Cancel buttons are only defined when the picker is clicked.
var builder = new AlertDialog.Builder(Context);
The AlertDialog will be displayed when the picker is clicked. The buttons that we will change is in this object and is defined with this object. That’s why redefining process need to done on the OnCLick () event where the builder is defined. Create a listener for OnCLick() method and use below methods to change Cancel/Done button’s text.
You can download the full project from GitHub.