Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Note
This book was published in the spring of 2016, and has not been updated since then. There is much in the book that remains valuable, but some of the material is outdated, and some topics are no longer entirely correct or complete.
This chapter explores eight View derivatives that allow interaction with the user.
View overview
Xamarin.Forms contains 20 instantiable classes that derive from View but not Layout. Six of these have been covered in previous chapters:
Label: Chapter 2. Anatomy of an appBoxView: Chapter 3. Scrolling the stackButton: Chapter 6. Button clicksImage: Chapter 13. BitmapsActivityIndicator: Chapter 13. BitmapsProgressBar: Chapter 14. AbsoluteLayout
The eight views in this chapter effectively allow the user to interact with basic .NET data types:
| Data type | Views |
|---|---|
Double |
Slider, Stepper |
Boolean |
Switch |
String |
Entry, Editor, SearchBar |
DateTime |
DatePicker, TimePicker |
You can think of these views as visual interactive representations of the underlying data types. This concept is explored more in the next chapter, Chapter 16. Data binding.
The remaining six views are covered in the following chapters:
WebView: Chapter 16. Data bindingPicker: Chapter 19. Collection viewsListView: Chapter 19. Collection viewsTableView: Chapter 19. Collection viewsMap: Chapter 28. Location and MapsOpenGLView: Not covered in this book (and no support for Windows platforms)
Slider and stepper
Both Slider and Stepper allow the user to choose a numeric value from a range. The Slider is a continuous range while the Stepper involves discrete values.
Slider basics
The Slider is a horizontal bar representing a range of values from a minimum on the left to a maximum on the right. It defines three public properties:
Valueof typedouble, default value of 0Minimumof typedouble, default value of 0Maximumof typedouble, default value of 1
The bindable properties that back these properties ensure that they are consistent:
- For all three properties, the
coerceValuemethod specified for the bindable property ensures thatValueis betweenMinimumandMaximum. - The
validateValuemethod onMinimumPropertyreturnsfalseifMinimumis being set to a value greater than or equal toMaximum, and similar forMaximumProperty. Returningfalsefrom thevalidateValuemethod causes anArgumentExceptionto be raised.
Slider fires the ValueChanged event with a ValueChangedEventArgs argument when the Value property changes, either programmatically or when the user manipulates the Slider.
The SliderDemo sample demonstrates the simple use of the Slider.
Common pitfalls
Both in code and in XAML, the Minimum and Maximum properties are set in the order that you specify. Be sure to initialize these properties so that Maximum is always greater than Minimum. Otherwise an exception will be raised.
Initializing the Slider properties can cause the Value property to change and the ValueChanged event to be fired. You should ensure that the Slider event handler doesn't access views that haven't yet been created during page initialization.
The ValueChanged event doesn't fire during Slider initialization unless the Value property changes. You can call the ValueChanged handler directly from code.
Slider color selection
The RgbSliders program contains three Slider elements that allow you to interactively select a color by specifying its RGB values:
The TextFade sample uses two Slider elements to move two Label elements across an AbsoluteLayout and fade one into the other.
The Stepper difference
The Stepper defines the same properties and events as Slider but the Maximum property is initialized to 100 and Stepper defines a fourth property:
Incrementof typedouble, initialized to 1
Visually, the Stepper consists of two buttons labeled – and +. Pressing – decreases Value by Increment to a minimum of Minimum. Pressing + increases Value by Increment to a maximum of Maximum.
This is demonstrated by the StepperDemo sample.
Switch and CheckBox
The Switch allows the user to specify a Boolean value.
Switch basics
Visually, the Switch consists of a toggle that can be turned off and on. The class defines one property:
IsToggledof typebool
Switch defines one event:
Toggledaccompanied by aToggledEventArgsobject, fired when theIsToggledproperty changes.
The SwitchDemo program demonstrates the Switch.
A traditional CheckBox
Some developers might prefer a more traditional CheckBox to the Switch. The Xamarin.FormsBook.Toolkit library contains a CheckBox class that derives from ContentView. CheckBox is implemented by the CheckBox.xaml and CheckBox.xaml.cs files. CheckBox defines three properties (Text, FontSize, and IsChecked) and a CheckedChanged event.
The CheckBoxDemo sample demonstrates this CheckBox.
Typing text
Xamarin.Forms defines three views that let the user enter and edit text:
Entryfor a single line of textEditorfor multiple lines of textSearchBarfor a single line of text for search purposes.
Entry and Editor derive from InputView, which derives from View. SearchBar derives directly from View.
Keyboard and focus
On phones and tablets without physical keyboards, the Entry, Editor, and SearchBar elements all cause a virtual keyboard to pop up. The presence of this keyboard on the screen is related to input focus. A view must have both its IsVisible and IsEnabled properties set to true to get input focus.
Two methods, one read-only property, and two events are involved with input focus. These are all defined by VisualElement:
- The
Focusmethod attempts to set input focus to an element and returnstrueif successful - The
Unfocusmethod removes input focus from an element - The
IsFocusedread-only property indicates if the element has input focus - The
Focusedevent indicates when an element gets input focus - The
Unfocusedevent indicates when an element loses input focus
Choosing the Keyboard
The InputView class from which Entry and Editor derive defines only one property:
This indicates the type of keyboard that is displayed. Some keyboards are optimized for URIs or numbers.
The Keyboard class allows defining a keyboard with a static Keyboard.Create method with an argument of type KeyboardFlags, an enumeration with the following bit flags:
Noneset to 0CapitalizeSentenceset to 1Spellcheckset to 2Suggestionsset to 4Allset to \xFFFFFFFF
When using the multiline Editor when a paragraph or more of text is expected, calling Keyboard.Create is a good approach to selecting a keyboard. For the single-line Entry, the following static read-only properties of Keyboard are useful:
The KeyboardTypeConverter allows specifying these properties in XAML as demonstrated by the EntryKeyboards program.
Entry properties and events
The single-line Entry defines the following properties:
Textof typestring, the text that appears in theEntryTextColorof typeColorFontFamilyof typestringFontSizeof typedoubleFontAttributesof typeFontAttributesIsPasswordof typebool, which causes characters to be maskedPlaceholderof typestring, for dimly colored text that appears in theEntrybefore anything is typedPlaceholderColorof typeColor
The Entry also defines two events:
TextChangedwith aTextChangedEventArgsobject, fired whenever theTextproperty changesCompleted, fired when the user is finished and the keyboard is dismissed. The user indicates completion in a platform-specific manner
The QuadraticEquations sample demonstrates these two events.
The Editor difference
The multiline Editor defines the same Text and Font properties as Entry but not the other properties. Editor also defines the same two properties as Entry.
JustNotes is a free-form notes-taking program that saves and restores the contents of the Editor.
The SearchBar
The SearchBar does not derive from InputView, so it does not have a Keyboard property. But it does have all the Text, Font, and Placeholder properties that Entry defines. In addition, SearchBar defines three additional properties:
CancelButtonColorof typeColorSearchCommandof typeICommandfor use with data-bindings and MVVMSearchCommandParameterof typeObject, for use withSearchCommand
The platform-specific cancel button erases the text. The SearchBar also has a platform-specific search button. Pressing either of those buttons raises one of the two events that SearchBar defines:
TextChangedaccompanied by aTextChangedEventArgsobjectSearchButtonPressed
The SearchBarDemo sample demonstrates the SearchBar.
Date and time selection
The DatePicker and TimePicker views implement platform-specific controls that allow the user to specify a date or time.
The DatePicker
DatePicker defines four properties:
MinimumDateof typeDateTime, initialized to January 1, 1900MaximumDateof typeDateTime, initialized to December 31, 2100Dateof typeDateTime, initialized toDateTime.TodayFormatof typestring, the .NET formatting string initialized to "d", the short date pattern, resulting in a date display like "7/20/1969" in the US.
You can set the DateTime properties in XAML by expressing the properties as property elements and using the culture-invariant short-date format ("7/20/1969").
The DaysBetweenDates sample calculates the number of days between two dates selected by the user.
The TimePicker (or is it a TimeSpanPicker?)
TimePicker defines two properties and no events:
Timeis of typeTimeSpanrather thanDateTime, indicating the time elapsed since midnightFormatof typestring, the .NET formatting string initialized to "t", the short time pattern, resulting in a time display like "1:45 PM" in the US.
The SetTimer program demonstrates how to use the TimePicker to specify a time for a timer. The program only works if you keep it in the foreground.
SetTimer also demonstrates using the DisplayAlert method of Page to display an alert box.
