You are on page 1of 2537

Telerik UI for Xamarin

DOCUMENTATION

Version: R1 2022 SP
Copyright © 2022, Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved.
Telerik UI for Xamarin

Welcome to Telerik UI for Xamarin


Thank you for choosing Telerik UI for Xamarin.

Telerik UI for Xamarin features Xamarin.Forms controls and Visual Studio item templates for building
professional-looking modern mobile applications for Android, iOS and UWP from a single code base.

In addition to the numerous Xamarin.Forms controls, the suite includes Xamarin.Android and
Xamarin.iOS wrappers built on top of truly native iOS and Android components. The Telerik UI for
UWP suite is used as basis for the UWP implementation of the controls.

To learn more please visit the Telerik UI for Xamarin product overview page.

Telerik UI for Xamarin.Forms Controls


Our suite features the following controls for cross-platform development with Xamarin.Forms:

 Data Controls
 DataGrid
 ListView
 DataForm
 Pdf Viewer
 PdfViewer
 Calendar & Scheduling
 Calendar

3
Telerik UI for Xamarin

 Navigation & Layout


 TreeView
 SideDrawer
 TabView
 Accordion
 Expander
 DockLayout
 Buttons
 Segmented Control
 Button
 CheckBox
 Editors
 Entry
 AutoCompleteView
 NumericInput
 MaskedInput
 Image Editor
 DateTime Picker
 List Picker
 Templated Picker

 Data Visualization
 Charts
 Map
 Gauge
 Rating
 Barcode
 Interactivity & UX
 BusyIndicator
 Popup
 SlideView
 Border
 Path
 Document Processing Libraries
 PdfProcessing
 WordsProcessing
 SpreadProcessing
 SpreadStreamProcessing
 ZipLibrary
 Chatbots
 Conversational UI

Telerik UI for Xamarin.Native


If you're building a Xamarin.Android or Xamarin.iOS application, you can take advantage of the
native controls wrappers on each platform. The native controls are a subset of all the controls
available to Xamarin.Forms. Visit the Native Controls Wrappers section for more information on
Telerik Xamarin.Android and Xamarin.iOS components.

Getting Started with Telerik UI for Xamarin

4
Telerik UI for Xamarin

To learn how to install and work with Telerik UI for Xamarin suite, visit the following resources:

 System Requirements
 Getting Started on Windows
 Getting Started on Mac

Trial Version and Commercial License


Telerik UI for Xamarin library is a commercial UI library. You are welcome to explore its full
functionality and get technical support from the team when you register for a free 30-day trial. To use
it commercially, you need to purchase a license. Feel free to review the Telerik UI for Xamarin
License Agreement to get acquainted with the full terms of use.

Support Options
For any issues you might encounter while working with Telerik UI for Xamarin, use any of the
available support channels:

 UI for Xamarin license holders and active trialists can take advantage of the outstanding
customer support delivered by the developers building the library. To submit a support ticket,
use the UI for Xamarin dedicated support system.
 UI for Xamarin forums are part of the free support you can get from the community and from
the UI for Xamarin team on all kinds of general issues.
 UI for Xamarin feedback portal and UI for Xamarin roadmap provide information on the features
in discussion and also the planned ones for release.
 You may still need a tailor-made solution for your project. In such cases, go straight to
Progress Services.

Learning Resources
 Virtual Classroom
 Knowledge Base
 Support Resources Hub Page

Related Links
 UI for Xamarin product page
 Latest news for Telerik UI for Xamarin
 UI for Xamarin blogs

Help us Improve the Telerik UI for Xamarin Documentation


We believe that the documentation for a product is at its best when the content is a collaboration
between the builders and consumers of that product. Everybody can play a role in making our
documentation better and we encourage you to help us with that task in the way that you choose:

Submit a New Issue at GitHub

5
Telerik UI for Xamarin

If you find an issue with our docs that need to be addressed, the best way to let us know is by
creating an issue in our Github repository. When creating an issue, please provide a descriptive title,
be as specific as possible and link to the documentation in question. If you can provide a link to the
closes anchor to the issue, that is even better.

Update the Documentation at GitHub

Creating an issue is great, but what we really love are pull requests. This is the most direct method.
So, if you find an issue in the docs, or even feel like creating new content, we’d be happy to have
your contributions! The basic steps are that you fork our documentation and submit a pull request.
That way you may contribute to exactly where you found the error. After that, our technical writing
team just needs to approve your change request. Please use only standard markdown. For a more
detailed instructions, please follow the contribution instructions published in GitHub.

Thank you for your contribution to the Telerik UI for Xamarin Documentation!

6
Telerik UI for Xamarin

First Steps
This article will guide you through the basics of Telerik UI for Xamarin and how to start using the
suite on Windows OS.

Once you have your first simple Xamarin control up and running, take a look at the Next Steps
section to explore other control functionality.

For additional resources you can also review the Related Articles section on the right.

Download the Controls


When you have an active trial or developer license, you can download the following files:

 Standalone installation
 Assemblies for manual installation
 NuGet packages
 Old versions

If you are not a customer, you can download a free, fully functional trial and the same options will
apply to you as well.
 
Make sure you have already read the System Requirements article before you proceed.
 
Follow the steps below in order to download the installation files:

1. Log into your Telerik account and click on the Downloads tab.

Figure 1: Downloads tab

2. Select Progress Telerik UI for Xamarin product title.


3. Download the Automatic Installation (msi) file.

Figure 2: Download automated (.msi) installer

7
Telerik UI for Xamarin

Once you have installed Telerik UI for Xamarin it's time to create your first application.

Create a Project with Telerik UI for Xamarin


The easiest way to create a Telerik UI for Xamarin project is to use Visual Studio Extensions which
are distributed with the Telerik UI for Xamarin installer. They can also be downloaded and installed
as separate product from the Visual Studio Marketplace. Once installed, the Visual Studio Extensions
can be accessed by going to Telerik Menu > Telerik UI for Xamarin.

For detailed information on installing the Project Wizard, go to the Installing VSExtensions article.
 
Depending on your scenario, you either have an existing app where you will add our Telerik
components, or you have to create a new blank app. For the purpose of this article we will focus on
creating an app from scrath with Visual Studio.

1. Open Microsoft Visual Studio.


2. Create new Telerik Xamarin project.

Figure 3: Go to Telerik > Telerik UI for Xamarin > Create New Telerik Project

8
Telerik UI for Xamarin

Select which platform(s) your application targets and the wizard will automatically reference
all required Telerik binaries and packages.

Figure 4: Select you the platform(s)

Next Steps

9
Telerik UI for Xamarin

Now that you have installed and created your first project it is time to add a Telerik UI for Xamarin
control:

 Add a Control to Your Project


 Explore Control Features
 Change control appearance
 Further information

See Also
 System Requirements
 Telerik NuGet Server
 Required Android Support Libraries
 Getting started on Mac

10
Telerik UI for Xamarin

Add a Control to Your Project


Show the Telerik Toolbox
In order to show the Telerik Toolbox in Visual Studio and add a control, you should navigate to
Telerik > Telerik UI for Xamarin > Open Telerik UI for Xamarin Toolbox.

Figure 1: Show the Telerik UI for Xamarin Toolbox

Add a Control to Your Project


Embedding the controls from the suite is made as easy as possible and all you need to do is simply
drag one of the controls within your XAML file. This will add the control definition and will also map
the needed namespace declarations. For the purpose of this example we will add RadListView
Control.

Figure 2: Adding Telerik controls to your application

11
Telerik UI for Xamarin

Populating RadListView with data


First thing you need to do is to create a data and view model classes:

Example 1: Populating RadListView with data in C#.

C#
public class SourceItem
{
public SourceItem(string name)
{
this.Name = name;
}
public string Name { get; set; }
}
public class ViewModel
{
public ViewModel()
{
this.Source = new List<SourceItem> { new SourceItem("Tom"), new
SourceItem("Anna"), new SourceItem("Peter"), new SourceItem("Teodor"), new
SourceItem("Lorenzo"), new SourceItem("Andrea"), new SourceItem("Martin") };

12
Telerik UI for Xamarin

}
public List<SourceItem> Source { get; set; }
}
 

Update the setup of the ListView you created in Figure 6 to be like:

Example 2: Update the setup of the ListView in XAML.

XAML
<telerikDataControls:RadListView x:Name="listView" ItemsSource="{Binding Source}">
<telerikDataControls:RadListView.BindingContext>
<local:ViewModel />
</telerikDataControls:RadListView.BindingContext>
<telerikDataControls:RadListView.ItemTemplate>
<DataTemplate>
<telerikListView:ListViewTemplateCell>
<telerikListView:ListViewTemplateCell.View>
<Grid>
<Label Margin="10" Text="{Binding Name}" />
</Grid>
</telerikListView:ListViewTemplateCell.View>
</telerikListView:ListViewTemplateCell>
</DataTemplate>
</telerikDataControls:RadListView.ItemTemplate>
</telerikDataControls:RadListView>
 

The results should be:

Figure 3: Result in Android, iOS and Windows

13
Telerik UI for Xamarin

Next Steps
Now that you have your first Telerik UI for Xamarin control running, you may want to explore the
different features, behavior and appearances. Below you can find guidance on getting started with
such tasks:

 Explore Control Features


 Change control appearance
 Further information

See Also
 System Requirements
 Telerik NuGet Server

14
Telerik UI for Xamarin

Explore Control Features


Once you have your first control working in your project, it's time to see what else it can do. This
article provides a short overview of how to get started with finding control functionality and features.

Demos
To get an overview of what each control offers, the fastest way will be to explore our Live Demos
availabile free in Google Play Store, App Store and Microsoft Store.

Documentation
Each control documentation consists of different sections to help you get started with the control and
explore its key features. For some of the more complex ones you can also find additional articles that
will help you get the best out of it. Things like feature usage and styling options.

Figure 1: Typical control documentation structure

15
Telerik UI for Xamarin

Control Features
In this example we are going to look Selection as one of the key features in the ListView control.

RadListView component exposes selection feature. It allows users to select one or many items out of
the ItemsSource of the control. This feature provides both visual and programmatic feedback for the
actions of the user.

This article will show the basic properties RadListView provides for working with selection.

Selection Configuration
RadListView provides three selection modes, which allow you to manipulate the type of selection.
This is controlled by the SelectionMode property which has the following entries:

 SelectionMode (Telerik.XamarinForms.DataControls.ListView.SelectionMode):
 None - This mode doesn't allow users to select an item.

16
Telerik UI for Xamarin

 Single - This is the default selection mode. It allows users to select only one item.
 Multiple - This mode allows users to select more than one item.

Check below how you can set SelectionMode in XAML and code-behind:

XAML
<telerikDataControls:RadListView x:Name="listView"
SelectionMode="Multiple" />
 

C#
var listView = new RadListView();
listView.SelectionMode =
Telerik.XamarinForms.DataControls.ListView.SelectionMode.Multiple;
 

You can also configure how the selection to be triggered by the end users through the
SelectionGesture property:

 SelectionGesture (Telerik.XamarinForms.DataControls.ListView.SelectionGesture):
 Tap - Users need to tap on an item to select it. This is the default SelectionGesture
value;
 Hold - Users need to tap & hold on an item to select it.

XAML
<telerikDataControls:RadListView x:Name="listView"
SelectionGesture="Hold" />
 

C#
var listView = new RadListView();
listView.SelectionGesture =
Telerik.XamarinForms.DataControls.ListView.SelectionGesture.Hold;
 

Getting Selected Items


RadListView exposes the following properties for getting the selected item or items in case of
multiple selection:

 SelectedItems (ObservableCollection<object>): Read-only collection used to get the


currently selected items;
 SelectedItem (object): Specifies the last selected item of the ListView.

Selection Events

 SelectionChanged: An event that is triggered whenever the SelectedItems collection is


changed. The SelectionChanged event handler receives two parameters:
 The sender argument which is of type object, but can be cast to the RadListView type.

17
Telerik UI for Xamarin

 A NotifyCollectionChangedEventArgs object which provides information on the collection


changed event. For more details check NotifyCollectionChangedEventArgs Class topic.

Styling
You can customize the way selected items look by applying SelectedItemStyle property to the
RadListView instance. For detailed information on the approach go to Items Styles topic in ListView
documentation.

Here is how the RadListView control looks like on different platforms when multiple items are
selected:

Figure 1: Result in Android, iOS and Windows

Next Steps
Now that you have the Telerik UI for Xamarin controls running in your project, you may want to
explore their features, customize their behavior or change their appearance. Below you can find
guidance on getting started with such tasks:

 Change control appearance


 Further information

See Also
 First Steps
 Progress Virtual Classroom

18
Telerik UI for Xamarin

Control Styling and Appearance


With the help of Telerik Theme you can set a theme for your application using an easy and
straightforward process. Furthermore, you can customize a default theme resources to achieve
different and more distinct appearance.

Component Styling
Majority of our components provide styling mechanism for customizing the look of their items. This is
one of the most common ways to achieve different looks. You can find detailed information on how
to customize our controls in the Theming and Styles or Styling folder available in the different
Xamarin Forms Controls.

Xamarin Forms Theming


You can also explore how to set a Telerik Theme by merging the required ResourceDictionaries in
your application or create a custom theme based on a Telerik Theme. The Default Theme Colors and
their actual appearance are present in the table below.

Default Theme Colors


Main Colors

Color Hex Value Appearance


Basic Font Color #4A4949
AlternativeFont Color #919191
Accent Color 1 #3148CA
Background Color 1 #3D5AFE
Accent Color 2 #30BCFF
Background Color 2 #000000
Color of Grid #D9D9D9
Color of Menu Bar #F8F8F8

Complementary Colors

Complementary Color Hex Value Appearance


Complementary Color 1 #FF5225
Complementary Color 2 #FFC325
Complementary Color 3 #2EC262

19
Telerik UI for Xamarin

Complementary Color 4 #FE3D5A


Complementary Color 5 #803DFE
Complementary Color 6 #3DBAFE

Next Steps
 More Learning Resources

See Also
 Modifying Default Theme
 Set a Telerik Theme

20
Telerik UI for Xamarin

Further Information
Now that you have the Telerik UI for Xamarin controls running in your project, the list of resources
below can help you get a better understanding of how they work and help you get the most of them.

If you are just getting started, you can find guidance in the following articles:

 First Steps
 Add a Control to Your Project
 Explore control features
 Change control appearance

More Learning Resources


You don't need all of this immediately, but you can use this list as a starting point for future
reference.

Video Tutorials

 Progress Virtual Classroom

Installation and Upgrade

 System Requirements
 Download Product Files
 Telerik Visual Studio Extensions
 Required Android Support Libraries
 Telerik NuGet Server
 Lite Assemblies
 Upgrading on Windows

Appearance

 Setting a Theme
 Modifying a Default Theme
 Telerik Font Icons

Common Information

 Localization and Globalization


 Xamarin Forms vs Xamarin Native
 Xamarin SDK Examples

21
Telerik UI for Xamarin

First Steps
This article will guide you through the basics of Telerik UI for Xamarin and how to start using the
suite on Mac.

Once you have your first simple Xamarin control up and running, take a look at the Next Steps
section to explore other control functionality.

For additional resources you can also review the Related Articles section on the right.

Download the Controls


When you have an active trial or developer license, you can download the following files:

 Standalone installation
 Assemblies for manual installation
 NuGet packages
 Old versions

If you are not a customer, you can download a free, fully functional trial and the same options will
apply to you as well.
 
Make sure you have already read the System Requirements article before you proceed.
 
Follow the steps below in order to download the installation files:

1. Log into your Telerik account and click on the Downloads tab.

Figure 1a: Downloads tab

2. Select Progress Telerik UI for Xamarin product title.


3. Download the Installation .pkg and .mpack files.

Figure 3a: Download installers

22
Telerik UI for Xamarin

4. Install Progress Telerik UI for Xamarin

Since MacOS Catalina, downloaded installers and packages are quarantined. If you try to
just open the pkg file, you may see a popup preventing you from installing it. The easiest
solution is to

1. Right-click on the .pkg file you downloaded in Step 3


2. Select "Open With"
3. Select "Installer" (see Fig 4a).

Figure 4a: Open With -> Installer

For a more permanent solution, open the Mac OS Settings -> Security & Privacy settings
panel and select Allow apps downloaded from App Store and Identified developers.

23
Telerik UI for Xamarin

5. Install Visual Studio for Mac Extensions

Once you have finished the pkg installation, now it's time to install the Visual Studio
Extensions with the mpack file.

Open the Visual Studio Extension Manager and select the Install form file... option. Figure 5a
shows how to access the Extension Manager.

Figure 5a: Accessing Visual Studio Extensions

Once you have accessed the Extension Manager, the following dialog will appear and you
should look for the Install from file option.

Figure 5b: Reaching the Extension Manager

24
Telerik UI for Xamarin

Navigate to the ProjectTemplateXamarin.mpack file, select it and click "Open" to complete


the installation.

Figure 5c: The ProjectTemplate location

25
Telerik UI for Xamarin

If the add-in is successfully added to Visual Studio, you should see it in the IDE extensions
section.

Figure 5d: Installation Successful

26
Telerik UI for Xamarin

6. Restart Visual Studio for Mac to complete the installation.

Create a Project with Telerik UI for Xamarin


1. Now you can create a new project using the Telerik Project Template. Select which
platform(s) your application targets and the wizard will automatically reference all required
Telerik binaries and packages.

Figure 1a: Create New Project Dialog

27
Telerik UI for Xamarin

2. Select the Telerik Forms App template which can be found in Other > Miscellaneous section.

Figure 2a: Telerik Forms App template

28
Telerik UI for Xamarin

Next Steps
Now that you have downloaded and installed Telerik UI for Xamarin, and created your first project its
time to add the Telerik UI for Xamarin control. Below you can find guidance on getting started with
that:

 Add Control to Your Project


 Explore Control Features
 Change control appearance
 Further information

See Also
 System Requirements
 Telerik NuGet Server
 Required Android Support Libraries
 Getting started on Windows

29
Telerik UI for Xamarin

Add a Control to Your Project


Show the Telerik Toolbox.
In order to show the Toolbox and start using the controls, you should navigate to the StartPage.xaml
file in your project and click on it. If the ProjectTemplate.mpack file is installed successfully, Toolbox
window is visible in the project when you click on the StartPage.xaml file.

For more information about Toolbox for Mac check the TelerikXamarinForms Toolbox article.
 

Add a Control to Your Project.


Embedding the controls from the suite is made as easy as possible and all you need to do is simply
drag one of the controls within your XAML file. This will add the control definition and will also map
the needed namespace declarations. For the purpose of this example we will add RadListView
Control.

Figure 1: Adding Telerik controls to your application

Populating RadListView with data


First thing you need to do is to create a data and view model classes:

Example 1: Populating RadListView with data in C#.

C#
public class SourceItem
{
public SourceItem(string name)

30
Telerik UI for Xamarin

{
this.Name = name;
}
public string Name { get; set; }
}
public class ViewModel
{
public ViewModel()
{
this.Source = new List<SourceItem> { new SourceItem("Tom"), new
SourceItem("Anna"), new SourceItem("Peter"), new SourceItem("Teodor"), new
SourceItem("Lorenzo"), new SourceItem("Andrea"), new SourceItem("Martin") };
}
public List<SourceItem> Source { get; set; }
}
 

Update the setup of the ListView you created in Figure 6 to be like:

Example 2: Update the setup of the ListView in XAML.

XAML
<telerikDataControls:RadListView x:Name="listView" ItemsSource="{Binding Source}">
<telerikDataControls:RadListView.BindingContext>
<local:ViewModel />
</telerikDataControls:RadListView.BindingContext>
<telerikDataControls:RadListView.ItemTemplate>
<DataTemplate>
<telerikListView:ListViewTemplateCell>
<telerikListView:ListViewTemplateCell.View>
<Grid>
<Label Margin="10" Text="{Binding Name}" />
</Grid>
</telerikListView:ListViewTemplateCell.View>
</telerikListView:ListViewTemplateCell>
</DataTemplate>
</telerikDataControls:RadListView.ItemTemplate>
</telerikDataControls:RadListView>
 

The results should be:

Figure 2: Result in Android, iOS and Windows

31
Telerik UI for Xamarin

Next Steps
Now that you have your first Telerik UI for Xamarin control running, you may want to explore the
different features, behavior and appearances. Below you can find guidance on getting started with
such tasks:

 Explore Control Features


 Change control appearance
 Further information

See Also
 System Requirements
 Telerik NuGet Server
 Getting started on Mac

32
Telerik UI for Xamarin

Explore Control Features


Once you have your first control working in your project, it's time to see what else it can do. This
article provides a short overview of how to get started with finding control functionality and features.

Demos
To get an overview of what each control offers, the fastest way will be to explore our Live Demos
availabile free in Google Play Store and App Store.

Documentation
Each control documentation consists of different sections to help you get started with the control and
explore its key features. For some of the more complex ones you can also find additional articles that
will help you get the best out of it. Things like feature usage and styling options.

Figure 1: Typical control documentation structure

33
Telerik UI for Xamarin

Control Features
In this example we are going to look Selection as one of the key features in the ListView control.

RadListView component exposes selection feature. It allows users to select one or many items out of
the ItemsSource of the control. This feature provides both visual and programmatic feedback for the
actions of the user.

This article will show the basic properties RadListView provides for working with selection.

Selection Configuration
RadListView provides three selection modes, which allow you to manipulate the type of selection.
This is controlled by the SelectionMode property which has the following entries:

 SelectionMode (Telerik.XamarinForms.DataControls.ListView.SelectionMode):
 None - This mode doesn't allow users to select an item.

34
Telerik UI for Xamarin

 Single - This is the default selection mode. It allows users to select only one item.
 Multiple - This mode allows users to select more than one item.

Check below how you can set SelectionMode in XAML and code-behind:

XAML
<telerikDataControls:RadListView x:Name="listView"
SelectionMode="Multiple" />
 

C#
var listView = new RadListView();
listView.SelectionMode =
Telerik.XamarinForms.DataControls.ListView.SelectionMode.Multiple;
 

You can also configure how the selection to be triggered by the end users through the
SelectionGesture property:

 SelectionGesture (Telerik.XamarinForms.DataControls.ListView.SelectionGesture):
 Tap - Users need to tap on an item to select it. This is the default SelectionGesture
value;
 Hold - Users need to tap & hold on an item to select it.

XAML
<telerikDataControls:RadListView x:Name="listView"
SelectionGesture="Hold" />
 

C#
var listView = new RadListView();
listView.SelectionGesture =
Telerik.XamarinForms.DataControls.ListView.SelectionGesture.Hold;
 

Getting Selected Items


RadListView exposes the following properties for getting the selected item or items in case of
multiple selection:

 SelectedItems (ObservableCollection<object>): Read-only collection used to get the


currently selected items;
 SelectedItem (object): Specifies the last selected item of the ListView.

Selection Events

 SelectionChanged: An event that is triggered whenever the SelectedItems collection is


changed. The SelectionChanged event handler receives two parameters:
 The sender argument which is of type object, but can be cast to the RadListView type.

35
Telerik UI for Xamarin

 A NotifyCollectionChangedEventArgs object which provides information on the collection


changed event. For more details check NotifyCollectionChangedEventArgs Class topic.

Styling
You can customize the way selected items look by applying SelectedItemStyle property to the
RadListView instance. For detailed information on the approach go to Items Styles topic in ListView
documentation.

Here is how the RadListView control looks like on different platforms when multiple items are
selected:

Figure 2: Result in iOS and Android

Next Steps
Now that you have the Telerik UI for Xamarin controls running in your project, you may want to
explore their features, customize their behavior or change their appearance. Below you can find
guidance on getting started with such tasks:

36
Telerik UI for Xamarin

 Change control appearance


 Further information

See Also
 First Steps
 Progress Virtual Classroom

37
Telerik UI for Xamarin

Control Styling and Appearance


With the help of Telerik Theme you can set a theme for your application using an easy and
straightforward process. Furthermore, you can customize a default theme resources to achieve
different and more distinct appearance.

Component Styling
Majority of our components provide styling mechanism for customizing the look of their items. This is
one of the most common ways to achieve different looks. You can find detailed information on how
to customize our controls in the Theming and Styles or Styling folder available in the different
Xamarin Forms Controls.

Xamarin Forms Theming


You can also explore how to set a Telerik Theme by merging the required ResourceDictionaries in
your application or create a custom theme based on a Telerik Theme. The Default Theme Colors and
their actual appearance are present in the table below.

Default Theme Colors


Main Colors

Color Hex Value Appearance


Basic Font Color #4A4949
AlternativeFont Color #919191
Accent Color 1 #3148CA
Background Color 1 #3D5AFE
Accent Color 2 #30BCFF
Background Color 2 #000000
Color of Grid #D9D9D9
Color of Menu Bar #F8F8F8

Complementary Colors

Complementary Color Hex Value Appearance


Complementary Color 1 #FF5225
Complementary Color 2 #FFC325
Complementary Color 3 #2EC262

38
Telerik UI for Xamarin

Complementary Color 4 #FE3D5A


Complementary Color 5 #803DFE
Complementary Color 6 #3DBAFE

Next Steps
 More Learning Resources

See Also
 Modifying Default Theme
 Set a Telerik Theme

39
Telerik UI for Xamarin

Next Steps
Now that you have the Telerik UI for Xamarin controls running in your project, the list of resources
below can help you get a better understanding of how they work and help you get the most of them.

If you are just getting started, you can find guidance in the following articles:

 First Steps
 Add Control to Your Project
 Explore control features
 Change control appearance

More Learning Resources


You don't need all of this immediately, but you can use this list as a starting point for future
reference.

Video Tutorials

 Progress Virtual Classroom

Installation and Upgrade

 System Requirements
 Download Product Files
 Telerik Visual Studio Extensions
 Required Android Support Libraries
 Telerik NuGet Server
 Lite Assemblies
 Upgrading on Mac

Appearance

 Setting a Theme
 Modifying a Default Theme
 Telerik Font Icons

Common Information

 Localization and Globalization


 Xamarin Forms vs Xamarin Native
 Xamarin SDK Examples

40
Telerik UI for Xamarin

Telerik UI for Xamarin Demo Applications


Telerik UI for Xamarin provides an easy-to-use infrastructure with many fully-featured examples
demonstrating our Xamarin controls. You can review the source code of each example and get
familiar with the configuration possibilities that each provides.

There are two sets of demos showing Telerik Xamarin.Forms controls: the Telerik UI for Xamarin
Samples application and the SDK Browser application. In this topic, we describe how to use them
and explain their differences.

Telerik UI for Xamarin Samples Application


The Telerik UI for Xamarin Samples is the application you can find in the app stores (Google Play,
Apple App Store and Windows Store). It is highly polished and has many scenario-specific use
cases designed to show off a subset of features for each component.

You can access the Xamarin Samples application in the following ways:

 If you have already installed Telerik UI for Xamarin, navigate to the /[installation-path]/Telerik
UI for Xamarin [version]/QSF/ folder and open the QSF.sln file;
 You can explore the code directly in the Xamarin Samples repository on GitHub;
 You can install it from the corresponding app store (Google Play, Apple App Store or Windows
Store).

The image below shows the Xamarin Samples application main view with all the Telerik UI for
Xamarin controls. There are the Latest and Featured sections that give a quick overview of the
features and recently introduced components.

41
Telerik UI for Xamarin

The following images show a concrete example from the Xamarin Samples application (Calendar &
Scheduling Appointment Template example):

42
Telerik UI for Xamarin

Telerik UI for Xamarin Samples Application Dark Mode


The Telerik UI for Xamarin Samples application has a dark mode support on Android and on iOS.
You can change the app theme by clicking on a button.

Here is how the Xamarin Samples application looks when Dark Mode is applied:

43
Telerik UI for Xamarin

SDK Browser Application


The SDKBrowser is a set of examples that explain how to use the features of a control. Contrary to
the Xamarin Samples application, the SDKBrowser shows the components in their pure form without
adding extra styling and polishing. It's the go-to source for "how do I use X in Y control". Most of the
code snippets available in the documentation are directly generated from the examples in the
SDKBrowser (you can see special comments in the code for this).

You can access the SDKBrowser application in the following ways:

 If you have already installed Telerik UI for Xamarin, navigate to the /[installation-path]/Telerik
UI for Xamarin [version]/Examples/Forms folder and open the SDKBrowser.sln file;
 You can directly explore the code in the SDKBrowser Examples repository on GitHub.

Repository Note: When cloning a repository, you can restore the Telerik assemblies
references in one of three ways:
 
The image below shows the SDKBrowser main view with all the controls listed:

44
Telerik UI for Xamarin

Clicking on any control will navigate to a page containing categories with all the examples related to
that component. Every control has a Getting Started category where you can learn how to use it in a
basic scenario (in XAML and in code-behind).

See Also

45
Telerik UI for Xamarin

 System Requirements
 Getting Started on Windows
 Getting Started on Mac

46
Telerik UI for Xamarin

Telerik UI for Xamarin Sample Applications


Discover the power of Telerik UI for Xamarin with several fully functional, real-world Xamarin.Forms
application examples.

The applications are developed using the Telerik UI for Xamarin controls. These applications are
valuable resource for best programming practices in Xamarin or as a blueprint for your next
Xamarin.Forms application.

Telerik ERP App


The Telerik ERP (Enterprise Resource Management Application) is a showcase software that
demonstrates how you can view and process different financial transactions and processes. From
clients to orders and vendors, this application provides a quick and efficient way to manage your
business.

The application is created with the powerful Telerik UI for Xamarin controls and demonstrates how
one can architecture real-world line of business application. It uses the most popular Telerik UI for
Xamarin controls such as Charts, Data Grid, ListView, Inputs, BusyIndicator and also features
MVVM utilizing the MVVM Cross framework.

The "Telerik UI for Xamarin ERP Application" is in the app stores (Google Play, Apple App Store and
Windows Store).

The application can be accessed in the following ways:

 You can explore the code directly in the Samples Application repository on GitHub;
 You can install it from the corresponding app store
 Google Play,
 Apple App Store
 Windows Store.

The image below shows how the Telerik ERP app looks on mobile phone:

47
Telerik UI for Xamarin

and the other screens:

and how the Tablet version looks:

48
Telerik UI for Xamarin

Check here to learn more about the Telerik ERP App.


 

Telerik CRM App


The Telerik CRM is a cross-platform Xamarin.Forms demo application developed within the business
context of a functioning art gallery and its customer relations. The application is built from the ground
up using a combination of Azure App Services for the backend, Azure Bot Framework for an in-app
support chat service and Telerik UI for Xamarin for a beautiful and feature-rich client experience.

The application provides a seamless user-experience which enables the users to easily explore
information about employees, customers, products and orders, as well as interact with a support
chat bot that will guide them through the application and answer various questions about finding the
appropriate information.

The application can be accessed in the following ways:

 You can explore the code directly in the Samples Application repository on GitHub;
 You can install it from the corresponding app store
 Google Play,
 Apple App Store
 Windows Store.

The image below shows how the Telerik CRM app looks:

49
Telerik UI for Xamarin

Check here to learn more about the Telerik CRM App.


 

Telerik ToDo App


The Telerik ToDo is a simple, yet elegant customer-facing application designed to cover various task
management scenarios. The application’s frontend is build entirely with Telerik UI for Xamarin
controls, while the backend is powered by a variety of interesting technologies such as Entity
Framework Core, SQLite and MMVMFresh. It features some of the most popular controls such as
ListView, DataForm, SideDrawer, TreeView, SlideView and many more.

The app scenario is about organizing notes, ideas, thoughts without losing focus.

 Create notes.
 Organize notes into categories.
 View your notes in card and linear view.
 Search notes.

The application can be accessed in the following ways:

 You can explore the code directly in the Samples Application repository on GitHub;
 You can install it from the corresponding app store
 Google Play,
 Apple App Store
 Windows Store.

The image below shows how the Telerik ToDo app looks:

50
Telerik UI for Xamarin

Check here to learn more about the Telerik ToDo App.


 

Telerik Tagit App


The Telerik TagIt app turns the photo gallery of a mobile device into a searchable database by
allowing users to easily tag and caption their photos for quick and easy retrieval. The application is
built on Xamarin.Forms with the help of Microsoft Azure’s Computer Vision API and Telerik UI for
Xamarin.

The Telerik TagIt application is an ideal example of an AI-powered app written in Xamarin.Forms.
The app uses Microsoft Azure's Computer Vision API — part of the Cognitive Services suite — for
building the backend with artificial intelligence and machine learning.

The application can be accessed in the following ways:

 You can explore the code directly in the Samples Application repository on GitHub;
 You can install it from the corresponding app store
 Google Play,
 Apple App Store
 Windows Store.

The image below shows how the Telerik Tagit app looks:

51
Telerik UI for Xamarin

Check here to learn more about the Telerik Tagit App.


 

See Also
 System Requirements
 Getting Started on Windows
 Getting Started on Mac

52
Telerik UI for Xamarin

Telerik UI for Xamarin.Android and


Xamarin.iOS Native Examples
Telerik UI for Xamarin provides an easy-to-use infrastructure with many fully featured examples
demonstrating our Xamarin controls. You can review the source code of each example and get
familiar with the configuration possibilities that each provides.

Native-only Examples
Solutions that show how to use the controls when developing through Xamarin.Android or
Xamarin.iOS are included in the Telerik UI for Xamarin zip file provided for manual installation.

Telerik_UI_for_Xamarin_[version]_[license].zip, where [version] marks the release and [license] is


replaced with Dev or Trial depending on the license, is available for download from the Downloads
section of your Telerik account. Unzip the archive and go to Examples folder - Xamarin.Android and
Xamarin.iOS solutions are available in separate folders - Android and iOS, respectively.

In addition, the native-only examples are included as part of the Telerik UI for Xamarin MSI installation
. You can find the solutions in the "[installation-path]/Telerik UI for Xamarin [version]/Examples"
folder.

Visit the Native Controls Wrappers section for more information on Telerik Xamarin.Android and
Xamarin.iOS components.
 

Xamarin.Android Samples
Telerik UI for Xamarin.Android Samples contains sample scenarios using the Telerik UI for
Xamarin.android controls. Telerik UI for Xamarin suite includes Xamarin.Android wrappers built on
top of truly native Android components.

53
Telerik UI for Xamarin

For more details please check the Xamarin.Android Wrappers article.


 

Xamarin.iOS Examples
Telerik UI for Xamarin.iOS Examples contains sample scenarios using the Telerik UI for
Xamarin.iOS controls. Telerik UI for Xamarin suite includes Xamarin.iOS wrappers built on top of
truly native iOS components, allowing you to build unique and visually stunning iOS applications.

54
Telerik UI for Xamarin

For more details please check the Xamarin.iOS Wrappers article.


 

See Also
 System Requirements
 Getting Started on Windows
 Getting Started on Mac

55
Telerik UI for Xamarin

License Agreement
 

The End User License Agreement for Telerik UI for Xamarin can be found on the following page:
https://www.telerik.com/purchase/license-agreement/ui-for-xamarin.

56
Telerik UI for Xamarin

Copyright
© Progress Software Corporation and/or one of its subsidiaries or affiliates. All rights reserved.

These materials and all Progress® software products are copyrighted and all rights are reserved by
Progress Software Corporation. The information in these materials is subject to change without
notice, and Progress Software Corporation assumes no responsibility for any errors that may appear
therein. The references in these materials to specific platforms supported are subject to change.

Business Making Progress, Corticon, DataDirect (and design), DataDirect Cloud, DataDirect
Connect, DataDirect Connect64, DataDirect XML Converters, DataDirect XQuery, Deliver More
Than Expected, Icenium, Kendo UI, Making Software Work Together, NativeScript, OpenEdge,
Powered by Progress, Progress, Progress Software Business Making Progress, Progress Software
Developers Network, Rollbase, RulesCloud, RulesWorld, SequeLink, Sitefinity (and Design),
SpeedScript, Stylus Studio, TeamPulse, Telerik, Telerik (and Design), Test Studio, and WebSpeed
are registered trademarks of Progress Software Corporation or one of its affiliates or subsidiaries in
the U.S. and/or other countries. AccelEvent, AppsAlive, AppServer, BravePoint, BusinessEdge,
DataDirect Spy, DataDirect SupportLink, Future Proof, High Performance Integration, OpenAccess,
ProDataSet, Progress Arcade, Progress Profiles, Progress Results, Progress RFID, Progress
Software, ProVision, PSE Pro, SectorAlliance, Sitefinity, SmartBrowser, SmartComponent,
SmartDataBrowser, SmartDataObjects, SmartDataView, SmartDialog, SmartFolder, SmartFrame,
SmartObjects, SmartPanel, SmartQuery, SmartViewer, SmartWindow, WebClient, and Who Makes
Progress are trademarks or service marks of Progress Software Corporation and/or its subsidiaries
or affiliates in the U.S. and other countries. Java is a registered trademark of Oracle and/or its
affiliates. Any other marks contained herein may be trademarks of their respective owners.

Please refer to the Release Notes applicable to the particular Progress product release for any
third-party acknowledgements required to be provided in the documentation associated with the
Progress product.

57
Telerik UI for Xamarin

Personal Data Collection


How personal data is used by Telerik Products
Telerik UI for Xamarin uses your account details, email address and a product usage data to better
understand customer experience allowing us to focus development efforts on the products and
features that matter most to our customers. Additionally, this information may be used by Marketing
and / or Sales to ensure you receive relevant content updates, product news and materials to ensure
your success with our products. Please see our Privacy Policy for more details.

This information is for our own purposes and we do not sell or otherwise provide this information to
any third-parties for a commercial purpose.

How I can see what data about me is stored?


You can see the information stored for your account by sending request to us via the following form
GDPR Data Subject Access Rights Request.

How I can delete the data stored about me?


You can request deletion of the information stored for your account by sending request to us via the
following form GDPR Data Subject Access Rights Request.

58
Telerik UI for Xamarin

System Requirements for Telerik UI for


Xamarin
In order to develop applications with Telerik UI for Xamarin you need to have the following
development tools installed:

Windows
 Windows 10 is required to develop for Xamarin.Forms.
 Visual Studio 2022 Preview with Xamarin installed. Go to Visual Studio Downloads page to
see the available download options.To install Xamarin for Visual Studio 2022, you would
need to enable Mobile development with .NET workload. Universal Windows Platform
development workload would be needed as well if you'd like to target UWP.
 If you run a fresh installation of Visual Studio, you will be prompted to select workloads
during the installation process.
 if you already have Visual Studio installed, you could modify the active workloads by
re-running the Visual Studio installer and selecting "Modify" option.
 Visual Studio 2019 with Xamarin installed. Go to Visual Studio Downloads page to see the
available download options.

To install Xamarin for Visual Studio 2019, you would need to enable Mobile development
with .NET workload. Universal Windows Platform development workload would be needed
as well if you'd like to target UWP.

 If you run a fresh installation of Visual Studio, you will be prompted to select workloads
during the installation process.
 if you already have Visual Studio installed, you could modify the active workloads by
re-running the Visual Studio installer and selecting "Modify" option.

Figure 1: VS 2019 with Mobile development with .NET workload enabled

59
Telerik UI for Xamarin

Before proceeding, please make sure the following Individual components are included:
 
If you use Telerik UI for Xamarin version older than R2 2019, the .NET Portable Library
Targeting Pack individual component is also required to successfully install and build with
our Xamarin controls.
 
For more detailed instructions go to Installing Xamarin in Visual Studio on Windows topic in
Xamarin documentation.
 

 For building iOS apps - configured iOS build host.

macOS
You will be able to develop Android and iOS apps. The iOS apps will require iOS 8 and higher.
Windows apps are not supported on macOS.

 macOS High Sierra 10.13 or higher.


 Visual Studio for Mac with Xamarin installed.

Visual Studio for Mac installer inspects your system and verifies which components are
installed and which need to be updated. In order to make sure Xamarin is installed, you
would need to run the VS for Mac installer and check whether Android and iOS options are
enabled.

Figure 3: VS for Mac with Android and iOS platforms enabled

60
Telerik UI for Xamarin

For more information go to Setup and Install Visual Studio for Mac topic.
 

 XCode 8.3 or higher.

Xamarin.Forms reference
The minimum required version of Xamarin.Forms package is 5.0.0.2083.

The Android project requires multiple packages with specific versions. The Xamarin.Forms package
will install most of the required packages as its dependencies. You can then go to Required Android
Support Libraries article and check if you have all required files and versions.
 

Supported mobile versions


You can use Telerik UI for Xamarin for application development for the following mobile operating
systems:

Platform Supported version


Android 5.0 (API Level 21) or higher
iOS 7.0 or higher

61
Telerik UI for Xamarin

Windows Windows 10

Next Steps
 Using Telerik UI for Xamarin on Windows
 Using Telerik UI for Xamarin on Mac

62
Telerik UI for Xamarin

Download Product Files


When you have an active trial or developer license, you can download the following files:

 Standalone installation
 Assemblies for manual installation
 NuGet packages
 Old versions

You can enable a free trial license from the Telerik UI for Xamarin product page.
 
In order to download these you need to take the following steps:

1. Log into your Telerik account.

2. Click on the Downloads tab:

3. Select Telerik UI for Xamarin product title:

4. The next page allows you to download the Automatic Installation msi file, DLLs and NuGet
Packages.

63
Telerik UI for Xamarin

Below you could find a list of the available files:

[license] could be Trial or Dev depending on the license you have.

[version] is replaced with the version the file corresponds to.

Installation

 Telerik_UI_for_Xamarin_[version]_[license].zip - contains binaries, VSExtensions and


examples used for manual installation.
 Telerik_UI_for_Xamarin_[version]_[license].msi - runnable msi file used for automatic
installation (for use on PC).
 Telerik_UI_for_Xamarin_[version]_[license].pkg - runnable pkg file used for automatic
installation (for use on Mac).

Other Setup Files

 Telerik_UI_for_Xamarin_[version]_[license]_Hotfix.zip - the Hotfix archive is a bare-bones


upgrade option for the Telerik Xamarin controls - it contains only those files that you need to
replace in your project to upgrade to a newer version.
 Telerik_UI_for_Xamarin_[version]_[license]_ProjectTemplate.mpack - a Visual Studio for
Mac add-in which provides a project template, pre-setup with all requirements to run Telerik
UI for Xamarin components.

And we provide the following NuGet packages you can use according to the concrete requirements:

64
Telerik UI for Xamarin

 Telerik_UI_for_Xamarin_[version]_[license]_NuGet_Separate_Packages.zip
 Telerik.UI.for.Xamarin.[version].nupkg
 Telerik.UI.for.Xamarin.Lite[version].nupkg

You could take a look at the Lite Assemblies topic for more details on the difference between lite and
standard assemblies.
 

See Also
 Getting started on Windows
 Getting started on Mac

65
Telerik UI for Xamarin

Using Telerik UI for Xamarin on Windows


This article aims to help you set up your application to use Telerik UI for Xamarin suite on Windows
OS.

Please, make sure you have already read the System Requirements article before you proceed.
 

1. Start with Xamarin.Forms app


Depending on your scenario, you either have an existing app where you will add our components, or
you have to create a new blank app.

Add Telerik components to an already existing app


You can manually reference the Telerik UI for Xamarin assemblies in each of the projects
(Xamarin.Forms, Android, iOS, UWP) or use the Telerik Nuget packages. For detailed instructions,
go to Step 2: Add references to Telerik Components.

Create a new app with Telerik UI for Xamarin


If you just start your app, you have two options:

 Use our Project Wizard to create a project that has everything setup for you. You can start
using our components right away without manually adding required assemblies and
modifying solution files.

We strongly recommend using the Project Wizard. If you choose this option, you can skip the
next steps in this article and jump directly to the Getting Started topic of any control.
 

 Create a new Xamarin.Forms app in Visual Studio and add the required references to Telerik
assemblies.

If your scenario requires creating a new app from scratch, please proceed following the steps
below:

1. Create a new solution using the Mobile App (Xamarin.Forms) template:

66
Telerik UI for Xamarin

2. In the next screen you could set Project name and location as well as choose the
Xamarin.Forms template and platforms your app will target:

67
Telerik UI for Xamarin

Typically, the solution can contain the following projects:

 .NET Standard: Cross platform application library that contains the shared code and
UI.
 Android: Available on all operation systems.
 UWP: Available only for projects created with Visual Studio.
 iOS:
 Available for MacOS.
 If you wish to use Visual Studio as a development environment you will also need
a mac machine. You can find more information how to set up your environment
here: Introduction to Xamarin.iOS for Visual Studio

The minimum required version of Xamarin.Forms package is 4.6.0.726.


 
The Android project requires multiple packages with specific versions. The Xamarin.Forms package
will install most of the required packages as its dependencies. You can then go to Required Android
Support Libraries article and check if you have all required files and versions.
 

2. Add references to Telerik Components


You have two options:

Telerik NuGet package server


You can use our Telerik NuGet package server to include our suite in your solution and/or update to
the latest available version.

Manually add required assemblies


If you prefer to manually reference the required Telerik UI for Xamarin assemblies into your solution,
you can get them in the following ways:

 Through the MSI installation - in this case after installing Telerik UI for Xamarin on your
machine, you can find the assemblies in the following default folder: C:\Program
Files\Progress\ or C:\Program Files (x86)\Progress\ for a 64bit machine;
 Download a ZIP file containing all the assemblies, for more details on this go to Download
Product Files topic. You can then unzip the file to any location on your machine and reference
the assemblies from that location.

If you're planning to use only a few components, you can add references to part of the assemblies.
There is a special section in each control documentation that lists all the required assemblies. The
section is called "Adding the required Telerik references" and is located in the Getting Started article
for each control.

As some of the controls included in Telerik UI for Xamarin suite rely on the SkiaSharp rendering
library, you should either install SkiaSharp.Views.Forms in all projects included in the Xamarin
solution (portable, android, ios, etc.) or in case you do not intend to use any of the Skia-dependent
components (Gauges, Rating, BusyIndicator), you could reference the Lite assemblies.

68
Telerik UI for Xamarin

See Also
 System Requirements
 Project Wizard
 Telerik NuGet packages server

69
Telerik UI for Xamarin

Installing Telerik UI for Xamarin from MSI


file
To install Telerik UI for Xamarin on your machine from the Windows Installer MSI file, follow the
instructions below:

Please, make sure you have already read the System Requirements article before you proceed.
 

1. Go to the Telerik UI for Xamarin download page following the instructions in Download
Product Files topic.
2. Download the automatic installation (MSI) file.
3. Once the download completes, run the MSI file and follow the instructions. On a 32bit
machine the wizard will install the UI for Xamarin component in the following folder unless
you specify otherwise: C:\Program Files\Telerik\ or C:\Program Files (x86)\Telerik\ for a 64bit
machine.

If you prefer using the ZIP file with the dlls instead of the automatic installation you can download it
from the Telerik UI for Xamarin product download page.
 

Exploring the installation folder

If you open the installation folder you will probably note the following sub directories:

 Binaries
 Examples - here you can find the SDK Browser application as well as sample applications
demonstrating our controls for Xamarin.Android and Xamarin.iOS.
 LicenseAgreements - provides the product EULA.
 QSF - includes the full source of Telerik UI for Xamarin Samples Application.
 VSExtensions - includes our Visual Studio Extension package. For more details go to Visual
Studio Extensions topic.

Binaries folder contains all the Telerik UI for Xamarin assemblies grouped in folders according to the
target project they should be added to. Check the exact structure in the image below:

70
Telerik UI for Xamarin

Next Steps

 Using project wizard for Visual Studio


 Getting started on Windows
 Getting started on Mac
 UI for Xamarin Support and Learning Resources

71
Telerik UI for Xamarin

Major and Minor Releases Installation


 

Telerik® UI for Xamarin has two types of official releases – major and minor releases. Examples of
major releases are R1 2019, R3 2019 and examples of minor releases are R1 2019 SP1, R2 2019
SP1 and R3 2019 SP1. Both major and minor releases are distributed as msi installation package
which follows certain upgrade logic explained below.

First, major releases can be installed in parallel on the same machine. This means that when you
install new major release it doesn’t uninstall your existing major releases. An example is that you can
have R1 2019, R2 2019 and R3 2019 installed at the same time.

Minor releases, on the other hand, can’t be installed in parallel when they are from the same major
release. This means that when you install a newer minor release it will automatically uninstall the
previous version minor release which is from the same major release. An example is that if there are
two minor releases for the same major release e.g. R2 2019 SP1 and R2 2019 SP2 for the R2 2019
release then you can have only one of the specified versions.

Here are some sample scenarios:

 Parallel major releases


1. Install R2 2018
2. Install R3 2018
3. Install R1 2019

Result: all three versions (R2 2018, R3 2018 and R1 2019) are installed in parallel on the
machine.

 Minor releases from the same major release


1. Install R2 2019
2. Install R2 2019 SP1
3. Install R2 2019 SP2

Result: only the latest version (R2 2019 SP2) is installed on the machine.

 Minor releases from different major releases


1. Install R1 2018
2. Install R1 2018 SP1
3. Install R3 2018 SP1

Result: R3 2018 SP1 and R1 2018 SP1 are installed on the machine.

Part of the Telerik® UI for Xamarin are the Visual Studio Extensions. Since the Visual Studio
Extensions integrate into the Visual Studio IDE they don’t support parallel versions. When newer
version is installed regardless of its type (major/minor) the Visual Studio Extensions get updated to
the newer version.
 

72
Telerik UI for Xamarin

Visual Studio Extensions


Visual Studio Extensions for Telerik UI for Xamarin aim to help developers when creating Xamarin
Application with Telerik Xamarin components.

The extensions handle the following major points in the development with Telerik UI for Xamarin:

 Project creation: Through the Project Wizard for Visual Studio you can quickly create an
application pre-configured to use Telerik UI for Xamarin;
 Toolbox support: Telerik UI for Xamarin Toolbox will ease the process of adding Telerik
controls to your Xamarin.Forms application.
 Common scenarios creation: VSExtensions includes several predefined item templates for
Visual Studio, such as Login and Feedback screens, that will simplify development for
commonly used application UI.

Installing VSExtensions
Visual Studio Extensions for Telerik UI for Xamarin are distributed with the Telerik UI for Xamarin
MSI installation. They can be downloaded and installed as separate product from the Visual Studio
Marketplace for Visual Studio 2019 and 2022 Preview.

Telerik UI for Xamarin Extension for Visual Studio is available for Visual Studio 2022 Current, Visual
Studio 2022 Preview and Visual Studio 2019
 
Below you can find more details on both options:

 Telerik UI for Xamatin installer: If you install the Telerik Xamarin suite through the MSI
automatic installation, you will be prompted to install the extensions automatically;
 Visual Studio Marketplace: You can download the Telerik Xamarin VSExtensions from within
Visual Studio:
1. Go to Extensions/Manage Extensions menu item in VS 2019 and select Online->Visual
Studio Marketplace section;
2. Search for "Telerik Xamarin":

73
Telerik UI for Xamarin

3. Download "Telerik Xamarin VSExtensions";


4. After the installation is complete, it will be present in the "Installed" section in Visual
Studio:

Either way you choose, after installing Telerik Xamarin VSExtensions, a Telerik menu (under
Extensions menu item) will be available in Visual Studio with several links that will help you quickly
navigate to various useful resources:

74
Telerik UI for Xamarin

VSExtensions Options
The Visual Studio Extensions options dialog provides settings, so you can configure the Telerik
Visual Studio Extensions to best suit your needs.

It can be accessed through the Telerik menu in Visual Studio (under Extensions menu item) ->
VSExtensions Options…

or from the Visual Studio Options Dialog -> Tools -> Options -> Telerik

75
Telerik UI for Xamarin

The Options dialog contains two sets of options that affect the Telerik UI for Xamarin.

The settings under the General category affect all of the installed Telerik Visual Studio Extensions.

76
Telerik UI for Xamarin

 Project Setup
 Copy referenced assemblies to solution and integrate with source control: When
enabled, the referenced assemblies will be copied to the solution when using Telerik
wizard.
 Project Upgrade Notifications for Detected Local Distributions
 Suggest project upgrades for Telerik product version available on my computer: When
enabled, you will be prompted to upgrade upon opening a project, which is not using the
latest version of Telerik UI installed on your system;
 Suggest upgrades when an equal Dev release is detected on projects using a Trial:
When enabled, you will be prompted to upgrade if a licensed version of Telerik UI for
Xamarin is available on your system, but the current project uses a trial version.
 Download Location: Configures the path where the extensions look for and store
distributions.

All settings under the Telerik UI for Xamarin category affect only the respective product.

 Latest Version Retrieval: When enabled, the Latest Version Acquirer tool will retrieve internal
builds as well as official releases when checking for a new version.
 Notifications: When enabled, you will receive notifications if a new version of Telerik UI for
Xamarin is available on the Telerik website.

Troubleshooting
Missing Telerik menu in Visual Studio

77
Telerik UI for Xamarin

Reason:

Telerik Visual Studio Extensions are disabled or not installed correctly.

Suggested solution 1 (Extension is Disabled):

1. Open Visual Studio


2. Go to menu Extensions -> Manage Extensions (for Visual Studio 2017 - Tools -> Extensions
and Updates...)
3. Open the Installed tab on the left
4. Search for Telerik Xamarin VSExtensions and make sure it's Enabled

Suggested solution 2 (Extension is not installed):

1. Open Visual Studio


2. Go to menu Extensions -> Manage Extensions (for Visual Studio 2017 - Tools -> Extensions
and Updates...)
3. Open the Online tab on the left
4. Search for Telerik Xamarin VSExtensions
5. Download and install the extensions

If the article does not help in solving your problem, please follow these steps to generate a Visual
Studio ActivityLog file before contacting our support:
 

Visual Studio Support is Disabled

Your Visual Studio installation needs to have both the Mobile Development with .NET workload and
the Text Template Transformation installed. you can find the Text Template Transformation option
under the Additional Components tab in the Visual Studio Installer.

See Also
 Project Wizard
 Telerik UI for Xamarin Toolbox
 Visual Studio Item Templates

78
Telerik UI for Xamarin

Project Wizard
This article introduces the Telerik UI for Xamarin.Forms Project Wizard. The Project Wizard is a
Visual Studio extension that improves the getting started experience for Telerik customers.

It allows customers to select which platform(s) their application targets and the wizard will
automatically reference all required Telerik binaries and packages.

Installing the Project Wizard


In order to have access to the Project Wizard to Visual Studio, you need to install the Visual Studio
Extensions that is shipped with the default installation of the Telerik UI for Xamarin suite. It can also
be downloaded and installed as separate product from the Visual Studio Marketplace for Visual
Studio 2017/2019.

For detailed information on installing the Project Wizard, go to Installing VSExtensions topic.
 

79
Telerik UI for Xamarin

New Project
In order to create a new solution using the Project Wizard customers should open the New Project
dialog window of Visual Studio.

Next users should navigate to Templates -> Visual C# section and the Telerik UI for Xamarin.Forms
Project Wizard will be listed there.

80
Telerik UI for Xamarin

Find the template and click OK. This will invoke the Project Wizard. Make your choice and click
Finish. Wait until Visual Studio prepares all the projects for you. After the solution is created it should
be rebuilt in order to update the Xamarin.Forms NuGet packages.

81
Telerik UI for Xamarin

After rebuilding the solution all packages and binaries will be updated and users will be ready to
choose a startup project and deploy it to the targeted platform.

See Also
 Visual Studio Item Templates
 Telerik NuGet Server

82
Telerik UI for Xamarin

 Required Android Support Libraries

83
Telerik UI for Xamarin

Telerik UI for Xamarin Toolbox


This article introduces Telerik UI for Xamarin Toolbox for Visual Studio, which eases the process of
adding Telerik controls to your Xamarin.Forms application. The Xamarin Toolbox is part of the Visual
Studio Extensions for Telerik UI for Xamarin.

Telerik UI for Xamarin Visual Studio Extensions are distributed with the Telerik UI for Xamarin MSI
installation. You can also download and install them as a separate product from the Visual Studio
Marketplace for Visual Studio 2017/2019.

For detailed instructions on how to install the Visual Studio Extensions, see Installing VSExtensions.
 

Showing the Telerik Toolbox


Visual Studio 2019
To show the Toolbox and start using the controls, navigate to the tab "Extensions" -> "Telerik" ->
"Telerik UI for Xamarin" -> "Open Telerik UI for Xamarin Toolbox" within Visual Studio. You can also
find this option when you type "Telerik UI for Xamarin Toolbox" in the Quick Launch search field (top
right corner in Visual Studio).

Figure 1 shows where you can find the option in Visual Studio 2019:

Figure 1: Showing the Telerik UI for Xamarin Toolbox in Visual Studio 2019

Visual Studio 2017


To show the Toolbox and start using the controls, navigate to the tab "Telerik" -> "Telerik UI for
Xamarin" -> "Open Telerik UI for Xamarin Toolbox" within Visual Studio. You can also find this option
when you type "Telerik UI for Xamarin Toolbox" in the Quick Launch search field (top right corner in
Visual Studio).

Figure 2 shows where you can find the option in Visual Studio 2017:

84
Telerik UI for Xamarin

Figure 2: Showing the Telerik UI for Xamarin Toolbox in Visual Studio 2017

When you open the Telerik UI for Xamarin Toolbox, you will see a window with the different controls
from the suite. Figure 3 shows the appearance of the toolbox in a correctly configured project.

If no usable controls are present in the toolbox, make sure that you added all the required references,
and try to rebuild your project.
 

Adding Controls to Your Project


Embedding the controls from the suite is made as easy as possible. All you need to do is simply drag
one of the controls within your XAML file. This adds the control definition and maps the needed
namespace declarations. Figure 3 shows how to perform this action.

Figure 2: Adding Telerik controls to your application

See Also
 Installing VSExtensions
 MSI installation
 Project Wizard

85
Telerik UI for Xamarin

Visual Studio Item Templates


Currently Item Templates are available only for Visual Studio on Windows.
 
There are several predefined item templates for Visual Studio included in the UI for Xamarin suite
which come by default with the installation of the product. You can directly include them in your
Xamarin Forms project and use them as footprints for similar scenarios in your application. This
article provides more information on the different templates included and the controls which they
utilize.

The Item Templates are installed through a Visual Studio extension file(vsix) which can be found in
the VSExtensions folder of your local installation.
 

Adding Item Templates to your project


As these item templates will be automatically added when you run the UI for Xamarin installation,
you can find them when you try adding a new item to your Xamarin Forms project, as shown in
Figure 1.

Figure 1: Adding a custom item to your Xamarin Forms project

86
Telerik UI for Xamarin

You can also add them through the Telerik menu of Visual Studio as shown in Figure 2:

Figure 2: Adding a custom item to your Xamarin Forms project through Telerik menu:

Or through the context menu of your Visual Studio project:

Figure 3: Adding a custom item to your Xamarin Forms project through the context menu:

87
Telerik UI for Xamarin

Views
The available item templates are listed below:

 Stocks View
 Activity View
 Search View
 Login Screen
 Feedback Screen

Stocks View
The Stocks View represents a list of several companies and information related to their stocks such
as current price, trends, percentage difference, etc. The main controls which are utilized are the
RadListView and RadCartesianChart controls. Figure 2 shows the default appearance of the view.

Figure 4: Stocks View's default appearance

88
Telerik UI for Xamarin

Activity View
The Activity View provides an information regarding a specific user and information regarding his
daily physical activity such as calories burned, average steps and active time. The view utilizes the
RadCartesianChart, RadRadialGauge and RadHorizontalGauge controls. Figure 3 shows the default
appearance of the Activity View:

Figure 5: Activity View's default appearance

89
Telerik UI for Xamarin

Search View
There are several Search View custom items which show the same setup with a slightly different
visualization. All of the item templates use the RadAutoComplete and RadListView controls with
different modifications in order to achieve a diverse look. The RadAutoComplete control is used to
filter the visible collection according to a certain user input.

Multiline Items

In the SearchViewMultiLineItems template, the items within the RadListView have multiple line
description.

Figure 6: Search View Multiline Items

90
Telerik UI for Xamarin

Singleline Items

In the SearchViewSingleLineItems template, only a single line of information regarding the specific
item is present.

Figure 7: Search View Singleline Items

91
Telerik UI for Xamarin

Singleline Items Big Image

The SearchViewSingleLineItemsBigImage template is similar to the SearchViewSingleLineItems


template, however, the look of the item within the RadListView is slightly tweaked for a distinctive
appearance that emphasizes on the image.

Figure 8: Search View Singleline Items Big Image

Twoline Items

The SearchViewTwoLinesItems template once again shows a different approach of modifying


RadListView's ItemTemplate.

Figure 9: Search View Twolines Items

92
Telerik UI for Xamarin

Login Screen
The Login Screen templates provide various options for entering user credentials, such as with
fingerprint, with pin or integrating a social login. There are 5 different scenarios available, so you
could choose the one that best suits your requirements. The templates use RadEntry, RadButton,
RadBorder, and RadCheckBox components from Progress Telerik UI for Xamarin.

The image below shows LoginComplete template:

Figure 10: Login Complete Screen

93
Telerik UI for Xamarin

Feedback Screen
The Feedback Screen template implements a feedback scenario for receiving comments, notes or
recommendations (and attachments) from the end users regarding the app. The template uses
RadBorder, RadButton and RadListView from Progress Telerik UI for Xamarin.

Figure 11: Feedback Screen

94
Telerik UI for Xamarin

See Also
 System Requirements
 Getting Started on Windows
 Getting Started on Mac

95
Telerik UI for Xamarin

Using Telerik UI for Xamarin on Mac


This article aims to help you set up your application to use Telerik UI for Xamarin suite on Mac OS.

Please, make sure you have already read the System Requirements article before you proceed.
 

1. Start with Xamarin.Forms app


Depending on your scenario, you either have an existing app where you will add our components, or
you have to create a new blank app.

Add Telerik components to an already existing app


You can manually reference the Telerik UI for Xamarin assemblies in each of the projects
(Xamarin.Forms, Android, iOS) or use the Telerik Nuget packages. For detailed instructions, go to
Step 3: Add references to Telerik Components.

Create a new app with Telerik UI for Xamarin


If you just start your app, you have two options:

 Use our Project Wizard to create a project that has everything setup for you. You can start
using our components right away without manually adding required assemblies and
modifying solution files.

We strongly recommend using the Project Wizard. If you choose this option, you can skip the
next steps in this article and jump directly to the Getting Started topic of any control.
 

 Create a new Xamarin.Forms app in Visual Studio for Mac and add the required references
to Telerik assemblies.

If your scenario requires creating a new app from scratch, please proceed following the steps
below:

1. Open Visual Studio for Mac, then create new project from the Multiplatform section select
App -> Xamarin.Forms -> Blank Forms App:

96
Telerik UI for Xamarin

2. In the next screen you could set App name. Organization Identifier, Target Platforms:

97
Telerik UI for Xamarin

3. Follow the steps in the wizard until your app is created. It should contain the following
projects:

2. Getting the latest platform SDK versions


Make sure that your Xamarin.Forms packages are up to date.

You can either use the Visual Studio UI to update all packages to the required versions, or you can
do it manually by editing the .csproj file in each project.

Update packages using Visual Studio UI


You have to make sure that you have the right version of Xamarin and all related packages.
 
To update specific package to the latest version, right-click on it and select "Update to ...":

98
Telerik UI for Xamarin

If your application requires specific version of a package, you can right-click directly on the packages
folder and choose "Manage NuGet Packages...". This will work even if newer version of the package
is already added.

You have to search for the package and select the correct version:

The minimum required version of Xamarin.Forms package is 4.6.0.726.


 
The Android project requires multiple packages with specific versions. The Xamarin.Forms package

99
Telerik UI for Xamarin

will install most of the required packages as its dependencies. You can then go to Required Android
Support Libraries article and check if you have all required files and versions.
 

3. Add references to Telerik Components


You have two options:

Telerik NuGet package server


You can use our Telerik NuGet package server to include our suite in your solution and/or update to
the latest available version.

Manually add required assemblies


If you prefer to manually reference the required Telerik UI for Xamarin assemblies into your solution,
you can get them in the following ways:

 Download the .pkg file, then install it on the Mac machine. After successful installation you will
get the following screen:

When the installation is completed the assemblies can be found in the Binaries folder.

100
Telerik UI for Xamarin

 Download a ZIP file containing all the assemblies, for more details on this go to Download
Product Files topic. You can then unzip the file to any location on your machine and reference
the assemblies from that location.

Exploring the installation folder

If you open the installation folder you will probably note the following sub directories:

 Binaries
 Examples - here you can find the SDK Browser application as well as sample applications
demonstrating our controls for Xamarin.Android and Xamarin.iOS.
 LicenseAgreements - provides the product EULA.
 QSF - includes the full source of Telerik UI for Xamarin Samples Application.
 VSExtensions - includes our Visual Studio Extension package. For more details go to Visual
Studio Extensions topic.

If you're planning to use only a few components, you can add references to part of the assemblies.
There is a special section in each control documentation that lists all the required assemblies. The
section is called "Adding the required Telerik references" and is located in the Getting Started article
for each control.
 
As some of the controls included in Telerik UI for Xamarin suite rely on the SkiaSharp rendering
library, you should either install SkiaSharp.Views.Forms in all projects included in the Xamarin
solution (portable, android, ios, etc.) or in case you do not intend to use any of the Skia-dependent
components (Gauges, Rating, BusyIndicator), you could reference the Lite assemblies.
 

101
Telerik UI for Xamarin

See Also
 System Requirements
 Telerik NuGet packages server
 Project Wizard for Visual Studio for Mac

102
Telerik UI for Xamarin

Project Wizard for Visual Studio for Mac


This article introduces the Telerik UI for Xamarin.Forms Project Wizard for Visual Studio for Mac.
The project wizard is a Visual Studio add-in that improves the getting started experience for Telerik
customers. It provides a project template that is pre-setup with all requirements to run our
components so the customers can start writing their apps right away.

Installation
First, you have to download the ProjectTemplateXamarin.mpack file from the Telerik UI for Xamarin
product download page inside your Telerik account. Go to Download Product Files for exact steps on
how to navigate to the download page.

Then, you have to install the project wizard add-in package. Open the Visual Studio Extension
Manager and select the Install form file... option. Figure 1 shows how to access the Extension
Manager.

Figure 1: Accessing Visual Studio Extensions

Once you have accessed the Extension Manager, the following dialog will appear and you should
look for the Install from file option.

Figure 2: Reaching the Extension Manager

103
Telerik UI for Xamarin

Navigate to the ProjectTemplateXamarin.mpack file.

Figure 3: The ProjectTemplate location

104
Telerik UI for Xamarin

If the add-in is successfully added to Visual Studio, you should see it in the IDE extensions section.

Restart Visual Studio for Mac to complete the installation.

New Telerik Xamarin UI Application


Now you can create a new project using the Telerik Project Template.

Figure 4: Create New Project Dialog

105
Telerik UI for Xamarin

The Telerik Xamarin UI Application template can be found in Other > .NET section.

Figure 5: Telerik Xamarin UI Application template

106
Telerik UI for Xamarin

Follow the steps to setup your app.

When you are done the project will contain all required packages and binaries and you can start
writing your app right away.

See Also
 System Requirements
 Getting Started on Mac
 Required Android Support Libraries

107
Telerik UI for Xamarin

Telerik Xamarin.Forms Toolbox Extension


for Mac
This article introduces TelerikXamarinForms Toolbox for Visual Studio for Mac which will ease the
process of adding Telerik controls to your Xamarin.Forms application on Mac.

In order to use the TelerikXamarinForms Toolbox, first you have to install the Project Wizard for
Visual Studio for Mac. In short you will need to download the ProjectTemplate.mpack file from the
Telerik UI for Xamarin download page inside your Telerik account and install it through the Visual
Studio Extension Manager.

For more details on adding the Telerik UI for Xamarin ProjectTemplate.mpack file check the article
about Project Wizard for Visual Studio for Mac.
 

Showing the Telerik Toolbox


In order to show the Toolbox and start using the controls, you should navigate to the MainPage.xaml
file in your project and click on it. If the ProjectTemplate.mpack file is installed successfully, Toolbox
window is visible in the project when you click on the MainPage.xaml file (or any other XAML file
inside your project). You can also find this option when typing “Toolbox” in the Search filed (top right
corner in Visual Studio for Mac).

Figure 1 and Figure 2 shows where you can find the options in Visual Studio for Mac:

Figure 1: Showing the TelerikXamarinForms Toolbox when clicking on MainPage.xaml

108
Telerik UI for Xamarin

Figure 2: Showing the TelerikXamarinForms Toolbox from Search field

Once you have clicked the option you should be prompted to the window which contains the different
controls from the suite. Figure 1 and Figure 2 shows the appearance of the toolbox if everything is
correctly set.

109
Telerik UI for Xamarin

If no usable controls are present in the toolbox - make sure all the required references are added
and try rebuilding your project.
 

Adding Controls to Your Project


Embedding the controls from the suite is made as easy as possible and all you need to do is simply
drag one of the controls within your XAML file. This will add the control definition and will also map
the needed namespace declarations. Figure 3 shows how the action is performed.

Figure 3: Adding Telerik controls to your application

See Also
 Project Wizard for Visual Studio for Mac
 Telerik NuGet packages server

110
Telerik UI for Xamarin

Required AndroidX Packages


Since R3 2020
With R3 2020 release we have migrated our Xamarin.Android components, which serve as
foundation for some of our Xamarin.Forms controls to use AndroidX. This allows to use all the latest
development in Android extensions (AndroidX) along with our controls.

You can read more on AndroidX and Xamarin here:


https://docs.microsoft.com/en-us/xamarin/android/platform/androidx

 
The controls in the Telerik UI for Xamarin suite require specific AndroidX packages references inside
the Android project to render correctly on Android.

Here is a list of the required AndroidX packages:

 Xamarin.AndroidX.RecyclerView
 Xamarin.AndroidX.AppCompat.Resources
 Xamarin.AndroidX.Lifecycle.LiveData
 Xamarin.AndroidX.Browser
 Xamarin.AndroidX.Legacy.Support.V4
 Xamarin.Google.Android.Material
 Xamarin.AndroidX.Migration

In addition, the following reference is required in the Android project:

 Mono.Android.Export.dll

If the app targets Android9, Xamarin.AndroidX.Migration nuget package should be of version 1.0.6.1.
 

Requirements
Check below the requirements for using AndroidX in Xamarin-based apps:

 Visual Studio 2019 - On Windows update to Visual Studio 2019 version 16.4 or later. On
macOS, update to Visual Studio 2019 for Mac version 8.4 or later.
 Xamarin.Android - Xamarin.Android 10.0 or later must be installed with Visual Studio
(Xamarin.Android is automatically installed as part of the Mobile Development With .NET
workload on Windows and installed as part of the Visual Studio for Mac Installer)
 Java Developer Kit - Xamarin.Android 10.0 development requires JDK 8. Microsoft's
distribution of the OpenJDK is automatically installed as part of Visual Studio.
 Android SDK - Android SDK API 28 or higher must be installed via the Android SDK
Manager.

111
Telerik UI for Xamarin

R2 2020 and below


With releases prior to R3 2020 (R2 SP 2020, R2 2020, R1 2020, etc) the controls in the Telerik UI for
Xamarin suite require specific Xamarin Android Support Libraries to render correctly on Android.

Here are listed the common requirements for all Android projects that use our suite:

 The minimum required version of all Xamarin Android Support Libraries is 28.0.0.1.
 Here are listed all packages that come with the latest version of Xamarin.Forms, which also
have to be updated to version 28.0.0.1:
 Xamarin.Android.Support.v4
 Xamarin.Android.Support.Design
 Xamarin.Android.Support.v7.AppCompat
 Xamarin.Android.Support.v7.CardView
 Xamarin.Android.Support.v7.MediaRouter
 Xamarin.Android.Support.Vector.Drawable
 Xamarin.Android.Support.Animated.Vector.Drawable
 Xamarin.Android.Support.v7.RecyclerView (required by Telerik.Xamarin.Android.List.dll)
 Xamarin.Android.Support.v8.RenderScript (required by
Telerik.Xamarin.Android.Primitives.dll. only with R3 2018.3 or earlier)
 The target Android version of the Android project should be Android 8.1 (API level 27) or
greater. This could be modified from the project settings.
 The corresponding to the target Android version Android SDK has to be installed in order to
use the required support libraries (install from the Android SDK Manager).

See Also
 System Requirements
 Getting started on Windows
 Getting started on Mac

112
Telerik UI for Xamarin

Telerik NuGet Server


The following steps demonstrate how you can take advantage of Telerik NuGet server
https://nuget.telerik.com/v3/index.json in order to include Telerik UI for Xamarin suite in your solution
and/or update to the latest available version.

The credentials needed to access Telerik NuGet server are the same you use to log into your Telerik
account.
 
You will find NuGet packages containing the standard and the lite assemblies - the latter have Lite in
their names. Please take a look at the Lite Assemblies topic for more details on the difference
between them.
 

Visual Studio for Windows


The first step is to add the Telerik server to the NuGet package sources. This can be done in the
Package Manager Settings from the Tools menu.

In the the Package Sources section you can add new sources.

113
Telerik UI for Xamarin

In the Source field you should fill in the address of the Telerik server (URL:
https://nuget.telerik.com/v3/index.json) and click the Update button.

The old https://nuget.telerik.com/nuget server will be deprecated and we encourage our clients to
switch to the v3 API. The new v3 API is faster, lighter, and reduces the number of requests from
NuGet clients.
 

114
Telerik UI for Xamarin

The Telerik server is now ready to use. You can go to the solution and open the solution package
manager.

115
Telerik UI for Xamarin

Add Telerik UI for Xamarin pack in Visual Studio for Windows


You will have to find the Telerik.UI.for.Xamarin package and install it to your projects following these
steps:

1. Select the Telerik server as a package source and enter your credentials when prompted.
2. Search for the Telerik.UI.for.Xamarin package.
3. Select the package when found.
4. Select which projects will have the package installed.
5. Choose the desired version and click Install.

Now the solution has all required Telerik assemblies.

Visual Studio for Mac


You have to first add the Telerik NuGet server to the Visual Studio for Mac packages sources list.
This can be done by clicking on the solution folder in Visual Studio for Mac to display the context
menu and choose “Manage NuGet Packages…”.

116
Telerik UI for Xamarin

This will open another dialog. Choose “Configure Sources…” option from the dropdown in the lower
left corner.

117
Telerik UI for Xamarin

On the next dialog you can see all the available sources. Choose “Add” to add the new server.

118
Telerik UI for Xamarin

In the Add Package Source dialog you should fill in the information of the Telerik server (URL:
https://nuget.telerik.com/v3/index.json) as well as your private Telerik credentials. Authentication
procedure is required in order to allow downloading the packs.

The old https://nuget.telerik.com/nuget server will be deprecated and we encourage our clients to
switch to the v3 API. The new v3 API is faster, lighter, and reduces the number of requests from
NuGet clients.
 

119
Telerik UI for Xamarin

After the Telerik NuGet server is added you will be able to see the available for download packages
in the Manage NuGet Packages... dialog. This will allow you to check the Telerik UI for Xamarin pack
and add it into your projects.

Add Telerik UI for Xamarin pack in Visual Studio for Mac


Once the server is added you will be able to add to your projects any of the Telerik NuGet packages
available for your license. One click on the solution folder will open the context menu and will give
you the option to call the Manage NuGet Packages... dialog where the available Telerik packs will be
listed.

120
Telerik UI for Xamarin

After choosing Telerik UI for Xamarin package, you can apply it to all the projects in the solution:

121
Telerik UI for Xamarin

Troubleshooting
'401 Logon failed' error
If you're receiving this error when connecting to Telerik Nuget Server, you could try to update your
NuGet credentials through the Windows Credential Manager. Please follow the steps below:

1. Close all open Visual Studio instances (this is so that all NuGet package manager tasks are
stopped).
2. Open the "Credential Manager" app on your PC.
3. Scroll through all the entries until you find any that are for nuget.telerik.com.
4. Once you find that entry, expand it and select "edit".
5. Make sure the username and password are the same ones you use for your Telerik account
and clisk
1. Use the email address in the place of username
2. Make sure any special characters are escaped (see Handling Special Characters in
Password below)
3. Click "Save"
6. Make sure the URL does not have a trailing slash, it must be only
https://nuget.telerik.com/nuget

Now you can reopen Visual Studio and access the Telerik NuGet server.

Handling Special Characters in Password

If your password contains a special character, those characters need to be escaped or it may fail
authentication resulting in Error 401 login failure from the NuGet server. A common character that
needs to be escaped is the ampersand &, but it can be as unique as the section character §. There
are two ways to handle this.

1. Change the password so that it only includes characters that do not need to be escaped
2. HTML encode the password so the special characters are escaped (e.g.
my§uper&P@§§word becomes my&sect;uper&amp;P@&sect;&sect;word).

We strongly discourage entering your password into an online encoder utility, use Powershell
instead. Here's one example:

Add-Type -AssemblyName System.Web


[System.Web.HttpUtility]::HtmlEncode('my§uper&P@§§word')
 

Result:

122
Telerik UI for Xamarin

Networking Problems
Another common problem is that your machine (PC or DevOps agent) is behind a proxy. To check if
you're experiencing a networking issue, open the following URL in your web browser:

https://nuget.telerik.com/nuget/Search()?$filter=IsAbsoluteLatestVersion&searchTerm=%27Xamarin%27
&includePrerelease=true&$skip=0&$top=100&semVerLevel=2.0.0.

After you enter your Telerik.com username and password, you should see an XML search result
containing a list of all the Telerik.UI.for.Xamarin packages available with your license.

See Also
 System Requirements
 Getting Started on Windows
 Getting Started on Mac

123
Telerik UI for Xamarin

Latest Internal Builds


The Latest Internal Build (LIB) is a bi-weekly distribution of the Telerik UI for Xamarin assemblies,
built against the latest development environment. It contains all the newest bug fixes. And it is
released on a bi-weekly basis.

The purpose of the the latest internal build is to allow the users to test the latest bug fixes. So, if you
have experienced any problem with the current official distributions there is a possibility that the
issue has already been addressed in the latest internal build.

The LIBs are intended for development only and are not recommended for production purposes as
these distributions have not gone through the complete QA process.
 

How to Download LIB


You can download the LIB assemblies from your Telerik account.

1. Go to the Telerik UI for Xamarin download page following the instructions in Download
Product Files topic.
2. Click on the Latest internal build button. This will download an archive with the UI for
Xamarin assemblies:

To get a specific version of the LIB, open the Internal Builds tab on the Downloads page. And select
a version from the list.

124
Telerik UI for Xamarin

Installing LIB from NuGet


Latest Internal Builds are available for installing as a NuGet package as well.

 On Visual Studio you would need to check the Include prerelease option next to the search
box:

 On Visual Studio for Mac you should check the Show pre-release package option at the
bottom of the "Manage NuGet Packages" window:

125
Telerik UI for Xamarin

See Also
 System Requirements
 Download Product Files
 Telerik Nuget Server

126
Telerik UI for Xamarin

Lite vs Standard Assemblies


Some of the controls included in the Telerik UI for Xamarin suite(Gauges, Rating, BusyIndicator) rely
on the SkiaSharp rendering library. This is the reason а reference to it should be added when using
the standard Telerik UI for Xamarin libraries. However, in case you do not intend to use these
controls you can reference the binaries included in the Lite folder of your local installation. This will
eventually lead to lower size when deploying your application in the respective store. If you are using
NuGet as a package manager, you should install the .Lite package.

Тhe difference between the lite and standard binaries is that the former do not need the actual
SkiaSharp binary files to function as intended. Instead, they reference an empty assembly labeled
Telerik.XamarinForms.SkiaSharp.

If you need to include controls that rely on the SkiaSharp library and you are using the lite
assemblies, an InvalidReferenceException with the following message will be thrown: Missing
assembly reference. Please use the non-Light version of the assemblies/nuget packages. If you
come across this exception, please make sure that you have added references to the correct binary
files.
 

List of controls that utilize the SkiaSharp rendering library


The following controls rely on the SkiaSharp library to render some elements within their structure:

 RadBusyIndicator
 RadDataGrid
 RadGauge
 RadImageEditor
 RadMap
 RadPath
 RadPdfViewer
 RadRating
 RadRSignaturePad

If you intend on using these, you need to add reference to the relevant version of SkiaSharp,
SkiaSharp.Views and SkiaSharp.Views.Forms NuGet packages. In case you would like to not take
advantage of these elements, we advise on using the Lite assemblies so that no direct references to
SkiaSharp are required.

SkiaSharp NuGet Packages


The SkiaSharp packages that need to be installed are as follows:

 SkiaSharp (install to all projects)


 SkiaSharp.Views (install to all projects, except class library)
 SkiaSharp.Views.Forms (install to all projects)

127
Telerik UI for Xamarin

Minimum package version required is v1.68.0.


 

See Also
 Skia Graphics Library
 Telerik NuGet Server

128
Telerik UI for Xamarin

Upgrading on Windows
The purpose of this topic is to explain you how to upgrade Telerik UI for Xamarin from Trial to
Developer License or to a newer version on Windows.

There are two options for referencing Telerik components and the upgrade method depends on
which one you chose. Both are listed below:

 Upgrade using the Telerik NuGet server


 Upgrade manually added assemblies

Upgrade using the Telerik NuGet server


As a prerequisite, you would need to have Telerik NuGet packages server configured in Visual
Studio as described in the following topic: Telerik NuGet server.
 

1. Go to Visual Studio and open the solution package manager.

2. Select the Telerik server as a package source and enter their credentials when prompted.
3. Go to Installed tab and find Telerik.UI.for.Xamarin package.

129
Telerik UI for Xamarin

4. Select the package when found.


5. Select which projects will have the package installed.
6. Choose the desired version and click Install.

Upgrade manually added assemblies


In order to upgrade your controls to a newer version of the suite, you need to perform the following
instructions:

1. Download the installation method you prefer:


 MSI file for automatic installation.
 ZIP file for manual (advanced) installation - you can download the zip containing the dlls
from the Telerik UI for Xamarin product download page.
2. If you have installed the trial version of Telerik UI for Xamarin and try to install the developer
version of the same release, you will receive the following message:

So, you should remove the trial version first.

3. If the upgrade is major (i.e. from R3 2018 to R1 2019), check the Release History.

130
Telerik UI for Xamarin

4. Back up your application.


5. Update all the Telerik references in all projects (.Net Standard/Shared, Android, iOS, UWP)
in Visual Studio to point to the new assemblies.
6. Clean the solution.
7. Rebuild the projects.
8. Run the application.

Check the version of Telerik UI for Xamarin


Each version number of Telerik UI for Xamarin is formed depending on what major release that
version belongs to as well the source code build date. In other words, the version number
corresponds to the date when the dlls were built.

The following image shows the name of the build generated on 18th of March (3rd month), after the
R1 2019 release.

See Also
 System Requirements
 Telerik NuGet packages server

131
Telerik UI for Xamarin

Upgrading on Mac
The purpose of this topic is to explain you how to upgrade Telerik UI for Xamarin to a newer version
on Mac.

There are two options for referencing Telerik components and the upgrade method depends on
which one you chose. Both are listed below:

 Upgrade using the Telerik NuGet server


 Upgrade manually added assemblies

Upgrade using the Telerik NuGet server


As a prerequisite, you would need to have Telerik NuGet packages server configured in Visual
Studio for Mac as described in the following topic: Telerik NuGet server.
 

1. With the solution open in Visual Studio for Mac, for example go to the Android project and
expand Packages folder.
2. Find Telerik.UI.for.Xamarin package, right-click on it and select Update.

132
Telerik UI for Xamarin

This will update the Telerik UI for Xamarin package to the latest available version.

3. Do the same for all other projects in the solution that have references to Telerik UI for
Xamarin.

Upgrade manually added assemblies


In order to upgrade your controls to a newer version of the suite, you need to perform the following
instructions:

1. Download the installation method you prefer (pkg installation or zip file) from you Telerik
account, check Download Product Files for more details.
2. If the upgrade is major (i.e. from R3 2018 to R1 2019), check the Release History.
3. Back up your application.
4. Update all the Telerik references in all projects (.Net Standard/Shared, Android, iOS) in

133
Telerik UI for Xamarin

Visual Studio for Mac to point to the new assemblies.


5. Clean the solution.
6. Rebuild the projects.
7. Run the application.

See Also
 System Requirements
 Telerik NuGet packages server

134
Telerik UI for Xamarin

Overview
Telerik Accordion for Xamarin is a vertically collapsible content panel that displays only one of its
items at a time within the available space. RadAccordion helps you save screen space and at the
same time present the content to the end user in an easily accessible way.

Key features
 Collapsed/expanded states: RadAccordion consists of AccordionItems that can host any
content. The end users could show or hide this content by interacting with the headers of the
control. For more information in this go to Key Features topic in our documentation.
 Collapse All Items: You can allow the app users to fully collapse the Accordion through the
CanCollapseAllItems boolean property. To learn more about this, visit Key Features Collapse
All Items section.
 Highly customizable items: You have full control over the visual appearance of the Accordion
items - you can customize the border style of each item, the border style of items' headers,
as well as the indicator text, font, size, location and color. For more info on this check the
AccordionItem Control help article.
 Animation while expanding/collapsing: RadAccordion provides slick customizable animation
played while the expandable content is expanded/collapsed, for additional info go to Key
Features Animation section.
 Theming: RadAccordion comes with built-in theming support that allows you to easily build
slick interfaces with the look-and-feel of a predefined theme. To learn more about this go to
Theme Overview.

Check out RadAccordion Getting Started help article that shows how to use it in a basic scenario.
 

See Also
 Key Features

135
Telerik UI for Xamarin

 AccordionItem Control

136
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadAccordion control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadAccordion control

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadAccordion control you have to install the
Telerik.UI.for.Xamarin.Primitives nuget package. This nuget will automatically refer the
Telerik.UI.for.Xamarin.Common and Telerik.UI.for.Xamarin.SkiaSharp nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadAccordion component:

Platform Assemblies
Portable Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Android Telerik.Xamarin.Android.Common.dll
Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
UWP Telerik.Core.dll
Telerik.UI.Xaml.Primitives.UWP.dll
Telerik.XamarinForms.Common.dll

137
Telerik UI for Xamarin

Telerik.XamarinForms.Primitives.dll

3. Adding RadAccordion control


You could use one of the following approaches:

Drag the control from the Toolbox.

Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML or C#.

The snippet below shows a simple RadAccordion definition:

XAML
<telerikPrimitives:RadAccordion x:Name="accordion">
<telerikPrimitives:AccordionItem HeaderText="Attachments">
<telerikPrimitives:AccordionItem.Content>
<Label Text="Attach files" Margin="30" />
</telerikPrimitives:AccordionItem.Content>
</telerikPrimitives:AccordionItem>
<telerikPrimitives:AccordionItem HeaderText="Comments">
<telerikPrimitives:AccordionItem.Content>
<Label Text="Add your comment here" Margin="30" />
</telerikPrimitives:AccordionItem.Content>
</telerikPrimitives:AccordionItem>
<telerikPrimitives:AccordionItem HeaderText="Rating" IsExpanded="True">
<telerikPrimitives:AccordionItem.Content>
<telerikInput:RadShapeRating x:Name="rating" Margin="20"/>
</telerikPrimitives:AccordionItem.Content>
</telerikPrimitives:AccordionItem>
</telerikPrimitives:RadAccordion>
 

C#
var accordion = new RadAccordion();

var attachmentsSection = new AccordionItem { HeaderText = "Attachments" };


attachmentsSection.Content = new Label { Text = "Attach files", Margin = 30 };
accordion.Children.Add(attachmentsSection);

var commentsSection = new AccordionItem { HeaderText = "Comments" };


commentsSection.Content = new Label { Text = "Add your comment here", Margin = 30 };
accordion.Children.Add(commentsSection);

var ratingSection = new AccordionItem { IsExpanded = true, HeaderText = "Rating" };


ratingSection.Content = new RadShapeRating { Margin = 20 };

138
Telerik UI for Xamarin

accordion.Children.Add(ratingSection);
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

C#
using Telerik.XamarinForms.Primitives;
using Telerik.XamarinForms.Input;
 

This is the result:

SDK Browser and QSF applications contain different examples that show RadAccordion's main
features. You can find the applications in the Examples and QSF folders of your local Telerik UI for
Xamarin installation.
 

See Also
 Key Features
 Accordion Item Control

139
Telerik UI for Xamarin

Key Features
The purpose of this help article is to show you the key features of the RadAccordion control.

Collapsed/expanded States
In the Accordion control each item provides a header that expands when clicked, showing more
information. The control is designed in such a way that opening one AccordionItem automatically
closes the previously displayed content.

There can be only one expanded item at a time indicated by IsExpanded property of the
AccordionItem object.

Collapse All Items


Through CanCollapseAllItems boolean property you can allow users to fully collapse the Accordion
items. If CanCollapseAllItems is enabled, clicking on the header of an expanded Accordion item will
collapse it.

The option for collapsing all items is available with R1 2020 release of Telerik UI for Xamarin.
 

Animation while expanding/collapsing


To enable or disable the animation you need to use the IsAnimationEnabled property of
RadAccordion. By default, the Animation is enabled.

You could also customize the duration and easing through AnimationDuration and AnimationEasing
properties.

 AnimationDuration (int): Defines the duration of the animation while expanding/collapsing the
AccordionItem. The default value is 500.
 AnimationEasing (Xamarin.Forms.Easing): Specifies animation acceleration over time. The
default value is Easing.Linear.

Spacing between items


Through Spacing(double) property you could specify the distance between the Accordion items. The
default value is 0.

Example
The snippet below shows how the CanCollapseAllItems, AnimationDuration, AnimationEasing and
Spacing properties can be applied:

140
Telerik UI for Xamarin

XAML
<telerikPrimitives:RadAccordion CanCollapseAllItems="True"
AnimationDuration="1500"
AnimationEasing="SpringOut"
Spacing="5">
<telerikPrimitives:AccordionItem HeaderText="Attachments"
IsExpanded="True">
<telerikPrimitives:AccordionItem.Content>
<Button Text="Attach files" FontSize="20" Margin="10" />
</telerikPrimitives:AccordionItem.Content>
</telerikPrimitives:AccordionItem>
<telerikPrimitives:AccordionItem HeaderText="Comments">
<telerikPrimitives:AccordionItem.Content>
<Label Text="Add your comment here" Margin="30" />
</telerikPrimitives:AccordionItem.Content>
</telerikPrimitives:AccordionItem>
<telerikPrimitives:AccordionItem HeaderText="Rating">
<telerikPrimitives:AccordionItem.Content>
<telerikInput:RadShapeRating x:Name="rating" Margin="20"/>
</telerikPrimitives:AccordionItem.Content>
</telerikPrimitives:AccordionItem>
</telerikPrimitives:RadAccordion>
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikBusyIndicator="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Tel
erik.XamarinForms.Primitives"
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

C#
using Telerik.XamarinForms.Primitives;
using Telerik.XamarinForms.Input;
 

The image below shows the result after running the snippet:

141
Telerik UI for Xamarin

And the Accordion when all items are collapsed:

A sample Key Features example can be found in the Accordion/Features folder of the SDK Samples
Browser application.
 

142
Telerik UI for Xamarin

See Also
 AccordionItem Control

143
Telerik UI for Xamarin

AccordionItem control
Basic Features
AccordionItem Header

You could either apply HeaderText property or use the AccordionItemHeader content control which
provides a set of useful properties for customizing the look & feel of the Header. For more details
refer to AccordionItemHeader section.

IsExpanded

IsExpanded is a Boolean property to indicate the currently expanded state of the AccordionItem.

Border Styles

You could utilize BorderColor, BorderThickness and CornerRadius properties of RadAccordionItem


to change the way the Border around the control looks.

AccordionItemHeader
The indicator is the little triangle that is rotated according to whether the AccordionItem control is
expanded or collapsed. AccordionItemHeader provides various options for customizing the look of
the indicator via the following properties:

 IndicatorText: The indicator is represented by a string symbol that could be changed through
IndicatorText property;
 IndicatorFontFamily: Specifies the indicator text FontFamily;
 IndicatorFontSize: Defines the indicator text font size;
 IndicatorColor: This property sets the color of the indicator;
 IndicatorLocation: This property is of type ExpandCollapseIndicatorLocation and is used to
place the indicator to the left or to the right inside the Header;
 IndicatorAnimationDuration: Specifies the duration of the rotation animation of the indicator;
 IndicatorAnimationEasing: Specifies the easing of the rotation animation of the indicator;
 IndicatorMargin: This property is of type Thickness and sets the margin applied to the
indicator;

You could apply BorderColor, BorderThickness and CornerRadius properties of


AccordionItemHeader to make it consistent with the design of your app.

The following snippet shows the AccordionItemHeader could be customized:

XAML
<telerikPrimitives:AccordionItem IsExpanded="True"
BorderColor="LightBlue"
BorderThickness="2">

144
Telerik UI for Xamarin

<telerikPrimitives:AccordionItem.Header>
<telerikPrimitives:AccordionItemHeader
IndicatorColor="Blue"
IndicatorFontSize="16"
IndicatorLocation="End"
BorderColor="LightBlue"
BorderThickness="2">
<Label Text="Settings" Margin="8" />
</telerikPrimitives:AccordionItemHeader>
</telerikPrimitives:AccordionItem.Header>
<telerikPrimitives:AccordionItem.Content>
<StackLayout Margin="10, 20, 10, 20">
<StackLayout Orientation="Horizontal" Spacing="10">
<telerikPrimitives:RadCheckBox />
<Label Text="Make my profile private" />
</StackLayout>
<StackLayout Orientation="Horizontal" Spacing="10">
<telerikPrimitives:RadCheckBox />
<Label Text="Only show my posts to people who follow me" />
</StackLayout>
</StackLayout>
</telerikPrimitives:AccordionItem.Content>
</telerikPrimitives:AccordionItem>
 

Next image displays how RadAccordion will look with thus defined items:

A sample AccordionItem example can be found in the Accordion/Features folder of the SDK Samples
Browser application.
 

145
Telerik UI for Xamarin

See Also
 Key Features

146
Telerik UI for Xamarin

RadAutoComplete control has been replaced with RadAutoCompleteView and will be removed from
the suite soon. You can read about the differences between both components and how to migrate to
the new RadAutoCompleteView in the kb article here: Replace AutoComplete with AutoCompleteView
 

Overview
RadAutoComplete for Xamarin can automatically complete user input string by comparing the text
being entered to all strings in the associated data source. The control provides means for easy
customization and data management.

Figure 1: RadAutoComplete Overview

Key features
 Tokens Support: With RadAutoComplete you could enable users to search for and select
several items in one control. These items appear as tokens that can easily be deselected
using their close button. For more details on this check here.
 Filtering Options: You could define the filtering behavior to display all the matches that either
“StartsWith” or “Contains” the typed symbols. Read here for more details on this.
 Watermark: Used to give guidance to the end user on what should be entered in the text
input. Check here for more info.
 NoResults Message: NoResults message appears in the popup used for the list of
suggestions whenever the control cannot find any matching items. Read more about this
here.
 Customizable Items: Whenever the default template does not fit a particular scenario you
could use the SuggestionItemTemplate property to define a custom template. Read here for

147
Telerik UI for Xamarin

detailed instructions on how you could apply it.

See Also
 Getting Started

148
Telerik UI for Xamarin

RadAutoComplete control has been replaced with RadAutoCompleteView and will be removed from
the suite soon. You can read about the differences between both components and how to migrate to
the new RadAutoCompleteView in the kb article here: Replace AutoComplete with AutoCompleteView
 

Getting Started
This example will guide you through the steps needed to add a basic RadAutoComplete control in
your application.

Before you proceed, please, take a look at these articles and follow the instructions to setup your
app:
 

Example
If your app is setup, you are ready to add a RadAutoComplete control as content of your page.

XAML
<telerikInput:RadAutoComplete x:Name="autoComplete" Watermark="Search here..." />
 

C#
var autoComplete = new RadAutoComplete { Watermark = "Search here..." };
 

In addition to this you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

C#
using Telerik.XamarinForms.Input;
 

You also have to provide an items source for the suggestions list:

C#
this.autoComplete.ItemsSource = new List<string>()
{
"Freda Curtis",
"Jeffery Francis",
"Eva Lawson",
"Emmett Santos",
"Theresa Bryan",
"Jenny Fuller",

149
Telerik UI for Xamarin

"Terrell Norris",
"Eric Wheeler",
"Julius Clayton",
"Alfredo Thornton",
"Roberto Romero",
"Orlando Mathis",
"Eduardo Thomas",
"Harry Douglas",
"Parker Blanton",
"Leanne Motton",
"Shanti Osborn",
"Merry Lasker",
"Jess Doyon",
"Kizzie Arjona",
"Augusta Hentz",
"Tasha Trial",
"Fredda Boger",
"Megan Mowery",
"Hong Telesco",
"Inez Landi",
"Taina Cordray",
"Shantel Jarrell",
"Soo Heidt",
"Rayford Mahon",
"Jenny Omarah",
"Denita Dalke",
"Nida Carty",
"Sharolyn Lambson",
"Niki Samaniego",
"Rudy Jankowski",
"Matha Whobrey",
"Jessi Knouse",
"Vena Rieser",
"Roosevelt Boyce",
"Kristan Swiney",
"Lauretta Pozo",
"Jarvis Victorine",
"Dane Gabor"
};
 

Finally, set the AutoComplete as content of your page.

Here is the result:

150
Telerik UI for Xamarin

SDK Browser and QSF applications contain different examples that show RadAutoComplete's main
features. You can find the applications in the Examples and QSF folders of your local Telerik UI for
Xamarin installation.
 

151
Telerik UI for Xamarin

RadAutoComplete control has been replaced with RadAutoCompleteView and will be removed from
the suite soon. You can read about the differences between both components and how to migrate to
the new RadAutoCompleteView in the kb article here: Replace AutoComplete with AutoCompleteView
 

Required Telerik Assemblies


This article contains a list with the assemblies required by the RadAutoComplete component.

The path of the assemblies is relative to the Binaries folder that is located in the installation folder
of the controls. The default location is:
C:\Program Files (x86)\Progress\UI for Xamarin RX XXX\Binaries.

Please keep in mind that all binaries built for a specific platform are placed in a folder named after
that platform.

 
Platform Assemblies
Portable Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.DataControls.dll
Android Telerik.Xamarin.Android.Common.dll
Telerik.Xamarin.Android.Data.dll
Telerik.Xamarin.Android.Input.dll
Telerik.Xamarin.Android.List.dll
Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.DataControls.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.DataControls.dll
UWP Telerik.Core.dll
Telerik.Data.dll
Telerik.UI.Xaml.Controls.Data.UWP.dll
Telerik.UI.Xaml.Input.UWP.dll
Telerik.UI.Xaml.Primitives.UWP.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.DataControls.dll
As some of the controls included in Telerik UI for Xamarin suite rely on the SkiaSharp rendering
library, you should either install SkiaSharp.Views.Forms in all projects included in the Xamarin
solution (portable, android, ios, etc.) or in case you do not intend to use any of the Skia-dependent
components (Gauges, Rating, BusyIndicator), you could reference the Lite assemblies.
 

See Also
152
Telerik UI for Xamarin

 Getting Started

153
Telerik UI for Xamarin

RadAutoComplete control has been replaced with RadAutoCompleteView and will be removed from
the suite soon. You can read about the differences between both components and how to migrate to
the new RadAutoCompleteView in the kb article here: Replace AutoComplete with AutoCompleteView
 

Key Features
The purpose of this help article is to show you the key features of the RadAutoComplete control.

Tokens Support
With AutoComplete you could enable users to search for and select several items. These items
appear as tokens that can easily be deselected using their close button.

DisplayMode property determines whether a single or multiple selection is enabled. The default
DisplayMode is “Plain”, for multiple selection you would need to set it to “Tokens”.

Tokens support is available only for Android and iOS platforms.


 
XAML
<telerikInput:RadAutoComplete x:Name="autoCompleteTokens"
ItemsSource="{Binding Source}"
TextSearchPath="Name"
DisplayMode="Tokens"/>
 

Figure 1: Tokens Support

154
Telerik UI for Xamarin

Filtering Options
You can determine the filtering behavior of RadAutoComplete through the CompletionMode
property. The available completion modes are "StartsWith" (default) and "Contains".

In data-binding scenarios you will also need to set TextSearchPath property, which defines the name
of the property the search function will be executed against. For more details check the Data Binding
topic.
 
XAML
<telerikInput:RadAutoComplete x:Name="autoCompleteFilter"
ItemsSource="{Binding Source}"
TextSearchPath="Name"
CompletionMode="Contains"/>
 

Figure 2: Filtering options

155
Telerik UI for Xamarin

Watermark
RadAutoComplete exposes Watermark property which is used to give guidance to the end user on
what should be entered in the text input. The watermark text is displayed when the control is empty.

XAML
<telerikInput:RadAutoComplete x:Name="autoCompleteWatermark"
ItemsSource="{Binding Source}"
TextSearchPath="Name"
Watermark="Enter name..."/>
 

Figure 3: Watermark

156
Telerik UI for Xamarin

Clear Button Visibility


The Clear button, which appears at the right side of the input field when the AutoComplete is in
focus, gives the end-user the option to quickly clear the entered values. You could control the
visibility of the button through the IsClearButtonVisible property.

NoResults Message
The NoResults message appears in the popup used for the list of suggestions whenever the control
cannot find any matching items. You could easily customize it through the NoResultsMessage
property.

XAML
<telerikInput:RadAutoComplete x:Name="autoCompleteNoResults"
ItemsSource="{Binding Source}"
TextSearchPath="Name"
NoResultsMessage="there are no matching items..."/>
 

Figure 3: NoResultsMessage

157
Telerik UI for Xamarin

Search Threshold
By default the search is triggered as soon as the user types into the input field. By using
SearchThreshold you can configure AutoComplete to trigger the search after a certain number of
letters is entered.

XAML
<telerikInput:RadAutoComplete x:Name="autoCompleteSearchTreshold"
ItemsSource="{Binding Source}"
TextSearchPath="Name"
SearchThreshold="3" />
 

Show/hide the SuggestionView


With the ShowSuggestionView boolean property you can determine the visibility of the popup
containing the search results of the AutoComplete.

XAML
<telerikInput:RadAutoComplete x:Name="autoCompleteSuggestionView"
ItemsSource="{Binding Source}"
TextSearchPath="Name"
ShowSuggestionView="False" />
 

FilteredItems collection

158
Telerik UI for Xamarin

FilteredItems bindable property allows you to access the collection containing the search results of
the AutoComplete. The property can be used in scenarios where the search results are visualized at
a different place or inside another container.

See Also
 AutoComplete Getting Started
 Data Binding

159
Telerik UI for Xamarin

RadAutoComplete control has been replaced with RadAutoCompleteView and will be removed from
the suite soon. You can read about the differences between both components and how to migrate to
the new RadAutoCompleteView in the kb article here: Replace AutoComplete with AutoCompleteView
 

Data Binding
For all cases where the business items are not simple strings data-binding is necessary in order to
correctly visualize information. The RadAutoComplete component supports data binding in the form
of path properties.

 TextSearchPath (string): Gets or sets the name of the property the search function will be
executed against.
 ImagePath (string): Gets or sets the name of the property holding a path to an image. This
property is optional.

The TextSearchPath property is required in data-binding scenarios.


 
The RadAutoComplete component provides a default template for suggestion items that cannot be
modified. You can use a custom template if you need to customize the suggestion items.

Example
Here is a simple view model that will be used as data source for the RadAutoComplete suggestions.

C#
public class BusinessObject
{
public BusinessObject(string name, string imageSource)
{
this.Name = name;
this.ImageSource = imageSource;
}

public string Name { get; set; }

public string ImageSource { get; set; }


}

public class ViewModel


{
public ViewModel()
{
this.Source = new List<BusinessObject>()
{
new BusinessObject("Freda Curtis", "available32.png"),
new BusinessObject("Jeffery Francis", "away32.png"),
new BusinessObject("Eva Lawson", "available32.png"),
new BusinessObject("Emmett Santos", "away32.png"),

160
Telerik UI for Xamarin

new BusinessObject("Theresa Bryan", "away32.png"),


new BusinessObject("Jenny Fuller", "available32.png"),
new BusinessObject("Terrell Norris", "away32.png"),
new BusinessObject("Eric Wheeler", "busy32.png"),
new BusinessObject("Julius Clayton", "available32.png"),
new BusinessObject("Alfredo Thornton", "busy32.png"),
new BusinessObject("Roberto Romero", "busy32.png"),
new BusinessObject("Orlando Mathis", "available32.png"),
new BusinessObject("Eduardo Thomas", "away32.png"),
new BusinessObject("Harry Douglas", "available32.png"),
new BusinessObject("Parker Blanton", "available32.png"),
new BusinessObject("Leanne Motton", "busy32.png"),
new BusinessObject("Shanti Osborn", "available32.png"),
new BusinessObject("Merry Lasker", "busy32.png"),
new BusinessObject("Jess Doyon", "away32.png"),
new BusinessObject("Kizzie Arjona", "busy32.png"),
new BusinessObject("Augusta Hentz", "available32.png"),
new BusinessObject("Tasha Trial", "away32.png"),
new BusinessObject("Fredda Boger", "busy32.png"),
new BusinessObject("Megan Mowery", "available32.png"),
new BusinessObject("Hong Telesco", "away32.png"),
new BusinessObject("Inez Landi", "busy32.png"),
new BusinessObject("Taina Cordray", "available32.png"),
new BusinessObject("Shantel Jarrell", "busy32.png"),
new BusinessObject("Soo Heidt", "available32.png"),
new BusinessObject("Rayford Mahon", "away32.png"),
new BusinessObject("Jenny Omarah", "away32.png"),
new BusinessObject("Denita Dalke", "available32.png"),
new BusinessObject("Nida Carty", "available32.png"),
new BusinessObject("Sharolyn Lambson", "away32.png"),
new BusinessObject("Niki Samaniego", "available32.png"),
new BusinessObject("Rudy Jankowski", "away32.png"),
new BusinessObject("Matha Whobrey", "busy32.png"),
new BusinessObject("Jessi Knouse", "available32.png"),
new BusinessObject("Vena Rieser", "away32.png"),
new BusinessObject("Roosevelt Boyce", "available32.png"),
new BusinessObject("Kristan Swiney", "away32.png"),
new BusinessObject("Lauretta Pozo", "busy32.png"),
new BusinessObject("Jarvis Victorine", "away32.png"),
new BusinessObject("Dane Gabor", "busy32.png")
};
}

public List<BusinessObject> Source { get; set; }


}
 

Here is how to setup the RadAutoComplete:

XAML
<telerikInput:RadAutoComplete x:Name="AutoComplete"
ImagePath="ImageSource"
ItemsSource="{Binding Source}"

161
Telerik UI for Xamarin

TextSearchPath="Name"
Watermark="Search here...">
<telerikInput:RadAutoComplete.SuggestionViewHeight>
<OnPlatform x:TypeArguments="x:Double"
Android="200"
WinPhone="400"
iOS="400" />
</telerikInput:RadAutoComplete.SuggestionViewHeight>
<telerikInput:RadAutoComplete.BindingContext>
<local:ViewModel />
</telerikInput:RadAutoComplete.BindingContext>
</telerikInput:RadAutoComplete>
 

Where:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

See Also
 AutoComplete Getting Started
 SuggestionItemTemplate

162
Telerik UI for Xamarin

RadAutoComplete control has been replaced with RadAutoCompleteView and will be removed from
the suite soon. You can read about the differences between both components and how to migrate to
the new RadAutoCompleteView in the kb article here: Replace AutoComplete with AutoCompleteView
 

Suggestion Items Customization


SuggestionItemTemplate
Whenever the default templates does not fit a particular scenario customers can use the
SuggestionItemTemplate property to define a custom template.

 SuggestionItemTemplate (DataTemplate): Gets or sets the template that will be used to


create each of the suggestions.

Example
This example will demonstrate how to set a custom template for the RadAutoComplete suggestion
items.

Here is a sample view model that will be used as data source for the suggestions:

C#
public class BusinessObject
{
public BusinessObject(string name, string imageSource)
{
this.Name = name;
this.ImageSource = imageSource;
}

public string Name { get; set; }

public string ImageSource { get; set; }


}

public class ViewModel


{
public ViewModel()
{
this.Source = new List<BusinessObject>()
{
new BusinessObject("Freda Curtis", "available32.png"),
new BusinessObject("Jeffery Francis", "away32.png"),
new BusinessObject("Eva Lawson", "available32.png"),
new BusinessObject("Emmett Santos", "away32.png"),
new BusinessObject("Theresa Bryan", "away32.png"),
new BusinessObject("Jenny Fuller", "available32.png"),
new BusinessObject("Terrell Norris", "away32.png"),

163
Telerik UI for Xamarin

new BusinessObject("Eric Wheeler", "busy32.png"),


new BusinessObject("Julius Clayton", "available32.png"),
new BusinessObject("Alfredo Thornton", "busy32.png"),
new BusinessObject("Roberto Romero", "busy32.png"),
new BusinessObject("Orlando Mathis", "available32.png"),
new BusinessObject("Eduardo Thomas", "away32.png"),
new BusinessObject("Harry Douglas", "available32.png"),
new BusinessObject("Parker Blanton", "available32.png"),
new BusinessObject("Leanne Motton", "busy32.png"),
new BusinessObject("Shanti Osborn", "available32.png"),
new BusinessObject("Merry Lasker", "busy32.png"),
new BusinessObject("Jess Doyon", "away32.png"),
new BusinessObject("Kizzie Arjona", "busy32.png"),
new BusinessObject("Augusta Hentz", "available32.png"),
new BusinessObject("Tasha Trial", "away32.png"),
new BusinessObject("Fredda Boger", "busy32.png"),
new BusinessObject("Megan Mowery", "available32.png"),
new BusinessObject("Hong Telesco", "away32.png"),
new BusinessObject("Inez Landi", "busy32.png"),
new BusinessObject("Taina Cordray", "available32.png"),
new BusinessObject("Shantel Jarrell", "busy32.png"),
new BusinessObject("Soo Heidt", "available32.png"),
new BusinessObject("Rayford Mahon", "away32.png"),
new BusinessObject("Jenny Omarah", "away32.png"),
new BusinessObject("Denita Dalke", "available32.png"),
new BusinessObject("Nida Carty", "available32.png"),
new BusinessObject("Sharolyn Lambson", "away32.png"),
new BusinessObject("Niki Samaniego", "available32.png"),
new BusinessObject("Rudy Jankowski", "away32.png"),
new BusinessObject("Matha Whobrey", "busy32.png"),
new BusinessObject("Jessi Knouse", "available32.png"),
new BusinessObject("Vena Rieser", "away32.png"),
new BusinessObject("Roosevelt Boyce", "available32.png"),
new BusinessObject("Kristan Swiney", "away32.png"),
new BusinessObject("Lauretta Pozo", "busy32.png"),
new BusinessObject("Jarvis Victorine", "away32.png"),
new BusinessObject("Dane Gabor", "busy32.png")
};
}

public List<BusinessObject> Source { get; set; }


}
 

Here is how to setup the RadAutoComplete control:

XAML
<telerikInput:RadAutoComplete x:Name="AutoComplete"
ItemsSource="{Binding Source}"
TextSearchPath="Name"
VerticalOptions="Start"
Watermark="Search here...">
<telerikInput:RadAutoComplete.BindingContext>

164
Telerik UI for Xamarin

<local:ViewModel />
</telerikInput:RadAutoComplete.BindingContext>
<telerikInput:RadAutoComplete.SuggestionViewHeight>
<OnPlatform x:TypeArguments="x:Double"
Android="200"
WinPhone="400"
iOS="400" />
</telerikInput:RadAutoComplete.SuggestionViewHeight>
<telerikInput:RadAutoComplete.SuggestionItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Label Margin="5"
FontSize="24"
Text="{Binding Item.Name}"
TextColor="Black" />
<Image Grid.Column="1"
Margin="5"
HeightRequest="20"
Source="{Binding Item.ImageSource}"
WidthRequest="20" />
</Grid>
</DataTemplate>
</telerikInput:RadAutoComplete.SuggestionItemTemplate>
</telerikInput:RadAutoComplete>
 

Where:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

Here is the result:

165
Telerik UI for Xamarin

Custom Highlight
With custom template the highlight of the matching strings in the auto-complete suggestions is lost.
We have provided a special RadAutoCompleteLabel for scenarios that require highlight. Customers
can use this label directly in the SuggestionItemTemplate and its text will be automatically set.

Example
XAML
<telerikInput:RadAutoComplete.SuggestionItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Image Margin="5"
HeightRequest="20"
Source="{Binding Item.ImageSource}"
VerticalOptions="Center"
WidthRequest="20" />
<telerikInput:RadAutoCompleteLabel Grid.Column="1"
Margin="5"
FontSize="24"
HighlightColor="Black"
TextColor="Silver"
VerticalOptions="Center" />
</Grid>

166
Telerik UI for Xamarin

</DataTemplate>
</telerikInput:RadAutoComplete.SuggestionItemTemplate>
 

Where:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

Here is the result:

See Also
 AutoComplete Getting Started
 Data Binding

167
Telerik UI for Xamarin

RadAutoComplete control has been replaced with RadAutoCompleteView and will be removed from
the suite soon. You can read about the differences between both components and how to migrate to
the new RadAutoCompleteView in the kb article here: Replace AutoComplete with AutoCompleteView
 

Events
RadAutoComplete component exposes the following events:

 SuggestionItemSelected - occurs when an item is selected from the SuggestionsView. The


SuggestionItemSelected event handler receives two parameters:
 The sender argument which is of type object, but can be cast to the RadAutoComplete
type.
 An SuggestionItemSelectedEventArgs object which has a reference to the selected item
through its DataItem property.
 FilteredItemsChanged - occurs when the FilteredItems collection is updated. The
FilteredItemsChanged event handler receives two parameters:
 The sender argument which is of type object, but can be cast to the RadAutoComplete
type.
 An FilteredItemsChangedEventArgs object which has a reference to filtered items
collection its FilteredItems property.

Example
Add the telerikInput namespace:

XML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

Add a RadAutoComplete with the event handlers:

XML
<telerikInput:RadAutoComplete x:Name="radAutoComplete"
FilteredItemsChanged="RadAutoComplete_OnFilteredItemsChanged"
SuggestionItemSelected="RadAutoComplete_OnSuggestionItemSelected" />
 

In code-behind, assign an ItemsSource and define the event handlers:

C#
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();

168
Telerik UI for Xamarin

radAutoComplete.ItemsSource = new ObservableCollection<string>


{
"Apple",
"Pear",
"Cherry"
};
}

private void RadAutoComplete_OnFilteredItemsChanged(object sender,


FilteredItemsChangedEventArgs e)
{
// Since the ItemsSource is of type ObservableCollection<string>, FilteredItems
will be as well.
var filteredFruits = e.FilteredItems as ObservableCollection<string>;
}

private void RadAutoComplete_OnSuggestionItemSelected(object sender,


SuggestionItemSelectedEventArgs e)
{
// The DataItem is an item from the FilteredItems collection. In this example,
it's of type string.
var selectedFruit = e.DataItem as string;
}
}
 

See Also
 AutoComplete Getting Started
 SuggestionItemTemplate

169
Telerik UI for Xamarin

Overview
RadAutoCompleteView for Xamarin can automatically complete user input string by comparing the
text being entered to all strings in the associated data source. The control has a number of
advanced features such as different filtering options, tokens support and remote search, as well as
full customization capabilities.

Figure 1: RadAutoCompleteView Overview

Key features
 Tokens Support: With RadAutoCompleteView you could enable users to search for and
select several items in one control. These items appear as tokens that can easily be
deselected using their close button. For more details on this check here.
 Filtering Options: You could define the filtering behavior to display all the matches that either
“StartsWith” or “Contains” the typed symbols. Read here for more details on this.
 Different Suggest Modes Support: RadAutoCompleteView exposes three different modes
(Suggest, Append, SuggestAppend) for providing suggestions. For more details check here.
 Watermark: Used to give guidance to the end user on what should be entered in the text
input. Check here for more info.
 NoResults Message: NoResults message appears in the popup used for the list of
suggestions whenever the control cannot find any matching items. Read more about this
here.
 Vizualized text Formatting: You could modify the displayed details of the selected item. For
more information check the DisplayText Formatter article.
 Custom Templates: If any of the default templates does not fit in a particular scenario, you

170
Telerik UI for Xamarin

can easily define a custom template. Check the available templates for customization here.
 Remote Search: Allows you to easily take the user input, trigger custom searching algorithm
and assign the results to the ItemSource of the AutoCompleteView. Read more about this
here.
 Show/Hide Suggestions: AutoCompleteView provides the ability to show/hide all suggestions
immediately when you focused on the input field. Read more about AutoCompleteView
methods here.
 Highlight Customization: The ability to highlight the text inside the custom template. Check
here for more info.
 Nested Properties Support: This allows binding of a complex object to the
RadAutoCompleteView TextSearchPath property.

See Also
 Getting Started
 Key Features
 Tokens Support

171
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadAutoCompleteView control in
your application.

 Setting up the app


 Adding the required Telerik references
 Adding RadAutoCompleteView control
 Populating RadAutoCompleteView with data

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadAutoCompleteView control you have to install the
Telerik.UI.for.Xamarin.Input nuget package. This nuget will automatically refer the
Telerik.UI.for.Xamarin.Primitives, Telerik.UI.for.Xamarin.Common, and
Telerik.UI.for.Xamarin.DataControls nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadAutoCompleteView component:

Platform Assemblies
Portable Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.Primitives.dll
Android Telerik.Xamarin.Android.Common.dll
Telerik.Xamarin.Android.Data.dll
Telerik.Xamarin.Android.Input.dll
Telerik.Xamarin.Android.List.dll
Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll

172
Telerik UI for Xamarin

Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.Primitives.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.Primitives.dll
UWP Telerik.Core.dll
Telerik.Data.dll
Telerik.UI.Xaml.Controls.Data.UWP.dll
Telerik.UI.Xaml.Input.UWP.dll
Telerik.UI.Xaml.Primitives.UWP.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.Primitives.dll

3. Adding RadAutoCompleteView control


You could use one of the following approaches:

Drag the control from the Toolbox.

Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML or C#.

The snippet below shows a simple RadAutoCompleteView definition:

XAML
<telerikInput:RadAutoCompleteView x:Name="autoCompleteView" Watermark="Search here..."
/>
 

C#
var autoCompleteView = new RadAutoCompleteView { Watermark = "Search here..." };
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

173
Telerik UI for Xamarin

C#
using Telerik.XamarinForms.Input;
 

4. Populating RadAutoCompleteView with data


Lets provide an items source for the suggestion list:

C#
this.autoCompleteView.ItemsSource = new List<string>()
{
"Freda Curtis",
"Jeffery Francis",
"Eva Lawson",
"Emmett Santos",
"Theresa Bryan",
"Jenny Fuller",
"Terrell Norris",
"Eric Wheeler",
"Julius Clayton",
"Alfredo Thornton",
"Roberto Romero",
"Orlando Mathis",
"Eduardo Thomas",
"Harry Douglas"
};
 

Finally, set the AutoCompleteView as content of your page.

This is the result:

174
Telerik UI for Xamarin

SDK Browser and QSF applications contain different examples that show RadAutoCompleteView's
main features. You can find the applications in the Examples and QSF folders of your local Telerik UI
for Xamarin installation.
 

See Also
 Key Features
 Tokens Support
 Data Binding

175
Telerik UI for Xamarin

Key Features
The purpose of this help article is to show you the key features of the RadAutoCompleteView
control.

Tokens Support
With AutoCompleteView you could enable users to search for and select several items. These items
appear as tokens that can easily be deselected using their close button.

DisplayMode (SuggestionsDisplayMode) property determines whether a single or multiple selection


is enabled. The default DisplayMode is “Plain”, for multiple selection you would need to set it to
“Tokens”.

XAML
<telerikInput:RadAutoCompleteView x:Name="autoCompleteViewTokens"
ItemsSource="{Binding Source}"
TextSearchPath="Name"
BackgroundColor="White"
DisplayMode="Tokens"/>
 

Here is the result when the DisplayMode is set to Tokens:

176
Telerik UI for Xamarin

Filtering Options
You can determine the filtering behavior of RadAutoCompleteView through the CompletionMode
property. The available completion modes are "StartsWith" (default) and "Contains".

In data-binding scenarios you will also need to set TextSearchPath property, which defines the name
of the property the search function will be executed against. For more details check the Data Binding
topic.
 
XAML
<telerikInput:RadAutoCompleteView x:Name="autoCompleteViewFilter"
ItemsSource="{Binding Source}"
TextSearchPath="Name"
CompletionMode="Contains"/>
 

Watermark
RadAutoCompleteView exposes Watermark property which is used to give guidance to the end user
on what should be entered in the text input. The watermark text is displayed when the control is
empty.You could also use the WatermarkTextColor property to define the Watermark text color of
the component.

XAML
<telerikInput:RadAutoCompleteView x:Name="autoCompleteViewWatermark"
ItemsSource="{Binding Source}"
TextSearchPath="Name"
Watermark="Enter name..."
WatermarkTextColor="LightBlue"/>
 

Keyboard
The Keyboard property of type Xamarin.Forms.Keyboard allows you to define the type of the
keyboard that will be visualized by the device.

XAML
<telerikInput:RadAutoCompleteView Keyboard="Numeric" />
 

Clear Button Visibility


The Clear button, which appears at the right side of the input field when the AutoCompleteView is on
focus, gives the end-user the option to quickly clear the entered values. You could control the
visibility of the button through the IsClearButtonVisible property.

NoResults Message

177
Telerik UI for Xamarin

The NoResults message appears in the popup used for the list of suggestions whenever the control
cannot find any matching items. You could use the following properties to customize the NoResult
message:

 NoResultsMessage (string): Defines the message visualized when there are no suggestions
found.
 NoResultsTemplate (DataTemplate): Defines the template visualized when there are no
suggestions found.

XAML
<telerikInput:RadAutoCompleteView x:Name="autoCompleteViewNoResults"
ItemsSource="{Binding Source}"
TextSearchPath="Name"
NoResultsMessage="there are no matching items..."/>
 

Search Threshold
By default the search is triggered as soon as the user types into the input field. By using
SearchThreshold you can configure AutoCompleteView to trigger the search after a certain number
of letters is entered.

XAML
<telerikInput:RadAutoCompleteView x:Name="autoCompleteViewSearchTreshold"
ItemsSource="{Binding Source}"
TextSearchPath="Name"
SearchThreshold="3" />
 

Show/Hide the SuggestionView


 ShowSuggestionView (bool): Determine the visibility of the popup containing the search
results of the AutoCompleteView.
 SuggestionViewHeight (double): Defines the SuggestionViewHeight of the control.
 SuggestionViewBackgroundColor: Defines the SuggestionViewBackgroundColor of the
component.

XAML
<telerikInput:RadAutoCompleteView x:Name="autoCompleteViewSuggestionView"
ItemsSource="{Binding Source}"
TextSearchPath="Name"
ShowSuggestionView="True"
SuggestionViewHeight="100"
SuggestionViewBackgroundColor="LightBlue"/>
 

SuggestionView Position

178
Telerik UI for Xamarin

With R2 2022 AutoCompleteView exposes a new SuggestionViewPosition property which enables


you to explicitly define whether the suggestions popup will be shown below or above the input field.
SuggestionViewPosition is of enum type
Telerik.XamarinForms.Input.AutoCompleteView.PopupPosition and can be set to any of the
following values:

 (default) Auto
 Top
 Bottom

Where "Auto" calculates the available space and chooses what's the best position of the popup,
starting with "Bottom". With "Top"/"Bottom" setting, the popup is positioned above or below the
AutoCompleteView respectively.

XAML
<telerikInput:RadAutoCompleteView ItemsSource="{Binding Source}"
TextSearchPath="Name"
SuggestionViewPosition="Top"/>
 

FilteredItems collection
FilteredItems bindable property allows you to access the collection containing the search results of
the AutoCompleteView. The property can be used in scenarios where the search results are
visualized at a different place or inside another container.

A sample Key Features example can be found in the AutoCompleteView/Features folder of the SDK
Samples Browser application.
 

See Also
 Styling Options
 Data Binding
 Events

179
Telerik UI for Xamarin

Suggest Mode
RadAutoCompleteView exposes three different modes for providing suggestions:

 Suggest: Provides a drop-down list of options for you to pick from;


 Append: Provides an inline display of the first suggestion;
 SuggestAppend: Combines the functionality of the two options above, shows a drop-down
with suggestions and at the same time selects the first one from the list.

In order to choose any of those modes you should set the SuggestMode property of the control. The
default SuggestMode is "Suggest".

Example
Here is an example how the RadAutoCompleteView Suggest Mode functionality works:

First, create the needed business objects, for example type Client with the following properties:

C#
public class Client
{
public Client(string name, string email, string imageSource)
{
this.Name = name;
this.Email = email;
this.ImageSource = imageSource;
}
public string Name { get; set; }
public string Email { get; set; }
public string ImageSource { get; set; }
}
 

Then create a ViewModel with a collection of Client objects:

C#
public class ViewModel
{
public ObservableCollection<Client> Source { get; set; }
public ViewModel()
{
this.Source = new ObservableCollection<Client>()
{
new Client("Freda Curtis", "fcurtis@mail.com", "available32.png"),
new Client("Jeffery Francis", "jfrancis@mail.com", "away32.png"),
new Client("Eva Lawson", "elawson@mail.com", "available32.png"),
new Client("Emmett Santos", "esantos@mail.com", "busy32.png"),
new Client("Theresa Bryan", "tbryan@mail.com", "available32.png"),

180
Telerik UI for Xamarin

new Client("Jenny Fuller", "jfuller@mail.com", "busy32.png"),


new Client("Terrell Norris", "tnorris@mail.com", "away32.png"),
new Client("Eric Wheeler", "ewheeler@mail.com", "away32.png"),
new Client("Nida Carty", "ncarty@mail.com", "away32.png"),
new Client("Niki Samaniego", "nsamaniego@mail.com", "busy32.png")
};
}
}
 

For example SuggestMode="Suggest" property can be declared through XAML using the following
snippet:

XAML
<telerikInput:RadAutoCompleteView x:Name="autoCompleteViewSuggest"
SuggestMode="Suggest"
ItemsSource="{Binding Source}"
TextSearchPath="Name"
Watermark="AutoCompleteView Suggest"
SuggestionViewHeight="150"/>
 

Here is the result when SuggestMOde is set to Suggest:

For SuggestMode="Append":

XAML
<telerikInput:RadAutoCompleteView x:Name="autoCompleteViewAppend"

181
Telerik UI for Xamarin

SuggestMode="Append"
ItemsSource="{Binding Source}"
TextSearchPath="Name"
Watermark="AutoCompleteView Append"
SuggestionViewHeight="150"/>
 

And the final result:

And finaly SuggestMode="SuggestAppend" is declared as follow:

XAML
<telerikInput:RadAutoCompleteView x:Name="autoCompleteViewSuggestAppend"
SuggestMode="SuggestAppend"
ItemsSource="{Binding Source}"
TextSearchPath="Name"
Watermark="AutoCompleteView SuggestAppend"
SuggestionViewHeight="100"/>
 

Here is the result:

182
Telerik UI for Xamarin

A sample Suggest Mode example can be found in the AutoCompleteView/Features folder of the SDK
Samples Browser application.
 

See Also
 Tokens Support
 SuggestionItemTemplate
 Remote Search

183
Telerik UI for Xamarin

Tokens Support - Multiple Selection


With AutoCompleteView you could enable users to search for and select several items (multiple
selection). These items appear as tokens that can easily be deselected using their close button.

The Tokens Support feature exposes the following properties:

 DisplayMode (SuggestionsDisplayMode) property determines whether a single or multiple


selection is enabled. The default DisplayMode is “Plain”, for multiple selection you would
need to set it to “Tokens”.
 ShowMoreItems (bool): Defines the visibility of the view that is used to represents more
items. When ShowMoreItems is set to true and ShowMoreTemplate is set, the
RadAutoCompleteView will hide tokens that are not on the first line and will show the hidden
count. Dy default ShowMoreItems is true. If you want to hide the hidden count you should set
the ShowMoreItems to false.
 ShowMoreTemplate (DataTemplate): Defines the template used to create show more view.

Tokens Collection
The RadAutoCompleteView control provides a readonly collection for the tokens - Tokens collection
of type ObservableCollection<object>. When items are selected from the SuggestionView and
DisplayMode is Tokens, these items are added to the Tokens collection. In order to track changes in
the Tokens collection when items are added or removed you have to subscribe for the
Tokens.CollectionChanged. For example:

C#
this.autoCompleteView.Tokens.CollectionChanged;
 

C#
private void Tokens_CollectionChanged(object sender,
System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{

Example
Here is an example how the RadAutoCompleteView Tokens feature works:

First, create the needed business objects, for example type City with the following properties:

C#
public class City
{

184
Telerik UI for Xamarin

public string Name { get; set; }


public City(string name)
{
this.Name = name;
}
}
 

Then create a TokensViewModel with a collection of City objects:

C#
public class TokensViewModel
{
public List<City> Source { get; set; }
public TokensViewModel()
{
this.Source = new List<City>()
{
new City("Madrid"),
new City("Paris"),
new City("Barcelona"),
new City("New York"),
new City("Budapest"),
new City("Sofia"),
new City("Palermo"),
new City("Melbourne"),
new City("London"),
new City("Nagoya"),
new City("Tokyo"),
new City("Atlanta"),
new City("Toronto"),
new City("Athens"),
};
}
}
 

Finally, use the following snippet to declare a RadAutoCompleteView in XAML:

XAML
<telerikInput:RadAutoCompleteView DisplayMode="Tokens"
ItemsSource="{Binding Source}"
TextSearchPath="Name"
Watermark="Search Here..."
BackgroundColor="White">
<telerikInput:RadAutoCompleteView.ShowMoreTemplate>
<DataTemplate>
<Label Text="{Binding Path=., StringFormat='+{0} more'}"
VerticalTextAlignment="Center" />
</DataTemplate>
</telerikInput:RadAutoCompleteView.ShowMoreTemplate>
<telerikInput:RadAutoCompleteView.NoResultsTemplate>

185
Telerik UI for Xamarin

<DataTemplate>
<Label Text="No match was found for the specific search. Please try again."/>
</DataTemplate>
</telerikInput:RadAutoCompleteView.NoResultsTemplate>
</telerikInput:RadAutoCompleteView>
 

Where the telerikInput namespace is the following:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

Here is the result when ShowMoreTemplate is used:

A sample Tokens example can be found in the AutoCompleteView/Features folder of the SDK
Samples Browser application.
 

See Also
 Data Binding
 Events
 Methods

186
Telerik UI for Xamarin

Data Binding
For all cases where the business items are not simple strings data-binding is necessary in order to
correctly visualize information. The RadAutoCompleteView component supports data binding in the
form of path properties.

 TextSearchPath (string): Defines the name of the property the search function will be
executed against.
 ImagePath (string): Defines the name of the property holding a path to an image. This
property is optional.

The TextSearchPath property is required in data-binding scenarios.


 
The RadAutoCompleteView component provides a default template for suggestion items that cannot
be modified. You can use a custom template if you need to customize the suggestion items.

Example
Here is an example how the RadAutoCompleteView Data Binding works:

First, create the needed business objects, for example type Client with the following properties:

C#
public class Client
{
public Client(string name, string email, string imageSource)
{
this.Name = name;
this.Email = email;
this.ImageSource = imageSource;
}
public string Name { get; set; }
public string Email { get; set; }
public string ImageSource { get; set; }
}
 

Then create a ViewModel with a collection of Client objects:

C#
public class ViewModel
{
public ObservableCollection<Client> Source { get; set; }
public ViewModel()
{
this.Source = new ObservableCollection<Client>()
{
new Client("Freda Curtis", "fcurtis@mail.com", "available32.png"),

187
Telerik UI for Xamarin

new Client("Jeffery Francis", "jfrancis@mail.com", "away32.png"),


new Client("Eva Lawson", "elawson@mail.com", "available32.png"),
new Client("Emmett Santos", "esantos@mail.com", "busy32.png"),
new Client("Theresa Bryan", "tbryan@mail.com", "available32.png"),
new Client("Jenny Fuller", "jfuller@mail.com", "busy32.png"),
new Client("Terrell Norris", "tnorris@mail.com", "away32.png"),
new Client("Eric Wheeler", "ewheeler@mail.com", "away32.png"),
new Client("Nida Carty", "ncarty@mail.com", "away32.png"),
new Client("Niki Samaniego", "nsamaniego@mail.com", "busy32.png")
};
}
}
 

Finally, use the following snippet to declare a RadAutoCompleteView in XAML:

XAML
<telerikInput:RadAutoCompleteView x:Name="autoCompleteView"
ImagePath="ImageSource"
ItemsSource="{Binding Source}"
TextSearchPath="Name"
Watermark="Show Suggestions on focus"/>
 

Where the telerikInput namespace is the following:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

A sample Data Binding example can be found in the AutoCompleteView/Features folder of the SDK
Samples Browser application.
 

See Also
 Tokens Support
 SuggestionItemTemplate

188
Telerik UI for Xamarin

DisplayText Formatter
RadAutoCompleteView control provides the option to format the visualized text in the input, so you
could modify the displayed details of the selected item. The format of the text could be defined when
AutoCompleteView DisplayMode is Plain or Tokens:

 DisplayTextFormatter(IDisplayTextFormatter): Defines the formatter of the selected item.

There are two options to define the formatter of the selected item:

 Set DisplayTextFortammer property and define the name of the property from the business
object which will be displaied after formatting.
 Create a custom class that inherits from IDisplayTextFormatter and implement a custom
logic how the selected item could be formatted.

Example
DisplayText Formatter with DisplayMode Plain
Here is an example how the RadAutoCompleteView DisplayText Formatter works on Plain
DisplayMode:

First, create the needed business objects, for example type Client with the following properties:

C#
public class Client
{
public Client(string name, string email, string imageSource)
{
this.Name = name;
this.Email = email;
this.ImageSource = imageSource;
}
public string Name { get; set; }
public string Email { get; set; }
public string ImageSource { get; set; }
}
 

Then create a ViewModel with a collection of Client objects:

C#
public class ViewModel
{
public ObservableCollection<Client> Source { get; set; }
public ViewModel()
{

189
Telerik UI for Xamarin

this.Source = new ObservableCollection<Client>()


{
new Client("Freda Curtis", "fcurtis@mail.com", "available32.png"),
new Client("Jeffery Francis", "jfrancis@mail.com", "away32.png"),
new Client("Eva Lawson", "elawson@mail.com", "available32.png"),
new Client("Emmett Santos", "esantos@mail.com", "busy32.png"),
new Client("Theresa Bryan", "tbryan@mail.com", "available32.png"),
new Client("Jenny Fuller", "jfuller@mail.com", "busy32.png"),
new Client("Terrell Norris", "tnorris@mail.com", "away32.png"),
new Client("Eric Wheeler", "ewheeler@mail.com", "away32.png"),
new Client("Nida Carty", "ncarty@mail.com", "away32.png"),
new Client("Niki Samaniego", "nsamaniego@mail.com", "busy32.png")
};
}
}
 

After that create a class for example MyBusinessObjectFormatter that inherist from
IDisplayTextFormatter:

C#
public class MyTextFormatter : IDisplayTextFormatter
{
public string FormatItem(object item)
{
var businessItem = item as Client;
return string.Format("Name: {0}, Email: {1}", businessItem.Name,
businessItem.Email);
}
}
 

Finally, use the following snippet to declare a RadAutoCompleteView in XAML:

XAML
<telerikInput:RadAutoCompleteView x:Name="autoCompleteView"
ItemsSource="{Binding Source}"
TextSearchPath="Name"
BackgroundColor="White"
DisplayMode="Plain"
SuggestionViewHeight="150">
<telerikInput:RadAutoCompleteView.DisplayTextFormatter>
<local:MyTextFormatter/>
</telerikInput:RadAutoCompleteView.DisplayTextFormatter>
</telerikInput:RadAutoCompleteView>
 

Where the telerikInput namespace is the following:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"

190
Telerik UI for Xamarin

DisplayText Formatter with DisplayMode Token


Here is an example how the RadAutoCompleteView DisplayText Formatter works on Tokens:

First, create the needed business objects, for example type Client with the following properties:

C#
public class Client
{
public Client(string name, string email, string imageSource)
{
this.Name = name;
this.Email = email;
this.ImageSource = imageSource;
}
public string Name { get; set; }
public string Email { get; set; }
public string ImageSource { get; set; }
}
 

Then create a ViewModel with a collection of Client objects:

C#
public class ViewModel
{
public ObservableCollection<Client> Source { get; set; }
public ViewModel()
{
this.Source = new ObservableCollection<Client>()
{
new Client("Freda Curtis", "fcurtis@mail.com", "available32.png"),
new Client("Jeffery Francis", "jfrancis@mail.com", "away32.png"),
new Client("Eva Lawson", "elawson@mail.com", "available32.png"),
new Client("Emmett Santos", "esantos@mail.com", "busy32.png"),
new Client("Theresa Bryan", "tbryan@mail.com", "available32.png"),
new Client("Jenny Fuller", "jfuller@mail.com", "busy32.png"),
new Client("Terrell Norris", "tnorris@mail.com", "away32.png"),
new Client("Eric Wheeler", "ewheeler@mail.com", "away32.png"),
new Client("Nida Carty", "ncarty@mail.com", "away32.png"),
new Client("Niki Samaniego", "nsamaniego@mail.com", "busy32.png")
};
}
}
 

Finally, use the following snippet to declare a RadAutoCompleteView in XAML:

XAML

191
Telerik UI for Xamarin

<telerikInput:RadAutoCompleteView x:Name="radAutoCompleteView"
ItemsSource="{Binding Source}"
TextSearchPath="Name"
DisplayTextFormatter="Email"
BackgroundColor="White"
DisplayMode="Tokens"
SuggestionViewHeight="150">
</telerikInput:RadAutoCompleteView>
 

Where the telerikInput namespace is the following:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

Here is how the DisplayText Formatter looks in both cases:

A sample DisplayText Formatter example can be found in the AutoCompleteView/Features folder of


the SDK Samples Browser application.
 

See Also
 Data Binding
 Events
 Methods

192
Telerik UI for Xamarin

Events
RadAutoCompleteView exposes the following events:

 TextChanged: Occurs when the text is changed. The TextChanged event handler receives a
TextChangedEventArgs argument containing data related to this event. The
TextChangedEventArgs provides the following properties:
 NewTextValue(string): which gets the new text value.
 OldTextValue(string): that gets the old text value.

You can find a working demo labeled Remote Search in the AutoCompleteView/Features folder of
the SDK Samples Browser application.
 

 SuggestionItemSelected: Occurs when an item is selected from the SuggestionsView. The


SuggestionItemSelected event handler receives two parameters:
 The sender argument which is of type object, but can be cast to the
RadAutoCompleteView type.
 A SuggestionItemSelectedEventArgs object which has a reference to the selected item
through its DataItem property.
 FilteredItemsChanged: Occurs when the FilteredItems collection is updated. The
FilteredItemsChanged event handler receives two parameters:
 The sender argument which is of type object, but can be cast to the
RadAutoCompleteView type.
 A FilteredItemsChangedEventArgs object which has a reference to filtered items
collection its FilteredItems property.
 Completed: Occurs when the user finalizes the text in an entry with the return key.

See Also
 Key Features
 Tokens Support
 Styling Options

193
Telerik UI for Xamarin

Methods
RadAutoCompleteView exposes the ability to explicitly show/hide the popup containing all items
through the following methods:

 ShowSuggesstions: Shows all items when the control recieves focus.


 HideSuggestions: Hide all items when the focus of the control is lost.

Example
The example below uses ShowSuggesstions method to display all items as soon as the
AutoCompleteView receives the focus.

First, create the needed business objects, for example type Client with the following properties:

C#
public class Client
{
public Client(string name, string email, string imageSource)
{
this.Name = name;
this.Email = email;
this.ImageSource = imageSource;
}
public string Name { get; set; }
public string Email { get; set; }
public string ImageSource { get; set; }
}
 

Then create a ViewModel with a collection of Client objects:

C#
public class ViewModel
{
public ObservableCollection<Client> Source { get; set; }
public ViewModel()
{
this.Source = new ObservableCollection<Client>()
{
new Client("Freda Curtis", "fcurtis@mail.com", "available32.png"),
new Client("Jeffery Francis", "jfrancis@mail.com", "away32.png"),
new Client("Eva Lawson", "elawson@mail.com", "available32.png"),
new Client("Emmett Santos", "esantos@mail.com", "busy32.png"),
new Client("Theresa Bryan", "tbryan@mail.com", "available32.png"),
new Client("Jenny Fuller", "jfuller@mail.com", "busy32.png"),
new Client("Terrell Norris", "tnorris@mail.com", "away32.png"),
new Client("Eric Wheeler", "ewheeler@mail.com", "away32.png"),

194
Telerik UI for Xamarin

new Client("Nida Carty", "ncarty@mail.com", "away32.png"),


new Client("Niki Samaniego", "nsamaniego@mail.com", "busy32.png")
};
}
}
 

Declare the RadAutoCompleteView in XAML:

XAML
<telerikInput:RadAutoCompleteView x:Name="autoCompleteView"
ImagePath="ImageSource"
ItemsSource="{Binding Source}"
TextSearchPath="Name"
Watermark="Show Suggestions on focus"/>
 

Use the following code to attach the focused event to the control:

C#
this.autoCompleteView.Focused += this.AutoCompleteView_Focused;
 

and call the ShowSuggestions method inside the event:

C#
private void AutoCompleteView_Focused(object sender, FocusEventArgs e)
{
this.autoCompleteView.ShowSuggestions();
}
 

Here is the result:

195
Telerik UI for Xamarin

See Also
 Key Features
 Tokens Support
 Styling Options

196
Telerik UI for Xamarin

Filtering
The RadAutoCompleteView control allows users to define custom filtering logic through the following
property:

 Filter (IAutoCompleteFilter): Defines the function that will be used to filter items.

The IAutoCompleteFilter interface contains a Filter (bool) function that is called by


RadAutoCompleteView control in order to filter items. The Filter function provides the following
properties:

 item: The item to be checked.


 searchText: The current text in the RadAutoCompleteView control.
 completionMode: The current CompletionMode of RadAutoCompleteView.

The function returns true when the item is added into RadAutoCompleteView FilteredItems
collection, otherwise it returns false and the item won't be added into RadAutoCompleteView
FilteredItems collection.

The RadAutoCompleteView TextSearchPath property is required in custom filtering scenarios.


 

FilteredItems collection
FilteredItems bindable property allows you to access the collection containing the search results of
the AutoCompleteView. The property can be used in scenarios where the search results are
visualized at a different place or inside another container.

Example
Here is an example how the RadAutoCompleteView Custom Filtering works when searching in two
properties:

First, create the needed business objects, for example type Person with the following properties:

C#
public class Person
{
public Person(string firstName, string lastName)
{
this.FirstName = firstName;
this.LastName = lastName;
}

public string FirstName { get; set; }

public string LastName { get; set; }

197
Telerik UI for Xamarin

}
 

Then create a CustomFilterViewModel with a collection of Person objects:

C#
public class CustomFilteringViewModel
{
public CustomFilteringViewModel()
{
this.Source = new ObservableCollection<Person>()
{
new Person("Freda", "Curtis"),
new Person("Jeffery", "Francis"),
new Person("Eva", "Lawson"),
new Person("Emmett", "Santos"),
new Person("Theresa", "Bryan"),
new Person("Terrell", "Norris"),
new Person("Eric", "Wheeler"),
new Person("Alfredo", "Thornton"),
new Person("Roberto", "Romero"),
new Person("Orlando", "Mathis"),
new Person("Eduardo", "Thomas"),
new Person("Harry", "Douglas"),
new Person("Merry", "Lasker")
};

this.Filter = new CustomAutoCompleteViewFilter();


}

public ObservableCollection<Person> Source { get; set; }

public CustomAutoCompleteViewFilter Filter { get; set; }


}
 

After, create a class for example CustomAutoCompleteViewFilter that implements the


IAutoCompleteFilter interface:

C#
public class CustomAutoCompleteViewFilter : IAutoCompleteFilter
{
public bool Filter(object item, string searchText, CompletionMode completionMode)
{
Person person = (Person)item;
string lowerFirstName = person.FirstName.ToLower();
string lowerLastName = person.LastName.ToLower();
string lowerSearchText = searchText.ToLower();
return lowerFirstName.Contains(lowerSearchText) ||
lowerLastName.Contains(lowerSearchText);
}
}

198
Telerik UI for Xamarin

Finally, use the following snippet to declare a RadAutoCompleteView in XAML:

XAML
<telerikInput:RadAutoCompleteView x:Name="аutoCompleteView"
Filter="{Binding Filter}"
TextSearchPath="FirstName"
ItemsSource="{Binding Source}"
Watermark="Search here..."
SuggestionViewHeight="300">
<telerikInput:RadAutoCompleteView.SuggestionItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<Label Text="{Binding FirstName}"/>
<Label Text="{Binding LastName}"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</telerikInput:RadAutoCompleteView.SuggestionItemTemplate>
</telerikInput:RadAutoCompleteView>
 

Where the telerikInput namespace is the following:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

Here is the result:

199
Telerik UI for Xamarin

A sample Custom Filtering example can be found in the AutoCompleteView/Features folder of the
SDK Samples Browser application.
 

Handling Punctuation
By default, the .NET string.Contains method will take all punctuation into consideration. If you
find punctuation to be hindering your user experience, you can use a custom filter that removes the
punctuation before the strings are compared.

For example, if the source string is Main Street, 101 and the user searches Main Street 101,
string.Contains will return false and the result will not appear in the FilteredItems view. The custom
filter below removes the commas before the string is used with the Contains method.

public class CustomAutoCompleteViewFilter : IAutoCompleteFilter


{
public bool Filter(object item, string searchText, CompletionMode completionMode)
{
var googleSearchResult = (string)item;

// Remove commas from the source value before comparing with the search term
var googleSearchResultNoCommas = googleSearchResult.Replace(",", "");

var normalizedPlace = googleSearchResultNoCommas.ToLowerInvariant();


var normalizedSearchText = searchText.ToLowerInvariant();

return normalizedPlace.Contains(normalizedSearchText);
}

200
Telerik UI for Xamarin

}
 

See Also
 Remote Search
 Events
 Methods

201
Telerik UI for Xamarin

Remote Search
The Remote Search functionality of the RadAutoCompleteView control allows you to easily take the
user input, trigger custom searching algorithm and assign the results to the ItemSource of the
control.

 LoadingTemplate (DataTemplate): Defines the loading message.

Implement your custom searching algorithm inside the body of the TextChanged event handler.

Example
Here is an example how the RadAutoCompleteView Remote Search works:

First, create the needed business objects, for example type Client with the following properties:

C#
public class Client
{
public Client(string name, string email, string imageSource)
{
this.Name = name;
this.Email = email;
this.ImageSource = imageSource;
}
public string Name { get; set; }
public string Email { get; set; }
public string ImageSource { get; set; }
}
 

Then create a ViewModel with a collection of Client objects:

C#
public class ViewModel
{
public ObservableCollection<Client> Source { get; set; }
public ViewModel()
{
this.Source = new ObservableCollection<Client>()
{
new Client("Freda Curtis", "fcurtis@mail.com", "available32.png"),
new Client("Jeffery Francis", "jfrancis@mail.com", "away32.png"),
new Client("Eva Lawson", "elawson@mail.com", "available32.png"),
new Client("Emmett Santos", "esantos@mail.com", "busy32.png"),
new Client("Theresa Bryan", "tbryan@mail.com", "available32.png"),
new Client("Jenny Fuller", "jfuller@mail.com", "busy32.png"),
new Client("Terrell Norris", "tnorris@mail.com", "away32.png"),

202
Telerik UI for Xamarin

new Client("Eric Wheeler", "ewheeler@mail.com", "away32.png"),


new Client("Nida Carty", "ncarty@mail.com", "away32.png"),
new Client("Niki Samaniego", "nsamaniego@mail.com", "busy32.png")
};
}
}
 

Use the following snippet to declare a RadAutoCompleteView in XAML:

XAML
<telerikInput:RadAutoCompleteView x:Name="autoCompleteView"
TextChanged="OnTextChanged"
TextSearchPath="Name"
Watermark="Remote Search..."
SuggestionViewHeight="200">
<telerikInput:RadAutoCompleteView.LoadingTemplate>
<DataTemplate>
<StackLayout Orientation="Horizontal"
HorizontalOptions="Center"
Margin="0, 20, 0, 20">
<Label Text="Searching... " FontSize="16" TextColor="#8E8E93"/>
<telerikPrimitives:RadBusyIndicator x:Name="busyIndicator"
HeightRequest="24"
WidthRequest="24"
IsBusy="True"
VerticalOptions="Start"
AnimationContentColor="Accent"
AnimationType="Animation9"/>
</StackLayout>
</DataTemplate>
</telerikInput:RadAutoCompleteView.LoadingTemplate>
<telerikInput:RadAutoCompleteView.NoResultsTemplate>
<DataTemplate>
<Label Text="No match was found for the specific search. Please try again."
HorizontalOptions="Center"
VerticalOptions="Center"/>
</DataTemplate>
</telerikInput:RadAutoCompleteView.NoResultsTemplate>
</telerikInput:RadAutoCompleteView>
 

Where you will need to add the following namespaces:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
 

Create a custom searching algorithm and assign the result to the control's ItemsSource inside the

203
Telerik UI for Xamarin

TextChanged event handler:

C#
public partial class RemoteSearch : ContentView
{
private ViewModel viewModel;
private string currentText;
private bool isRemoteSearchRunning;

public RemoteSearch()
{
InitializeComponent();

this.viewModel = new ViewModel();


this.BindingContext = viewModel;
}

private void OnTextChanged(object sender, TextChangedEventArgs e)


{
var autoCompleteView = (RadAutoCompleteView)sender;
autoCompleteView.ItemsSource = null;

this.currentText = e.NewTextValue ?? "";

if (this.currentText.Length >= autoCompleteView.SearchThreshold &&


!this.isRemoteSearchRunning)
{
this.isRemoteSearchRunning = true;
Device.StartTimer(TimeSpan.FromMilliseconds(1500), () =>
{
this.isRemoteSearchRunning = false;
string searchText = this.currentText.ToLower();
autoCompleteView.ItemsSource = this.viewModel.Source.Where(i =>
i.Name.ToLower().Contains(searchText));
return false;
});
}
}
}
 

This is the result when LoadingTemplate is searching for results:

204
Telerik UI for Xamarin

This is the search complete results:

A sample Remote Search example can be found in the AutoCompleteView/Features folder of the
SDK Samples Browser application.
 

205
Telerik UI for Xamarin

See Also
 Data Binding
 Events
 Filtering

206
Telerik UI for Xamarin

Localization
RadAutoCompleteView for Xamarin provides language localization. In short, you can translate the
used across the AutoCompleteView phrases to other languages, so that your app can be adapted to
different regions.

To learn in details about the localization process of Telerik UI for Xamarin components, please go
through the common Localization and Globalization topic.
 
In RadAutoCompleteView you can localization the following string:

Localization Key Default Value


AutoComplete_NoResultsMessage No Results Found.
The localization key refers to the default message that is shown in case there are no result
corresponding to the user input:

207
Telerik UI for Xamarin

The other option for setting this message is through the NoResultMessage property of
RadAutoCompleteView. For more details on this go to Key Features: NoResults Message.
 

See Also
 Key Features
 Data Binding
 Events
 Filtering

208
Telerik UI for Xamarin

RadAutoCompleteView Custom Templates


Overview
If the default templates of the control do not suit your needs, you can easily define a custom
template. The available templates for customizing are:

 NoResults Template(DataTemplate): Defines the template visualised when there are no


suggestions found.
 ShowMore Template(DataTemplate) for Tokens Support: Defines the template used to
create show more view when DisplayMore="Tokens".
 Loading Template(DataTemplate) for Remote Search functionality: Defines the loading
message in RemoteSearch state.
 Tokens Template(DataTemplate) for Tokens Support: Defines the template used to vizualize
the tokens.
 SuggestionItem Template(DataTemplate): Defines the template that will be used to create
each of the suggestions.
 SuggestionView Template(DataTemplate): Defines the template used to visualize the filtered
items.

Example
NoResults Template
Here is an example how the NoResults Template could be defined:

XAML
<telerikInput:RadAutoCompleteView.NoResultsTemplate>
<DataTemplate>
<Label Text="No match was found for the specific search. Please try again."/>
</DataTemplate>
</telerikInput:RadAutoCompleteView.NoResultsTemplate>
 

ShowMore Template
XAML definition of ShoWMore Template:

XAML
<telerikInput:RadAutoCompleteView.ShowMoreTemplate>
<DataTemplate>
<Label Text="{Binding Path=., StringFormat='+{0} more'}"
VerticalTextAlignment="Center" />
</DataTemplate>
</telerikInput:RadAutoCompleteView.ShowMoreTemplate>
 

209
Telerik UI for Xamarin

A sample NoResult and ShowMore Template example can be found in the


AutoCompleteView/Features/Tokens folder of the SDK Samples Browser application.
 

Loading Template
XAML definition of the Loading Template:

XAML
<telerikInput:RadAutoCompleteView.LoadingTemplate>
<DataTemplate>
<StackLayout Orientation="Horizontal"
HorizontalOptions="Center"
Margin="0, 20, 0, 20">
<Label Text="Searching... " FontSize="16" TextColor="#8E8E93"/>
<telerikPrimitives:RadBusyIndicator x:Name="busyIndicator"
HeightRequest="24"
WidthRequest="24"
IsBusy="True"
VerticalOptions="Start"
AnimationContentColor="Accent"
AnimationType="Animation9"/>
</StackLayout>
</DataTemplate>
</telerikInput:RadAutoCompleteView.LoadingTemplate>
 

A sample Loading Template definition can be found in the


AutoCompleteView/Features/RemoteSearch folder of the SDK Samples Browser application.
 

See Also
 Token Template
 SuggestionItem Template
 SuggestionView Template

210
Telerik UI for Xamarin

Token Customization
Token Template
RadAutoCompleteView provides an option to customize the template that vizualize the tokens
through TokenTemplate property.

 TokenTemplate (DataTemplate): Defines the template used to vizualize the tokens.

Example
Here is an example how to use the RadAutoCompleteView TokenTemplate:

First, create the needed business objects, for example type City with the following properties:

C#
public class City
{
public string Name { get; set; }
public City(string name)
{
this.Name = name;
}
}
 

Then create a ViewModel with a collection of City objects:

C#
public class TokensViewModel
{
public List<City> Source { get; set; }
public TokensViewModel()
{
this.Source = new List<City>()
{
new City("Madrid"),
new City("Paris"),
new City("Barcelona"),
new City("New York"),
new City("Budapest"),
new City("Sofia"),
new City("Palermo"),
new City("Melbourne"),
new City("London"),
new City("Nagoya"),
new City("Tokyo"),

211
Telerik UI for Xamarin

new City("Atlanta"),
new City("Toronto"),
new City("Athens"),
};
}
}
 

let's use the following snippet to declare a RadAutoCompleteView and its TokenTemplate with
RadDataGrid in XAML:

XAML
<telerikInput:RadAutoCompleteView x:Name="autoCompleteViewTokensTemplate"
ItemsSource="{Binding Source}"
DisplayMode="Tokens"
SuggestionViewHeight="150"
TextSearchPath="Name"
Watermark="Search Here..."
BackgroundColor="White">
<telerikInput:RadAutoCompleteView.TokenTemplate>
<DataTemplate>
<telerikPrimitives:RadBorder BorderColor="Brown"
BorderThickness="2"
Margin="2">
<StackLayout Orientation="Horizontal"
BackgroundColor="LightGreen"
Margin="2">
<Label Text="{Binding Name}"
TextColor="Black"
VerticalTextAlignment="Center"
Margin="2" />
<Label FontFamily="{StaticResource IconsFontFamily}"
Text="&#xE80A;" FontSize="Small"
VerticalTextAlignment="Center"
TextColor="Black"
Margin="2">
<Label.GestureRecognizers>
<TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped"/>
</Label.GestureRecognizers>
</Label>
</StackLayout>
</telerikPrimitives:RadBorder>
</DataTemplate>
</telerikInput:RadAutoCompleteView.TokenTemplate>
</telerikInput:RadAutoCompleteView>
 

and the code for Label.GestureRecognizer property:

C#
private void TapGestureRecognizer_Tapped(object sender, EventArgs e)
{

212
Telerik UI for Xamarin

var closeLabel = sender as Label;


if (closeLabel != null)
{
var item = closeLabel.BindingContext as City;
if (item != null)
{
this.autoCompleteViewTokensTemplate.Tokens.Remove(item);
}
}
}
 

Here is the result:

A sample Tokens Template example can be found in the AutoCompleteView/Templates folder of the
SDK Samples Browser application.
 

See Also
 Tokens Support
 Data Binding

213
Telerik UI for Xamarin

Suggestion Items Customization


SuggestionItem Template
Whenever the default template does not fit a particular scenario you can use the
SuggestionItemTemplate property to define a custom template.

 SuggestionItemTemplate (DataTemplate): Defines the template that will be used to create


each of the suggestions.
 SuggestionItemTextColor: Defines the Text Color of the suggested item of the component.

Example
Here is an example how to use the RadAutoCompleteView SuggestionItemTemplate:

First, create the needed business objects, for example type Client with the following properties:

C#
public class Client
{
public Client(string name, string email, string imageSource)
{
this.Name = name;
this.Email = email;
this.ImageSource = imageSource;
}
public string Name { get; set; }
public string Email { get; set; }
public string ImageSource { get; set; }
}
 

Then create a ViewModel with a collection of Client objects:

C#
public class ViewModel
{
public ObservableCollection<Client> Source { get; set; }
public ViewModel()
{
this.Source = new ObservableCollection<Client>()
{
new Client("Freda Curtis", "fcurtis@mail.com", "available32.png"),
new Client("Jeffery Francis", "jfrancis@mail.com", "away32.png"),
new Client("Eva Lawson", "elawson@mail.com", "available32.png"),
new Client("Emmett Santos", "esantos@mail.com", "busy32.png"),
new Client("Theresa Bryan", "tbryan@mail.com", "available32.png"),

214
Telerik UI for Xamarin

new Client("Jenny Fuller", "jfuller@mail.com", "busy32.png"),


new Client("Terrell Norris", "tnorris@mail.com", "away32.png"),
new Client("Eric Wheeler", "ewheeler@mail.com", "away32.png"),
new Client("Nida Carty", "ncarty@mail.com", "away32.png"),
new Client("Niki Samaniego", "nsamaniego@mail.com", "busy32.png")
};
}
}
 

Finally, use the following snippet to declare a RadAutoCompleteView in XAML:

XAML
<telerikInput:RadAutoCompleteView x:Name="AutoComplete"
ItemsSource="{Binding Source}"
TextSearchPath="Name"
VerticalOptions="Start"
Watermark="Search here...">
<telerikInput:RadAutoCompleteView.SuggestionItemTemplate>
<DataTemplate>
<ViewCell>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Label Margin="5"
FontSize="24"
Text="{Binding Name}"
TextColor="Black"/>
<Image Grid.Column="1"
Margin="5"
HeightRequest="20"
Source="{Binding ImageSource}"
WidthRequest="20"/>
</Grid>
</ViewCell>
</DataTemplate>
</telerikInput:RadAutoCompleteView.SuggestionItemTemplate>
</telerikInput:RadAutoCompleteView>
 

Where the telerikInput namespace is the following:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

Here is the result:

215
Telerik UI for Xamarin

A sample SuggestionItemTemplate example can be found in the AutoCompleteView/Features folder


of the SDK Samples Browser application.
 

See Also
 Tokens Support
 Data Binding

216
Telerik UI for Xamarin

Suggestion View Customization


SuggestionView Template
RadAutoCompleteView provides the option to change the default template that visualize the filtered
items and implement a custom template using SuggestionViewTemplate property.

 SuggestionViewTemplate (DataTemplate): Defines the template used to visualize the filtered


items

Example
Here is an example how to use the RadAutoCompleteView SuggestionViewTemplate:

First, create the needed business objects, for example type Person with the following properties:

C#
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
 

Then create a ViewModel with a collection of Person objects:

C#
public class ViewModel
{
public ViewModel()
{
this.Items = new ObservableCollection<Person>
{
new Person{FirstName = "Alex", LastName = "Ramos"},
new Person{FirstName = "Ben", LastName = "Johnas"},
new Person{FirstName = "Carlos", LastName = "Romero"},
new Person{FirstName = "Anna", LastName = "Kurtis"},
new Person{FirstName = "Eva", LastName = "Johnson"},
new Person{FirstName = "Terry", LastName = "Willson"},
new Person{FirstName = "John", LastName = "Doe"},
new Person{FirstName = "Teressa", LastName = "Bryan"},
new Person{FirstName = "Nick", LastName = "Norris"},
new Person{FirstName = "Eric", LastName = "Wheeler"},
new Person{FirstName = "William", LastName = "Montero"},
new Person{FirstName = "Sam", LastName = "Browm"},
new Person{FirstName = "Ivan", LastName = "Petrov"},
new Person{FirstName = "Martin", LastName = "Romero"},

217
Telerik UI for Xamarin

new Person{FirstName = "Eva", LastName = "Gonzales"},


new Person{FirstName = "An", LastName = "Watson"},
new Person{FirstName = "David", LastName = "Alvarez"},
new Person{FirstName = "Danny", LastName = "Johnes"},
new Person{FirstName = "Pawel", LastName = "Ivanon"},
new Person{FirstName = "Henrry", LastName = "Carty"},
new Person{FirstName = "Nick", LastName = "Morales"},
new Person{FirstName = "Eric", LastName = "Samaniego"},
new Person{FirstName = "William", LastName = "Curtis"},
new Person{FirstName = "James", LastName = "Santos"}
};
}

public ObservableCollection<Person> Items { get; set; }


}
 

Finally, let's use the following snippet to declare a RadAutoCompleteView and its
SuggestionViewTemplate with RadDataGrid in XAML:

XAML
<telerikInput:RadAutoCompleteView x:Name="autoCompleteView"
ItemsSource="{Binding Items}"
TextSearchPath="FirstName"
DisplayMode="Tokens"
VerticalOptions="Start"
CompletionMode="Contains"
Watermark="Search here..."
SuggestionViewHeight="150">
<telerikInput:RadAutoCompleteView.SuggestionViewTemplate>
<DataTemplate>
<telerikDataGrid:RadDataGrid x:Name="dataGrid"
ItemsSource="{Binding FilteredItems, Source={x:Reference autoCompleteView}}"
AutoGenerateColumns="False"
GridLinesVisibility="Vertical"
BackgroundColor="LightGray"
SelectionChanged="DataGrid_SelectionChanged">
<telerikDataGrid:RadDataGrid.Columns>
<telerikDataGrid:DataGridTextColumn HeaderText="First Name"
PropertyName="FirstName"
CanUserSort="False"
CanUserGroup="False"
CanUserFilter="False"
HeaderStyle="{StaticResource CustomDataGridColumnHeaderStyle}"
CellContentStyle="{StaticResource CustomCellContentStyle}"/>
<telerikDataGrid:DataGridTextColumn HeaderText="Last Name"
PropertyName="LastName"
CanUserSort="False"
CanUserGroup="False"
CanUserFilter="False"
HeaderStyle="{StaticResource CustomDataGridColumnHeaderStyle}"
CellContentStyle="{StaticResource CustomCellContentStyle}"/>
</telerikDataGrid:RadDataGrid.Columns>

218
Telerik UI for Xamarin

</telerikDataGrid:RadDataGrid>
</DataTemplate>
</telerikInput:RadAutoCompleteView.SuggestionViewTemplate>
</telerikInput:RadAutoCompleteView>
 

Where you will need to add the following namespaces:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
xmlns:telerikDataGrid="clr-namespace:Telerik.XamarinForms.DataGrid;assembly=Telerik.Xa
marinForms.DataGrid"
 

Here is the result:

A sample SuggestionView Template example can be found in the AutoCompleteView/Templates


folder of the SDK Samples Browser application.
 

See Also
 Tokens Support
 Data Binding

219
Telerik UI for Xamarin

Styling Options
RadAutoCompleteView control provides the following Style properties for customizing its look:

 Font Options(FontAttributes, FontFamily, FontSize): Define the font options to the text of the
RadAutoCompleteView.
 TextColor: Defines the textcolor of the component.
 SuggestionItemTextColor: Defines the highlightcolor of the selection items.

Here is an example how to use the SuggestionItemTextColor property:

First, create the needed business objects, for example type Client with the following properties:

C#
public class Client
{
public Client(string name, string email, string imageSource)
{
this.Name = name;
this.Email = email;
this.ImageSource = imageSource;
}
public string Name { get; set; }
public string Email { get; set; }
public string ImageSource { get; set; }
}
 

Then create a ViewModel with a collection of Client objects:

C#
public class ViewModel
{
public ObservableCollection<Client> Source { get; set; }
public ViewModel()
{
this.Source = new ObservableCollection<Client>()
{
new Client("Freda Curtis", "fcurtis@mail.com", "available32.png"),
new Client("Jeffery Francis", "jfrancis@mail.com", "away32.png"),
new Client("Eva Lawson", "elawson@mail.com", "available32.png"),
new Client("Emmett Santos", "esantos@mail.com", "busy32.png"),
new Client("Theresa Bryan", "tbryan@mail.com", "available32.png"),
new Client("Jenny Fuller", "jfuller@mail.com", "busy32.png"),
new Client("Terrell Norris", "tnorris@mail.com", "away32.png"),
new Client("Eric Wheeler", "ewheeler@mail.com", "away32.png"),
new Client("Nida Carty", "ncarty@mail.com", "away32.png"),
new Client("Niki Samaniego", "nsamaniego@mail.com", "busy32.png")
};

220
Telerik UI for Xamarin

}
}
 

Where the telerikInput namespace is the following:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

Finally, use the following snippet to declare a RadAutoCompleteView in XAML with


SuggestionItemTextColor property:

XAML
<telerikInput:RadAutoCompleteView x:Name="autoCompleteView1"
ItemsSource="{Binding Source}"
TextSearchPath="Name"
Watermark="Search Here..."
SuggestionItemTextColor="BlueViolet"
SuggestionViewHeight="100"
SuggestionViewBackgroundColor="#DBDBDB" />
 

Highlight Customization
In case a custom template is used, the user can achieve text highlighting inside the
RadAutoCompleteView.SuggestionItemTemplate using SuggestionItemLabel and the following
namespace:

XAML
xmlns:autoCompleteView="clr-namespace:Telerik.XamarinForms.Input.AutoCompleteView;asse
mbly=Telerik.XamarinForms.Input"
 

The AutoCompleteView SuggestionItemLabel exposes the following properties:

 HighlightTextColor
 HighlightText
 UnformattedText

Example
First, create the needed business objects, for example type Client with the following properties:

C#
public class Client
{
public Client(string name, string email, string imageSource)

221
Telerik UI for Xamarin

{
this.Name = name;
this.Email = email;
this.ImageSource = imageSource;
}
public string Name { get; set; }
public string Email { get; set; }
public string ImageSource { get; set; }
}
 

Then create a ViewModel with a collection of Client objects:

C#
public class ViewModel
{
public ObservableCollection<Client> Source { get; set; }
public ViewModel()
{
this.Source = new ObservableCollection<Client>()
{
new Client("Freda Curtis", "fcurtis@mail.com", "available32.png"),
new Client("Jeffery Francis", "jfrancis@mail.com", "away32.png"),
new Client("Eva Lawson", "elawson@mail.com", "available32.png"),
new Client("Emmett Santos", "esantos@mail.com", "busy32.png"),
new Client("Theresa Bryan", "tbryan@mail.com", "available32.png"),
new Client("Jenny Fuller", "jfuller@mail.com", "busy32.png"),
new Client("Terrell Norris", "tnorris@mail.com", "away32.png"),
new Client("Eric Wheeler", "ewheeler@mail.com", "away32.png"),
new Client("Nida Carty", "ncarty@mail.com", "away32.png"),
new Client("Niki Samaniego", "nsamaniego@mail.com", "busy32.png")
};
}
}
 

Where the telerikInput namespace is the following:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

and the autoCompleteView namespace is the following:

XAML
xmlns:autoCompleteView="clr-namespace:Telerik.XamarinForms.Input.AutoCompleteView;asse
mbly=Telerik.XamarinForms.Input"
 

Finally, use the following snippet to declare a RadAutoCompleteView in XAML with

222
Telerik UI for Xamarin

SuggestionItemLabel property:

XAML
<telerikInput:RadAutoCompleteView x:Name="autoCompleteView2"
ItemsSource="{Binding Source}"
TextSearchPath="Name"
Watermark="Search Here..."
SuggestionViewHeight="100"
SuggestionViewBackgroundColor="#DBDBDB">
<telerikInput:RadAutoCompleteView.SuggestionItemTemplate>
<DataTemplate>
<ViewCell>
<autoCompleteView:SuggestionItemLabel TextColor="Black"
HighlightTextColor="BlueViolet"
UnformattedText="{Binding Name}"
HighlightText="{Binding Source={x:Reference autoCompleteView2}, Path=Text}"/>
</ViewCell>
</DataTemplate>
</telerikInput:RadAutoCompleteView.SuggestionItemTemplate>
</telerikInput:RadAutoCompleteView>
 

Here is the result:

A sample HighlightText example can be found on the AutoCompleteView/Features folder of the SDK
Samples Browser application.
 

See Also
223
Telerik UI for Xamarin

 SuggestionItemTemplate
 Data Binding
 Events

224
Telerik UI for Xamarin

Overview
Telerik BadgeView for Xamarin allows you to display badges in your application. Badges can be
used for an additional marker for any element: to decorate avatars, navigation menus, or other
components in the application when the visual notification is needed.

In addition you can change the badge look setting different predefined badge types, using templates
and various styling options.

Figure 1: RadBadgeView Overview

Key features
 BadgeView allows you to specify the badge Position based on its content. Visit the Badge
Position article for more details on this feature.
 Alignment - You can easily align the badge according to its content. For more details about
badge alignment options, visit the Badge Alignment article.

225
Telerik UI for Xamarin

 You can choose whether to have an Animation while displaying the badge. In addition, you
can specify the animation duration and animation easing. For more details and example ->
navigate to Badge Animation topic.
 Badge Types - You can choose in between various predefined badge types. Also, you have
the option to customize and style the badge types. More information about how-to define,
style and customize the predefined badge types can be found in the Badge Types article.
 Flexible Styling API and Customization options – Allows you to change the BadgeView
BackgroundColor, Border Thickness and Color. Also, we have exposed API which you can
use to fully customize and style the badge indicator. For more details, please visit our Badge
Styling and Badge Customization articles.

See Also
 Visual Structure
 Getting Started
 Key Features
 Badge Position and Alignment
 Badge Animation
 Badge Types
 Styling
 Customization

226
Telerik UI for Xamarin

Visual Structure
Here are described all visual elements used in the BadgeView for Xamarin.

Legend
 BadgeView - The BadgeView control which includes the Badge marker(indicator) and the
content the marker is related to.
 Badge - The marker that can be used for notifications, statuses, etc.
 BadgeView Content - The Badge marker/indicator is positioned based on the content inside
the RadBadgeView. Without a content the Badge won't be visualized.

See Also
 Getting Started
 Key Features
 Badge Position and Alignment
 Badge Animation
 Badge Types

227
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadBadgeView control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadBadgeView control
 Adding RadBadgeView Content

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic. Note that RadBadgeView does not have a separate nuget package.
 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadBadgeView component:

Platform Assemblies
Portable Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.SkiaSharp.dll
Android Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.SkiaSharp.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.SkiaSharp.dll
UWP Telerik.Core.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.SkiaSharp.dll

3. Adding RadBadgeView control

228
Telerik UI for Xamarin

If your app is setup, you are ready to add a RadBadgeView control to your page.

XAML
<telerikPrimitives:RadBadgeView/>
 

C#
var badge = new RadBadgeView();
 

In addition to this you need to add the following namespace:

XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
 

C#
using Telerik.XamarinForms.Primitives;
 

4. Adding RadBadgeView Content and BadgeText


The Badge marker(indicator) which is part of the RadBadgeView will be visualized only if
RadBadgeView Content property is set.
 

Example
Add the RadBadgeView and set Content property and BadgeText property.

XAML
<telerikPrimitives:RadBadgeView BadgeText="1">
<telerikPrimitives:RadBadgeView.Content>
<telerikPrimitives:RadBorder WidthRequest="80"
HeightRequest="80"
BorderThickness="1"
BorderColor="LightGray">
<Label Text="Telerik Badge View for Xamarin"
FontSize="14"
VerticalTextAlignment="Center"
HorizontalTextAlignment="Center"/>
</telerikPrimitives:RadBorder>
</telerikPrimitives:RadBadgeView.Content>
</telerikPrimitives:RadBadgeView>
 

C#

229
Telerik UI for Xamarin

var badgeView = new RadBadgeView();


badgeView.BadgeText = "1";
badgeView.Content = new RadBorder
{
WidthRequest = 80,
HeightRequest = 80,
BorderThickness = 1,
BorderColor = Color.LightGray,
Content = new Label
{
Text = "Telerik Badge View for Xamarin",
FontSize = 14,
VerticalTextAlignment = TextAlignment.Center,
HorizontalTextAlignment = TextAlignment.Center,
},
};
 

Here is the result:

Figure 1: BadgeView Getting Started

BadgeView Getting Started Example can be found in SDK


Browser/Examples/BadgeViewControl/GettingStartedCategory folder.
 

See Also

230
Telerik UI for Xamarin

 Key Features
 Badge Position and Alignment
 Badge Animation
 Badge Types

231
Telerik UI for Xamarin

Key Features
The purpose of this help article is to show you the key features of the RadBadgeView control.

Content
The BadgeView will be visualized only if its Content property is set.
 

 Content(of type Xamarin.Formd.View): Defines the content of the RadBadgeView.

You must define a content. The Badge marker/indicatior is positioned based on the content inside
the RadBadgeView. Without a content the Badge won't be visualized.

XAML
<telerikPrimitives:RadBadgeView>
<telerikPrimitives:RadBadgeView.Content>
<!-- add the content of the RadBadgeView. For exmaple: Label, Image, Frame,
Border, Button, etc -->
</telerikPrimitives:RadBadgeView.Content>
</telerikPrimitives:RadBadgeView>
 

Example
There is a Button inside the Content. The BadgeText is updated on a ButtonClick.

XAML
<telerikPrimitives:RadBadgeView BadgeText="0"
VerticalOptions="Center"
HorizontalOptions="Center"
x:Name="badgeView">
<telerikPrimitives:RadBadgeView.Content>
<Button Text="Click me!"
Clicked="Button_Clicked"
BorderColor="Gray"
BorderWidth="2"
Padding="3"
VerticalOptions="Center"
HorizontalOptions="Center"/>
</telerikPrimitives:RadBadgeView.Content>
</telerikPrimitives:RadBadgeView>
 

and the page's code behind where is the button click implementation:

C#

232
Telerik UI for Xamarin

public partial class BadgeViewContent : ContentView


{
private int badgeCounter = 0;

public BadgeViewContent()
{
InitializeComponent();
}

private void Button_Clicked(object sender, EventArgs e)


{
badgeCounter++;
badgeView.BadgeText = badgeCounter.ToString();
}
}
 

And the result

Badge Text
With BadgeText property(string) you can define a text. The text will be displayed in the badge
marker.

Example
XAML
<telerikPrimitives:RadBadgeView BadgeText="Badge Text">
<telerikPrimitives:RadBadgeView.Content>
<telerikPrimitives:RadBorder WidthRequest="80"
HeightRequest="80"
BorderThickness="1"
BorderColor="LightGray">
<Label Text="Telerik Badge View for Xamarin"
FontSize="14"
VerticalTextAlignment="Center"

233
Telerik UI for Xamarin

HorizontalTextAlignment="Center"/>
</telerikPrimitives:RadBorder>
</telerikPrimitives:RadBadgeView.Content>
</telerikPrimitives:RadBadgeView>
 

You can fully customize the look & feel of the BadgeView, for detailed information check the Badge
Styling and Badge Customization articles.
 

Badge Position
BadgeHorizontalPosition

BadgeVerticalPosition

234
Telerik UI for Xamarin

Use the BadgeHorizontalPositon and BadgeVerticalPosition properties to position the


badge marker based on the content inside the RadBadgeView. The properties are of type
Telerik.XamarinForms.Primitives.BadgePosition and the available options are Start, Center and
End.

For more details about this check the Badge Position section.

Badge Alignment
BadgeHorizontalAlignment

BadgeVerticalAlignment

Specify the alignment of the badge based on the content inside the RadBadgeView using the
BadgeHorizontalAlignment and BadgeVerticalAlignment properties. The properties are of
type Telerik.XamarinForms.Primitives.BadgeAlignment and the available options are Start, Center
and End.

For more details about this check the Badge Alignment section.

Badge Offset

235
Telerik UI for Xamarin

Specify the horizontal/vertical distance between the content of the Badge and its alignment point
using the BadgeOffsetX and BadgeOffsetY properties.

For more details please visit our Badge Offset section.

Badge Animation
You can choose whether the badge marker/indicator will be displayed with animation. In addition you
can define the antimation duration and easing.

For more details please visit our Badge Animation article.

Badge Types

You can choose what will be the type of the badge by setting the BadgeType property(enumeration
of type Telerik.XamarinForms.Primitives.BadgeType). For more details please visit our Badge Types
article.

Badge Visibility
Change the Badge visibility state using the BadgeVisibility property (enum of type
Telerik.XamarinForms.Common.Visibility).

The available options are:

 Visible - The badge marker/indicator is visualized.


 Hidden - The badge marker/indicator is hidden.
 Collapsed - The badge marker/indicator is collapsed.

The default value of BadgeVisibility is Visible.

236
Telerik UI for Xamarin

Example with BadgeVisibility Hidden


XAML
<telerikPrimitives:RadBadgeView BadgeText="1" BadgeVisibility="Hidden">
<telerikPrimitives:RadBadgeView.Content>
<telerikPrimitives:RadBorder WidthRequest="80"
HeightRequest="80"
BorderThickness="1"
BorderColor="LightGray">
<Label Text="Telerik Badge View for Xamarin"
FontSize="14"
VerticalTextAlignment="Center"
HorizontalTextAlignment="Center"/>
</telerikPrimitives:RadBorder>
</telerikPrimitives:RadBadgeView.Content>
</telerikPrimitives:RadBadgeView>
 

Padding
 Padding(Xamarin.Forms.Thickness): Defines the inner padding of the BadgeView.

XAML
<telerikPrimitives:RadBadgeView BadgeText="Add" Padding="30">
<telerikPrimitives:RadBadgeView.Content>
<!-- add your content here -->
</telerikPrimitives:RadBadgeView.Content>
</telerikPrimitives:RadBadgeView>
 

237
Telerik UI for Xamarin

Integration with other Controls


BadgeView control can be integrated with other controls like ListView, SideDrawer, TabView, Button,
Label, Image, etc. It depends on the scenario you want to achieve.

238
Telerik UI for Xamarin

Sample Integration Example can be found in our Telerik UI for Xamarin Sample application and SDK
Browser application.

See Also
 Badge Position and Alignment
 Badge Animation
 Badge Types
 Badge Styling
 Badge Customization

239
Telerik UI for Xamarin

Alignment and Position


This article explains the options you can use to align and position the badge according to the
BadgeView Content.

Badge Position
You can use the following properties to specify the position of the badge according to its content:

 BadgeHorizontalPosition(of type Telerik.XamarinForms.Primitives.BadgePosition): Specifies


the horizontal BadgePosition of the badge. The following options are: Start, Center,
End. The default value is End.

 BadgeVerticalPosition(of type Telerik.XamarinForms.Primitives. BadgePosition): Specifies


the vertical BadgePosition of the badge. The following options are: Start, Center, End.
The default value is Start.

Badge Alignment
You can use the following properties to specify the alignment of the badge according to its content:

 BadgeHorizontalAlignment(of type Telerik.XamarinForms.Primitives.BadgeAlignment):


Specifies the horizontal alignment of the badge. The following options are: Start, Center,
End. The default value is Center.

240
Telerik UI for Xamarin

 BadgeVerticalAlignment(of type Telerik.XamarinForms.Primitives.BadgeAlignment):


Specifies the vertical alignment of the badge. The following options are: Start, Center,
End. The default value is End.

Badge Offset
Use the following properties to specify the horizontal/vertical distance between the content of the
Badge and its alignment point:

 BadgeOffsetX(double): Specifies the horizontal distance between the content of the Badge
and its alignment point. The default value is 0.
 BadgeOffsetY(double): Specifies the vertical distance between the content of the Badge and
its alignment point. The default value is 0.

Example with Badge Alignment, Position and Offset


Here is the BadgeView definition:

XAML
<telerikPrimitives:RadBadgeView BadgeText="12"
BadgeVerticalPosition="Center"
BadgeHorizontalAlignment="End"
BadgeOffsetX="-5"
VerticalOptions="Center">
<telerikPrimitives:RadBadgeView.Content>
<telerikInput:RadButton HeightRequest="40"
WidthRequest="180"
CornerRadius="20"
Text="Shopping Cart"
TextColor="White"
VerticalOptions="Center"

241
Telerik UI for Xamarin

VerticalContentAlignment="Center"
BackgroundColor="#0E88F2"/>
</telerikPrimitives:RadBadgeView.Content>
</telerikPrimitives:RadBadgeView>
 

And the result:

Sample Badge Alignment, Position, and Offset example can be found here.

See Also
 Badge Animation
 Predefined Badges

242
Telerik UI for Xamarin

Badge Animation
BadgeView allows you to display the badge indicator using animation. The following properties are
related to the Badge animation feature:

BadgeAnimationType(enum of type Telerik.XamarinForms.Primitives.BadgeAnimationType):


Specifies the type of the animation applied to the BadgeView. You can choose between two options:
None and Scale. The default BadgeAnimationType is Scale.

BadgeAnimationDuration(int): Specifies the duration for the badge animation in milliseconds. The
default value is 300.

BadgeAnimationEasing(Xamarin.Forms.Easing): Specifies the Easing of the badge animation. The


default value is SinInOut.

BadgeStartAnimationCommand(System.Windows.Input.ICommand): Gets the command that starts


the badge animation.

C#
this.badgeView.BadgeStartAnimationCommand.Execute(null);
 

Example
Here is the Animation properties set to the RadBadgeVierw control:

XAML
<telerikPrimitives:RadBadgeView BadgeAnimationDuration="900"
VerticalOptions="Center"
HorizontalOptions="Center"
BadgeAnimationEasing="BounceOut"
BadgeType="Available">
<telerikPrimitives:RadBadgeView.Content>
<Image WidthRequest="60"
HeightRequest="60"
VerticalOptions="Center"
HorizontalOptions="Center">
<Image.Source >
<OnPlatform x:TypeArguments="ImageSource" Default="sampleAvatar.png">
<On Platform="UWP">Assets\sampleAvatar.png</On>
</OnPlatform>
</Image.Source>
</Image>
</telerikPrimitives:RadBadgeView.Content>
</telerikPrimitives:RadBadgeView>
 

Badge Animation example is located inside the

243
Telerik UI for Xamarin

SDKBrowserApplication/Examples/BadgeViewControl/FeaturesCategory.
 

See Also
 Predefined Badges
 Badge Position and Alignment

244
Telerik UI for Xamarin

Badge Types

You can change the Badge type using one of the predefined badge types.

 BadgeType(of type Telerik.XamarinForms.Primitives.BadgeType): Specifies the type of the


Badge. The default value is Default

The available options are:

 Default
 Available
 Away
 DoNotDisturb
 Offline
 OutOfOffice,
 Dot
 Add
 Remove
 Rejected

Example
Define the BadgeView:

XAML
<telerikDataControls:RadListView x:Name="listView">
<telerikDataControls:RadListView.ItemTemplate>
<DataTemplate>
<telerikListView:ListViewTemplateCell>

245
Telerik UI for Xamarin

<StackLayout>
<telerikPrimitives:RadBadgeView x:Name="badge"
BadgeVerticalPosition="End"
BadgeOffsetX="-15"
BadgeOffsetY="-10"
BadgeType="{Binding .}"
HorizontalOptions="Center"
VerticalOptions="Center">
<telerikPrimitives:RadBadgeView.Content>
<Image WidthRequest="100"
HeightRequest="100">
<Image.Source >
<OnPlatform x:TypeArguments="ImageSource"
Default="sampleAvatar.png">
<On Platform="UWP">Assets\sampleAvatar.png</On>
</OnPlatform>
</Image.Source>
</Image>
</telerikPrimitives:RadBadgeView.Content>
</telerikPrimitives:RadBadgeView>
<Label HorizontalOptions="Center"
Text="{Binding .}"
FontSize="10"/>
</StackLayout>
</telerikListView:ListViewTemplateCell>
</DataTemplate>
</telerikDataControls:RadListView.ItemTemplate>
<telerikDataControls:RadListView.ItemStyle>
<telerikListView:ListViewItemStyle BackgroundColor="Transparent"/>
</telerikDataControls:RadListView.ItemStyle>
<telerikDataControls:RadListView.LayoutDefinition>
<telerikListView:ListViewGridLayout HorizontalItemSpacing="5"
VerticalItemSpacing="25"
ItemLength="140"
SpanCount="5"/>
</telerikDataControls:RadListView.LayoutDefinition>
</telerikDataControls:RadListView>
 

Use the following namespace:

XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
xmlns:telerikListView="clr-namespace:Telerik.XamarinForms.DataControls.ListView;assemb
ly=Telerik.XamarinForms.DataControls"
xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te
lerik.XamarinForms.DataControls"
 

The result:

246
Telerik UI for Xamarin

Badge Types example can be found in our SDK Browser Application.

See Also
 Key Features
 Badge Position, Alignment and Offset
 Badge Animation
 Styling
 CustomizAation

247
Telerik UI for Xamarin

Badge Styling
Use the following properties to style the look of the badge:

 BadgeText(string): Defines the badge text.


 BadgeTextColor(Xamarin.Forms.Color): Defines the badge text color.
 BadgeTextMargin(Xamarin.Forms.Thickness): Defines the mergin of the badge text.
 BadgeFontSize(double): Defines the font size of the badge text.
 BadgeFontFamily(string): Defines the badge text font family.
 BadgeFontAttributes(FontAttributes): Defines the badge text font attributes.
 BadgeBackgroundColor(Xamarin.Forms.Color): Defines the background color of the badge.
 BadgeBorderColor(Xamarin.Forms.Color): Defines the badge border color.
 BadgeBorderThickness(Xamarin.Forms.Thickness): Defines the thickness of the badge
border.
 BadgeCornerRadius(Xamarin.Forms.Thickness): Defines the corner radius of the badge
border.
 BadgeMinimumWidth(double): Defines the minimum width of tha badge.
 BadgeMinimumHeight(double): Defines the minimum height of the badge.

Use BadgeType for predefined types for the badge. If you set the BadgeText it will override the
predefined icon for the badge type.
 

Example
The BadgeView definition with some of the above properties set.

XAML
<telerikPrimitives:RadBadgeView BadgeText="{StaticResource ExpandedIconText}"
BadgeFontFamily="{StaticResource IconsFontFamily}"
BadgeTextColor="White"
BadgeBorderThickness="2"
BadgeCornerRadius="3"
BadgeMinimumHeight="25"
BadgeMinimumWidth="25"
BadgeFontSize="18"
BadgeBorderColor="#0DA6FF"
HorizontalOptions="Center"
BadgeBackgroundColor="#FF6F00"
x:Name="badgeView">
<telerikPrimitives:RadBadgeView.Content>
<Image WidthRequest="100"
HeightRequest="100">
<Image.Source >
<OnPlatform x:TypeArguments="ImageSource" Default="custom_toolbar.png">
<On Platform="UWP">Assets\custom_toolbar.png</On>
</OnPlatform>
</Image.Source>

248
Telerik UI for Xamarin

</Image>
</telerikPrimitives:RadBadgeView.Content>
</telerikPrimitives:RadBadgeView>
 

Use the following namespace:

XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
 

The final Result::

Badge Styling Example can be found inside the FeaturesCategory folder in SDK Browser
Application/Examples/BadgeViewControl.
 

See Also
 Key Features
 Badge Position and Alignment
 Badge Animation
 CustomizAation

249
Telerik UI for Xamarin

Badge Customization
You can use te following property to specify different text inside the badge

 BadgeText(string): Defines the badge text. You can set the BadgeText property for example
if you want to customize the text inside the badge. If you don't want to use one of the
predefined badges, etc.

XAML
<telerikPrimitives:RadBadgeView BadgeText="Badge Text">
<telerikPrimitives:RadBadgeView.Content>
<telerikPrimitives:RadBorder WidthRequest="80"
HeightRequest="80"
BorderThickness="1"
BorderColor="LightGray">
<Label Text="Telerik Badge View for Xamarin"
FontSize="14"
VerticalTextAlignment="Center"
HorizontalTextAlignment="Center"/>
</telerikPrimitives:RadBorder>
</telerikPrimitives:RadBadgeView.Content>
</telerikPrimitives:RadBadgeView>
 

The final result:

Badge Control Template

250
Telerik UI for Xamarin

The Badge has a default ControlTemplate which you can customize.

In order to override the default control template you will need to set implicit style with
TargetType="telerikPrimitives:Badge"
 

Default ControlTemplate

Default ControlTemplate definition

XAML
<Style TargetType="telerikPrimitives:Badge">
<Setter Property="ControlTemplate">
<Setter.Value>
<ControlTemplate>
<!-- you can change the control tempalte in order to customize the bage default
look -->
<telerikPrimitives:RadBorder BorderThickness="{TemplateBinding
BorderThickness}"
BorderColor="{TemplateBinding BorderColor}"
CornerRadius="{TemplateBinding CornerRadius}"
BackgroundColor="{TemplateBinding BackgroundColor}">
<Label x:Name="PART_BadgeContent"
Text="{TemplateBinding Text}"
TextColor="{TemplateBinding TextColor}"
Margin="{TemplateBinding TextMargin}"
FontSize="{TemplateBinding FontSize}"
FontFamily="{TemplateBinding FontFamily}"
FontAttributes="{TemplateBinding FontAttributes}"
HorizontalTextAlignment="Center"
VerticalTextAlignment="Center" />
</telerikPrimitives:RadBorder>
</ControlTemplate>
</Setter.Value>
</Setter>

251
Telerik UI for Xamarin

</Style>
 

BadgeView definition

XAML
<telerikPrimitives:RadBadgeView VerticalOptions="Start"
HorizontalOptions="Start">
<telerikPrimitives:RadBadgeView.Content>
<BoxView BackgroundColor="LightGray"
VerticalOptions="Center"
WidthRequest="80"
HeightRequest="80"
HorizontalOptions="Center"/>
</telerikPrimitives:RadBadgeView.Content>
</telerikPrimitives:RadBadgeView>
 

Add the following namespace:

XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
 

Custom ControlTemplate
BadgeView definition

XAML
<telerikPrimitives:RadBadgeView VerticalOptions="Start"
HorizontalOptions="Start">
<telerikPrimitives:RadBadgeView.Content>
<BoxView BackgroundColor="LightGray"
VerticalOptions="Center"
HorizontalOptions="Center"
WidthRequest="80"
HeightRequest="80"/>
</telerikPrimitives:RadBadgeView.Content>
</telerikPrimitives:RadBadgeView>
 

Custom ControlTemplate definition

XAML
<Style TargetType="telerikPrimitives:Badge">
<Setter Property="ControlTemplate">
<Setter.Value>
<ControlTemplate>
<!-- you can change the control tempalte in order to customize the bage default

252
Telerik UI for Xamarin

look -->
<telerikPrimitives:RadBorder HeightRequest="30"
WidthRequest="60"
BackgroundColor="#0DA6FF"
CornerRadius="15">
<StackLayout Orientation="Horizontal"
VerticalOptions="Center"
HorizontalOptions="Center">
<Label Text="{StaticResource CheckIconText}"
TextColor="White"
VerticalOptions="Center"
FontFamily="{StaticResource IconsFontFamily}"/>
<Label Text="234"
TextColor="White"/>
</StackLayout>
</telerikPrimitives:RadBorder>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
 

Add the following namespace:

XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
 

The final result:

ControlTemplate Example can be found inside the FeaturesCategory folder in SDK Browser
Application/Examples/BadgeViewControl.

253
Telerik UI for Xamarin

See Also
 Badge Position and Alignment
 Badge Animation
 Badge Types

254
Telerik UI for Xamarin

Badge Control
Badge vs BadgeView

Badge is the marker which is displayed to show notifications, statuses, etc. The BadgeView is the
control in which you can add a content and position the badge based on this content.

We recommend you use the BadgeView control


 

Badge Getting Started


XAML
<telerikPrimitives:Badge/>
 

Badge Features
Badge has the following properties:

 Text(string): Defines the badge text.


 TextColor(Xamarin.Forms.Color): Defines the text color of the badge.
 TextMargin(Xamarin.Forms.Thickness): Defines the margin of the badge text.
 FontSize(double): Defines the badge text font size.
 FontFamily(string): Defines the badge text font family.
 FontAttributes(FontAttributes): Defines the badge text font attributes.
 BorderColor(Xamarin.Forms.Color): Defines the badge border color.
 CornerRadius(Xamarin.Forms.Thickness): Defines the corner radius of the badge border.
 BorderThickness(Xamarin.Forms.Thickness): Defines the badge border thickness.
 AnimationType(Telerik.XamarinForms.Primitives.BadgeAnimationType). You can choose
between Scale and None. The default value is Scale.
 AnimationEasing(Xamarin.Forms.Easing): Defines the animation easing. For more details
about different easing options check the Xamarin.Forms.Easing article. The default value is
SinInOut.
 AnimationDuration in milliseconds(int) Defines the animation duration in milliseconds. The
default value is 300.
 ControlTemplate(Xamarin.Forms.ControlTemplate): Specifies the Badge control template.

255
Telerik UI for Xamarin

Badge ControlTemplate
Default ControlTemplate definition

XAML
<Style TargetType="telerikPrimitives:Badge">
<Setter Property="ControlTemplate">
<Setter.Value>
<ControlTemplate>
<!-- you can change the control tempalte in order to customize the bage default
look -->
<telerikPrimitives:RadBorder BorderThickness="{TemplateBinding
BorderThickness}"
BorderColor="{TemplateBinding BorderColor}"
CornerRadius="{TemplateBinding CornerRadius}"
BackgroundColor="{TemplateBinding BackgroundColor}">
<Label x:Name="PART_BadgeContent"
Text="{TemplateBinding Text}"
TextColor="{TemplateBinding TextColor}"
Margin="{TemplateBinding TextMargin}"
FontSize="{TemplateBinding FontSize}"
FontFamily="{TemplateBinding FontFamily}"
FontAttributes="{TemplateBinding FontAttributes}"
HorizontalTextAlignment="Center"
VerticalTextAlignment="Center" />
</telerikPrimitives:RadBorder>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
 

Define the Badge:

XAML
<telerikPrimitives:Badge/>
 

Add the following namespace:

XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
 

See Also
 BadgeView Overview
 BadgeView Getting Started
 Badge Position and Alignment
 Badge Animation

256
Telerik UI for Xamarin

 Badge Types
 Badge Styling
 Badge Customization

257
Telerik UI for Xamarin

Overview
Telerik RadBarcode for Xamarin is a control used for creating and showing barcodes. You can
generate and visualize barcodes in a machine-readable format via the RadBarcode control by
providing numeric or character data.

Figure 1: RadBarcode Overview

258
Telerik UI for Xamarin

Key features
 Support for different one-dimensional barcodes: including EAN13, EAN8, UPC-A, UPC-E
and Code39 symbologies. Go to 1D barcodes section for the full list.
 Support for different two-dimensional barcodes: such as the popular QR Code, SwissQR
Code and PDF417. Go to 2D barcodes for more details on this.
 Three sizing modes: RadBarcode provides three sizing modes that will help you fine-tune the
rendering of your codes. For more details read Defining the sizing mode section.

259
Telerik UI for Xamarin

 Styling capabilities: RadBarcode exposes ForegroundColor and BackgroundColor properties


that can be used to customize its visual appearance. Go to Changing the colors section for
more information.

See Also
 Getting Started

260
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadBarcode control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadBarcode control

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic. Note that RadBarcode does not have a separate nuget package.
 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadBarcode component:

Platform Assemblies
Portable Telerik.XamarinForms.Barcode.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.SkiaSharp.dll
Android Telerik.Xamarin.Android.Common.dll
Telerik.XamarinForms.Barcode.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.SkiaSharp.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Barcode.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.SkiaSharp.dll
UWP Telerik.Core.dll
Telerik.XamarinForms.Barcode.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.SkiaSharp.dll
RadBarcode is rendered via the SkiaSharp graphics library so you need to install also
SkiaSharp.Views.Forms in all projects of the Xamarin solution (.Net Standard/Shared, Android, iOS,
etc).

261
Telerik UI for Xamarin

3. Adding RadBarcode control


If your app is setup, you are ready to add a RadBarcode control to your page. In the sample the
QRCode symbology is used, for more details on the available Barcode symbologies go to Supported
Types topic.

XAML
<telerikBarcode:RadBarcode x:Name="barcode"
Value="https://www.telerik.com/xamarin-ui"
WidthRequest="100" HeightRequest="100">
<telerikBarcode:RadBarcode.Symbology>
<telerikBarcode:QRCode SizingMode="Stretch" />
</telerikBarcode:RadBarcode.Symbology>
</telerikBarcode:RadBarcode>
 

In addition to this you need to add the following namespace:

XAML
xmlns:telerikBarcode="clr-namespace:Telerik.XamarinForms.Barcode;assembly=Telerik.Xama
rinForms.Barcode"
 

Here is the result:

Figure 1: Barcode Getting Started

262
Telerik UI for Xamarin

SDK Browser and QSF applications contain different examples that show RadAutoComplete's main
features. You can find the applications in the Examples and QSF folders of your local Telerik UI for
Xamarin installation.
 

See Also
 Key Features
 Supported Barcodes

263
Telerik UI for Xamarin

Key Features
The purpose of this help article is to show you the key features of the RadBarcode control.

Setting barcode value


RadBarcode exposes a Value property that is used to set the barcode data presented by the control.
The Value of the barcode is of type string and the allowed length depends on the symbology you
choose.

Setting the symbology


Through the Symbology property you could set the symbology that will be used to convert the Value
of the control into a visual barcode representation. RadBarcode supports the most commonly used
symbologies such as:

 EAN13
 EAN8
 UPC-A
 UPC-E
 Code39
 QRCode
 PDF417

For more details on the available symbologies go to Supported Types topic.


 
Here is a quick example of RadBarcode with the Code39 symbology applied:

XAML
<telerikBarcode:RadBarcode WidthRequest="200" HeightRequest="100"
HorizontalOptions="Center" VerticalOptions="Center"
Value="58000106">
<telerikBarcode:RadBarcode.Symbology>
<telerikBarcode:Code39 HorizontalTextAlignment="Center"
SizingMode="Stretch"
ShowText="True"
CodeTextSpacing="10"/>
</telerikBarcode:RadBarcode.Symbology>
</telerikBarcode:RadBarcode>
 

You need to add the following namespace:

XAML
xmlns:telerikBarcode="clr-namespace:Telerik.XamarinForms.Barcode;assembly=Telerik.Xama
rinForms.Barcode"
 

264
Telerik UI for Xamarin

Figure 1: RadBarcode with 1D Code39 symbology

Defining the sizing mode


RadBarcode provides three sizing modes that will help you fine-tune the rendering of your codes:

 Manual – you could define the size of the smallest line or dot of the code through the Module
property and the other lines and dots multiply that size. Module property is measured in
device pixels;
 Snap – the code is stretched to the available size, but each line or dot is drawn with exact
number of pixels so they look sharp;
 Stretch – the code is stretched in such a way to fit exactly the available size, each line or dot
size is calculated so they snap to the device pixels. In order the lines to stay sharp and
stretch the barcode to the available size, some of them are slightly thicker than others.

The next example shows the same Barcode with Manual SizingMode:

XAML
<telerikBarcode:RadBarcode WidthRequest="300" HeightRequest="100"
HorizontalOptions="Center" VerticalOptions="Center"
Value="58000106">
<telerikBarcode:RadBarcode.Symbology>
<telerikBarcode:Code39 HorizontalTextAlignment="Center"
SizingMode="Manual"
Module="2"
ShowText="True"
CodeTextSpacing="10"/>
</telerikBarcode:RadBarcode.Symbology>
</telerikBarcode:RadBarcode>
 

And here is the result:

Figure 2: Barcode with Manual SizingMode

265
Telerik UI for Xamarin

Setting AutoCheckSum
By default, RadBarcode control automatically adds a checksum at the end of the barcode. You could
disable this by setting AutoCheckSum property of its Symbology to false.

If you disable the AutoCheckSum feature, you would need to manually add a checksum to ensure
the reliability of the barcode symbol.
 

Changing the colors


You could easily change the visual appearance of your Barcodes in order to match your application
theme through ForegroundColor and BackgroundColor properties.

XAML
<telerikBarcode:RadBarcode WidthRequest="200" HeightRequest="100"
HorizontalOptions="Center" VerticalOptions="Center"
ForegroundColor="DarkBlue"
BackgroundColor="Beige"
Value="58000106">
<telerikBarcode:RadBarcode.Symbology>
<telerikBarcode:Code39 SizingMode="Stretch" />
</telerikBarcode:RadBarcode.Symbology>
</telerikBarcode:RadBarcode>
 

Figure 3: Barcode with customized colors

See Also
 Supported Types

266
Telerik UI for Xamarin

Supported Types
There are two types of barcodes according to their dimensions:

Matrix (2D) barcodes


The matrix code is a two-dimensional way for representing information. It can also be referred to as
a 2D barcode or simply a 2D code. It is similar to the linear (one dimensional) barcode, but can
represent more data per unit area.

Currently, RadBarcode supports QR Code, PDF417, SwissQR Code and DataMatrix barcode types.

Linear (1D) barcodes


The linear (one dimensional) barcodes are made up of lines and spaces of various widths that create
specific patterns. Currently, RadBarcode supports the following one dimensional barcode types:

Barcode Description
Codabar (aka Ames Code/USD-4/NW-7/2 of 7 Code):
Used in libraries and blood banks
Code 11 (USD-8): Used to identify telecommunications
equipment
Code 25 Standard Used in airline ticket marking, photofinishing
Code 25 Interleaved Used in warehouse, industrial applications
Code 39 (aka USD-3, 3 of 9): U.S. Government and
military use, required for DoD applications
Code 39 Extended (aka USD-3, 3 of 9): U.S. Government and
military use, required for DoD applications,
supports full ASCII
Code 93 (aka USS-93): Compressed form of Code 39
Code 93 Extended (aka USS-93): Compressed form of Code 39,
supports full ASCII
Code 128 Very dense code, used extensively worldwide
Code 128 A Subset of Code 128 *(more info in 1D
Barcodes)
Code 128 B Subset of Code 128 *(more info in 1D
Barcodes)
Code 128 C Subset of Code 128 *(more info in 1D
Barcodes)

267
Telerik UI for Xamarin

MSI Variation of Plessey code, with similar


applications
EAN 8 Short version of EAN-13, 8 characters
EAN 13 Used with consumer products internationally,
13 characters
GS1-128 Formerly known as UCC-128 and EAN-128.
Used to encode shipping/product information
*(more info in 1D Barcodes)
Postnet Printed by U.S. Post Office on envelopes
Planet Used by the U.S. Postal Service to identify and
track pieces of mail during delivery - the Post
Office's "CONFIRM" services
UPC A Used with consumer products in U.S., 12
characters
UPC E Short version of UPC symbol, 6 characters
UPC Supplement 2 Used to indicate magazines and newspaper
issue numbers
UPC Supplement 5 Used to mark suggested retail price of books

See Also
 Key Features

268
Telerik UI for Xamarin

PDF417
PDF417 is a stacked linear barcode symbol format used in a variety of applications, primarily
transport, identification cards, and inventory management. PDF stands for Portable Data File. The
417 signifies that each pattern in the code consists of 4 bars and spaces, and that each pattern is 17
units long. The PDF417 symbology was invented by Dr. Ynjiun P. Wang at Symbol Technologies in
1991. (Wang 1993) It is represented by ISO standard 15438.

Figure 1. PDF417 RadBarcode

Visual Structure
The code is divided into rows and columns, which accommodate all the encoded data, the error
correction code words, as well as any additional format information, such as start and stop
sequences.

The PDF417 barcode has the following structure:

Figure 2. PDF417 RadBarcode's structure

The Data codewords are located in the middle section of the barcode and include the following
sections:

1. The length indicator cluster (each cluster contains 17 modules), which signifies the total
length of the data code words.
2. The actual data, which represents the data entered by the user initially, encoded.
3. The error correction cluster(s), which help the decoder in recovering any data from the code.

269
Telerik UI for Xamarin

4. Padding cluster(s) – since a rectangular matrix is allocated for the data code words, it may
become necessary to pad the data, and add one or more clusters, in order to fill any gaps in
the available matrix.

The Left Row Indicator codewords, as well as the Right Row Indicator codewords help the decoder
locate each row. Essentially the row indicators represent an encoding of the row number.

The Start and Stop patterns are present on each row in the PDF417. The signal when the data and
row indicators start and end. Each start/stop cluster is identical for each row.

Additionally, there is a minimum of two modules on each side of the PDF417 barcode, dedicated to
the quiet zone. This gives space and separates the barcode from other visual elements on the page,
allowing the reader to more reliably detect it.

Example
Check below a quick example with PDF417 symbology applied to RadBarcode:

Add the telerikBarcode namespace:

XAML
xmlns:telerikBarcode="clr-namespace:Telerik.XamarinForms.Barcode;assembly=Telerik.Xama
rinForms.Barcode"
 

Here is the result:

See Also
 Key Features
 Supported Barcodes

270
Telerik UI for Xamarin

QRCode
QR code (abbreviated from Quick Response Code) is the trademark for a type of matrix barcode first
designed for the automotive industry in Japan. The QR Code system has become popular outside
the automotive industry due to its fast readability and greater storage capacity compared to standard
UPC barcodes.

A QR code consists of black modules (square dots) arranged in a square grid on a white
background, which can be read by an imaging device (such as a camera) and processed using
Reed–Solomon error correction until the image can be appropriately interpreted. The required data
are then extracted from patterns present in both horizontal and vertical components of the image.

A QR code uses four standardized encoding modes (numeric, alphanumeric, byte/binary, and kanji)
to efficiently store data.

Visual Structure
There are a total of 40 versions available in the QR code, from 21 by 21 modules to 177 by 177
modules, increasing in steps of 4 modules per side. Naturally, higher versions are used to encode
larger amounts of data:

271
Telerik UI for Xamarin

Disregarding the data, which consists of the actual encoded data, along with the error correction bits,
the structure of the code includes the module groups listed below:

272
Telerik UI for Xamarin

 Finder Pattern - The finder pattern is a concentric square of alternating colors, located in all
corners of the symbol except the bottom right. They are used by decoders establish
orientation. The center is a 3x3 black square and it is surrounded by a one-module-thick
white box, which is surrounded by a one-module-thick black box, making the full pattern 7x7
modules.
 Alignment Pattern - The alignment pattern is only included in the rendered QR code in
version 2 and above. Its purpose is to allow the decoder to scan a skewed image, and
convert it to the virtual grid of black and white modules, representing the encoded data. The
alignment pattern is made of concentric squares, much like the finder patterns, with the
center being a single black module.
 Timing Pattern - The timing pattern is an alternating stripe of black and white modules,
starting at the lower left corner of the upper right Finder Pattern, going horizontally to the
upper left finder pattern and then going vertically to the lower left finder pattern.
 Format Data - The format data is information, pertaining to the Masking rule used in the QR
Code, along with error correction level. When the data in the QR code is encoded, some of
the modules are inverted, in accordance with a predefined rule, in order to improve
readability, and ensure that there are no big clusters of same-colored modules. This process
is called masking, and the masking information is included in the format data, to alert the
decoder that certain modules have been inverted.

The format data is encoded in 15 bits. One full copy of the format data is located around the upper
left finder pattern. A second copy, divided into 7 and 8 bits, is located next to the other two finder
patterns.

 Version Data - The version data includes information on which version the QR code is. This
data is encoded into 18 modules, in a 6 by 3 matrix. Two copies of the version data matrix
are included in the QR code - one next to the upper right finder pattern, and the other next to
the lower left one.
 Blank Space - Additionally, around each QR code, there is an obligatory 4-modules-wide
white space area:

 Data - The data occupies all available modules, not occupied by any of the formatting data

273
Telerik UI for Xamarin

segments mentioned above. If the data is smaller than the capacity of the remaining modules, it
is padded, in order to ensure that all modules are used. Additionally, the data consists of the
actual encoded data, entered by the user, and the error correction bits, calculated on that data.

Example
Check below a quick example with QRCode symbology applied to RadBarcode:

XAML
<telerikBarcode:RadBarcode x:Name="barcode"
Value="https://docs.telerik.com/devtools/xamarin/introduction">
<telerikBarcode:RadBarcode.Symbology>
<telerikBarcode:QRCode SizingMode="Stretch"
CodeMode="Byte"
ErrorCorrectionLevel="H"
ECIMode ="ISO8859_1"
FNC1Mode="SecondPosition"
ApplicationIndicator="00"/>
</telerikBarcode:RadBarcode.Symbology>
</telerikBarcode:RadBarcode>
 

Add the telerikBarcode namespace:

XAML
xmlns:telerikBarcode="clr-namespace:Telerik.XamarinForms.Barcode;assembly=Telerik.Xama
rinForms.Barcode"
 

Here is the result:

See Also
 Key Features
 Supported Barcodes

274
Telerik UI for Xamarin

SwissQRCode
The QR-bill makes issuing and paying invoices simpler, and is being introduced throughout
Switzerland to modernize payment transactions. Its most striking feature is the Swiss QR code,
which contains all the payment information in a digital format, which can be read using a smartphone
or a slip scanner.

Figure 1: A Swiss QR-bill

The Swiss QR Code encodes all the information necessary for a payment in specific format and
structure. Along with the printed information, the Swiss QR Code forms the payment part of the
QR-bill. The allowed currencies for payments are CHF and EUR. The QR-Bill also guarantees you
compliance with the regulatory requirements arising from the revised Anti-Money Laundering
Ordinance.

Requirements
The Swiss QR Code symbol requires an error correction level "M", which means a redundancy or
assurance of around 15%.

In addition, the measurements of the Swiss QR Code for printing must always be 46 x 46 mm
(without surrounding quiet space) regardless of the Swiss QR Code version. Depending on the
printer resolution, the Swiss QR Code produced might require size adjustments.

Generating a Swiss Barcode

275
Telerik UI for Xamarin

To generate a Swiss Barcode using Telerik UI for Xamarin, you need to first set the Symbology of
the Barcode to SwissQRCode.

XAML
<telerikBarcode:RadBarcode x:Name="Barcode"
WidthRequest="100"
HeightRequest="100">
<telerikBarcode:RadBarcode.Symbology>
<telerikBarcode:SwissQRCode/>
</telerikBarcode:RadBarcode.Symbology>
</telerikBarcode:RadBarcode>
 

The Swiss QR code standard mandates that the input provided for the generation of the barcode is
strictly formatted. Both validating and generating this input are complex processes and to facilitate
them you can use the SwissQRCodeValueStringBuilder helper class. Its purpose is to hold the
information needed for a SwissQRCode in a type-safe manner, to validate this information and to
generate the input. Through its constructor, you need to set the following properties:

 Iban: The IBAN of the Account/Payable to.


 Currency: The currency of the payment - CHF or EUR.
 Creditor: The information of the contact that receives the payment.
 Reference: The reference information for the payment.
 AdditionalInformation: The additional information for the payment.
 Debtor: The information of the contact that makes the payment.
 Amount: The amount of the payment.
 AlternativeProcedure: The alternative procedures for the payment.

C#
SwissQRCodeValueStringBuilder qrCodeValue = new SwissQRCodeValueStringBuilder(
new Iban("CH4431999123000889012", IbanType.QRIBAN),
SwissQRCodeCurrency.EUR,
new Contact("Max Muster & Söhne",
new StructuredAddress("CH", "8000", "Seldwyla", "Musterstrasse", "123")),
new Reference(ReferenceType.QRR, "210000000003139471430009017"),
new AdditionalInformation("Order from 15.03.2021",
"//S1/10/1234/11/201021/30/102673386/32/7.7/40/0:30"),
new Contact("Simon Muster", new StructuredAddress("CH", "8000", "Seldwyla",
"Musterstrasse", "1")),
(decimal)1949.75,
new AlternativeProcedure("Name AV1: UV;UltraPay005;12345", "Name AV2:
XY;XYService;54321"));
 

Once you've set up the SwissQRCodeValueStringBuilder you can call its Validate method which
validates all its fields and the relations between them. The method returns a string which contains
the accumulated errors. If there are no errors - null is returned. In this case, you can call the
BuildValue method of the string builder which will build the string value to be provided to the
RadBarcode.

C#

276
Telerik UI for Xamarin

string errors = qrCodeValue.Validate();

if (string.IsNullOrEmpty(errors))
{
this.Barcode.Value = qrCodeValue.BuildValue();
}
 

Invoking the code from the above snippets will generate the following result:

See Also
 Key Features
 Supported Barcodes

277
Telerik UI for Xamarin

DataMatrix
Data Matrix barcode is a two-dimensional type of code used widely in industry for marking small
parts and items due to its high data density and reliability. Data Matrix code consists of dark and light
square cells that form a matrix. The produced code can be square or rectangular and can have size
up to 144x144 for square codes or 16x48 for rectangular codes. To provide better readability, the
Data Matrix code includes error correction algorithm, allowing to reconstruct up to 30% of damaged
code image.

Figure 1: DataMatrix Barcode

DataMatrix Barcode Structure


 Finder pattern: The L-shaped lines at the bottom and left of the code are called "finder
pattern". It is used by the readers for orientation, adjustment and to correct distortion.
 Module size: the smallest cell in the code graphical representation. The module size is
recommended to be at least 2x2 printed dots for better readability.
 Timing pattern: The lines at the top and right of the code are called "timing pattern". It
provides information about the barcode size.
 Data area: The area surrounded by the finding pattern and timing pattern. Contains the
modules that encode the barcode contents.

The size of the Data Matrix code depends on module size, length and type of its contents. The
contents type determines if the encoded value contains only numerical characters or includes ASCII
or Unicode characters. The following table shows the correlation between the content type, content
length and matrix size:

COUNT OF NUMERICAL COUNT OF ASCII MATRIX SIZE

278
Telerik UI for Xamarin

CHARACTERS CHARACTERS
6 3 10x10
10 6 12x12
16 10 14x14
24 16 16x16
36 25 18x18
44 31 20x20
60 43 22x22
72 52 24x24
88 64 26x26
124 91 32x32

Encodation
The encodation determines the type of contents encoded by the Data Matrix barcode. Choosing a
proper encodation imposes validation rules, but reduces the barcode size and improves its
readability.

The following table shows the supported encodations and provides information about their
restrictions and data storing requirements:

 ASCII: Allowed characters include double digit numerics and all values from the ASCII table.
The double digit numerics use 4 bits. The ASCII values in the 0-127 range use 8 bits. The
ASCII values in 128-255 range use 16 bits.
 C40: Used primarily for upper-case alphanumerics. The upper-case alphanumeric characters
use 5.33 bits. The lower-case and special characters use 10.66 bits.
 Text: Used primarily for lower-case alphanumerics. The lower-case alphanumeric characters
use 5.33 bits. The upper-case and special characters use 10.66 bits.
 X12: Uses the characters from ANSI X12 EDI data set. Each character takes 5.33 bits.
 EDIFACT: Used to encode ASCII values in the 32-94 range. Each character takes 6 bits.
 Base256: Used to encode characters in the whole ASCII range. Each character takes 8 bits.
 AsciiGS1: Used to encode FNC1 characters in the ASCII range

Symbol Size
Sets the symbol size and shape of the generated barcode. It can be automatically determined using
SquareAuto or RectangleAuto, or specific like Square32x32 or Rectangle16x48.

Text Encoding
Determines character encoding used to encode the barcode contents. By default it is set to UTF-8,
which uses more bits per character and may increase the size of the barcode image.

279
Telerik UI for Xamarin

Example
Check below a quick example with DataMatrix symbology applied to RadBarcode.

First, add the telerikBarcode namespace:

XAML
xmlns:telerikBarcode="clr-namespace:Telerik.XamarinForms.Barcode;assembly=Telerik.Xama
rinForms.Barcode"
 

Then, add the Barcode definition:

XAML
<telerikBarcode:RadBarcode x:Name="Barcode"
Value="https://www.telerik.com/xamarin-ui">
<telerikBarcode:RadBarcode.Symbology>
<telerikBarcode:DataMatrix Encodation="Ascii"
SymbolSize="SquareAuto" />
</telerikBarcode:RadBarcode.Symbology>
</telerikBarcode:RadBarcode>
 

Here is the result:

See Also
 Key Features
 Supported Barcodes

280
Telerik UI for Xamarin

1D Barcode Specifications
One dimensional (1D) barcodes are made up of lines and spaces of various widths that create
specific patterns.

The following table describes the specific characteristics of the bar codes per type.

Barcode type Image Description Character Length Check Digit


Set
Codabar Codabar is a 0123456789- variable (no Calculated
discrete, $:/.+ fixed length) according to
self-checking Modulo 16
symbology
that may
encode 16
different
characters,pl
us an
additional 4
start/stop
characters.
Code 11 Code11 is a 0123456789- variable (no Calculated
barcode fixed length) according to
symbology Modulo 11
which is
discrete and
is able to
encode the
numbers 0
through to 9,
the dash
symbol (-),
and
start/stop
characters
Code 25 Standard 2 0123456789 variable (no Calculated
Standard of 5 is a fixed length) according to
low-density Modulo 10
numeric
symbology.
The spaces
in the
barcode exist
only to
separate the
bars
themselves.
Additionally,

281
Telerik UI for Xamarin

a bar may
either be
wide or
narrow, a
wide bar
generally
being 3 times
as wide as a
narrow bar.
The exact
size of the
spaces is not
critical, but is
generally the
same width
as a narrow
bar.
Code 25 Interleaved 2 0123456789 variable (no Calculated
Interleaved of 5 is a fixed length), according to
higher-densit but even Modulo 10
y numeric
symbology
based upon
the Standard
2 of 5
symbology.In
terleaved 2
of 5 encodes
any even
number of
numeric
characters in
the widths of
the bars and
spaces of the
bar
code.Unlike
Standard 2
of 5, which
only encodes
information
in the width
of the
bars,Interlea
ved 2 of 5
encodes
data in the
width of both
the bars and
spaces. This
allows
Interleaved 2

282
Telerik UI for Xamarin

of 5 to
achieve a
somewhat
higher
density.The
symbology is
called
"interleaved"
because the
first numeric
data is
encoded in
the first 5
bars while
the second
numeric data
is encoded in
the first 5
spaces that
separate the
first 5
bars.Thus
the first 5
bars and
spaces
actually
encode two
characters.
This is also
why the bar
code can
only encode
an even
number of
data
elements.
Code 39 Code39 is a 0123456789[ variable (no Calculated
barcode Space] fixed length) according to
symbology ABCDEFGHI Modulo 43
which JKLMNO
encodes PQRSTUVW
alphanumeri XYZ-.$/+%
c characters
into a series
of bars. It is
of variable
length and
accepts
uppercase
letters, as
well as
numbers.It

283
Telerik UI for Xamarin

includes an
optional Mod
43
checksum.
Code 39 Code39Exte 0123456789[ variable (no Calculated
Extended nded is an Space] fixed length) according to
exteded ABCDEFGHI Modulo 43
version of JKLMNO
code 39, PQRSTUVW
which XYZ!#$%&'()
includes a *+,-./:;<=>?
bigger @[]^_`
character abcdefghijkl
set. If there mnopqrstuvw
is a xyz{|}
requirement
to use the
Code39
barcode with
characters
other than
numbers and
uppercase
alphabets,
then this is
the
recommende
d barcode.
Code 93 Code93 was 0123456789[ variable (no Calculated
designed to Space]ABCD fixed length) according to
complement EFGHIJKL Modulo 47
and improve MNOPQRST
upon Code UVWXYZ-.$/
39. Code 93 +%
is similar in
that it,like
Code 39, can
represent the
full ASCII
character set
by using
combinations
of 2
characters.It
differs in that
Code 93 is a
continuous
symbology
and
produces
denser code.

284
Telerik UI for Xamarin

It also
encodes
47characters
compared to
Code 39's 43
characters.
Code 93 Code93Exte 0123456789[ variable (no Calculated
Extended nded is an Space]ABCD fixed length) according to
exteded EFGHIJKL Modulo 47
version of MNOPQRST
code 93, UVWXYZ
which -.$/+%!#&'()*,
includes a :;<=>?@[]^_`
bigger abcdefghijkl
character mnopqrstuvw
set. xyz{|}~
Code93Exte
nded can
encode full
128
character
ASCII using
the four
additional
characters:
($) (%) (/) (+)
Code 128 Code128 is a !"#$%&''()*+,- variable (no Calculated
barcode ./ fixed length) according to
symbology 0123456789: Modulo 103
which ;<=>?@
encodes ABCDEFGHI
alphanumeri JKLMNO
c characters PQRSTUVW
into a series XYZ[]^_`
of bars. It is abcdefghijkl
of variable mnopqrstuvw
length, and xyz{|}Space,
accepts Control
numbers, characters:
upper and ASCII
lower case 1-31,127
characters. It
also includes
an obligatory
MOD 103
checksum.
The
Code128 is
divided into
three
subsets A, B,

285
Telerik UI for Xamarin

and C. There
are three
separate
start codes
to indicate
which subset
will be used.
Code 128 A Code128A
supports the
standard
ASCII
symbols,
numbers,
upper case
letters, and
control
characters,s
uch as tab
and new-line.
Code 128 B Code128B
supports
standard
ASCII
symbols,
numbers,
upper and
lower case
letters.
Code 128 C Code128C
supports
numbers
only.

MSI MSI(also 0123456789 variable (no The MSI


known as 0 fixed length) barcode
Modified uses one of
Plessey) is a four possible
barcode schemes for
symbology, a calculating a
continuous, check digit:
non-self-che MSImod10(
cking most
symbology. It common),
is used MSImod1010
primarily for , MSImod11,
inventory MSImod1110
control,
marking
storage
containers

286
Telerik UI for Xamarin

and shelves
in warehouse
environment
s. The length
of this
barcode type
is variable.
EAN 8 EAN8 is a 0123456789 8 Calculated
barcode 0 according to
symbology Modulo 10
which
encodes
numbers into
a series of
bars. It is of
fixed length,
of 7 digits,
and accepts
numbers
only. It
includes a
checksum.
EAN 13 EAN13 is a 0123456789 13 Calculated
barcode 0 according to
symbology Modulo 10
which
encodes
numbers into
a series of
bars.It is of
fixed length,
of 13 digit
(12 data and
1 check),
and accepts
numbers.
First digit is
always
placed
outside the
symbol;
additionally a
right quiet
zone
indicator (>)
is used to
indicate
Quiet Zones
that are
necessary
for barcode

287
Telerik UI for Xamarin

scanners to
work
properly. It
includes a
checksum.
Postnet Postnet(Post 0123456789 variable (no The check
al Numeric 0 fixed length) digit is
Encoding calculated as
Technique) follows: First
is a barcode add all digits.
symbology The
which difference of
encodes this sum to
numbers into the next
a series of multiple of 10
bars. It is of is the check
variable digit.
length and
accepts
numbers
only. It
includes a
checksum.
The
POSTNET
barcode was
replaced by
the Intelligent
Mail barcode
in the fall of
2009.
Planet The Postal 0123456789 A PLANET Calculated
Alpha barcode according to
Numeric appears Modulo 10
Encoding either 12 or
Technique 14 digits
(PLANET) long.
barcode was
used by the
United
States Postal
Service to
identify and
track pieces
of mail
during
delivery - the
Post Office's
"CONFIRM"
services. It
was fully

288
Telerik UI for Xamarin

superseded
by Intelligent
Mail Barcode
by January
28, 2013.
Intelligent The numeric 20, 25, 29 or CRC check
Mail Intelligent 31
Mail Barcode
(IM barcode)
is a 65-bar
barcode for
use on mail
in the United
States. The
IM barcode
is intended to
provide
greater
information
and
functionality
than its
predecessor
s POSTNET
and
PLANET.
GS1-128 GS1-128 is a alphanumeri variable (no Calculated
special form c fixed length) according to
of Code 128. Modulo 103
It is used for
goods and
palettes in
commerce
and industry.
The name
GS1-128
replaces the
old name
EAN/UCC
128.
UPC A UPC A is a 0123456789 12 bzw. 8 Calculated
barcode 0 according to
symbology, Modulo 10
which
consists of
12 digits, one
of which is a
checksum.
This barcode
identifies the
manufacturer

289
Telerik UI for Xamarin

and specific
product, so
point-of-sale
cash register
systems can
automatically
look up the
price.
UPC E UPC E is a 0123456789 12 bzw. 8 Calculated
variation of 0 according to
the UPCA Modulo 10
symbol that
is used for
number
system 0. By
suppressing
zeroes,
UPCE codes
can be
printed in a
very small
space and
are used for
labeling
small items.
UPC A two digit 0123456789 2 none
Supplement UPC
2 supplementa
ry code. This
barcode
should only
be used with
magazines,
newspapers
and other
such
periodicals.
UPC A five digit 0123456789 5 none
Supplement UPC
5 supplementa
ry code. This
barcode is
used on
books to
indicate a
suggested
retail price.

1D Barcode example

290
Telerik UI for Xamarin

Here is a quick example of RadBarcode with the Code39 symbology applied:

XAML
<telerikBarcode:RadBarcode WidthRequest="200" HeightRequest="100"
HorizontalOptions="Center" VerticalOptions="Center"
Value="58000106">
<telerikBarcode:RadBarcode.Symbology>
<telerikBarcode:Code39 HorizontalTextAlignment="Center"
SizingMode="Stretch"
ShowText="True"
CodeTextSpacing="10"/>
</telerikBarcode:RadBarcode.Symbology>
</telerikBarcode:RadBarcode>
 

You need to add the following namespace:

XAML
xmlns:telerikBarcode="clr-namespace:Telerik.XamarinForms.Barcode;assembly=Telerik.Xama
rinForms.Barcode"
 

Check the result below:

See Also
 Key Features
 Supported Barcodes

291
Telerik UI for Xamarin

Overview
With the new Telerik RadBorder for Xamarin component you will have full control over the look & feel
of the border that wraps around your Xamarin views. You could surround any view such as Label,
Image, and other, and specify different border thickness and corner radius on each side.

Figure 1: RadBorder Overview

Key features
 Setting BorderThickness: RadBorder provides a BorderThickness property which you can
use together with BorderColor in order to have various types of borders around your views,
check here for more details.
 Defining different corner radius on each side: Through the CornerRadius property you could
specify separate corner radius value on all four angles of RadBorder. Go here for more
information on this.

See Also
 Getting Started

292
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadBorder control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadBorder control

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadBorder control you have to install the
Telerik.UI.for.Xamarin.Primitives nuget package. This nuget will automatically refer the
Telerik.UI.for.Xamarin.Common and Telerik.UI.for.Xamarin.SkiaSharp nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadBorder component:

Platform Assemblies
Portable Telerik.XamarinForms.Primitives.dll
Android Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Primitives.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Primitives.dll
UWP Telerik.Core.dll
Telerik.UI.Xaml.Primitives.UWP.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll

3. Adding RadBorder control

293
Telerik UI for Xamarin

You could use one of the following approaches:

Drag the control from the Toolbox.

Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML or C#.

The snippet below shows a simple RadBorder definition. In the example RadBorder wraps around a
Label:

XAML
<telerikPrimitives:RadBorder BorderColor="#4488F6" CornerRadius="5">
<Label Text="Hello there" Margin="2" />
</telerikPrimitives:RadBorder>
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
 

C#
using Telerik.XamarinForms.Primitives;
 

Here is the result:

294
Telerik UI for Xamarin

SDK Browser and Telerik Xamarin Samples applications contain different examples that show
RadBorder's main features. For detailed information on this go to Xamarin Demos Applications topic.
 

See Also
 Key Features

295
Telerik UI for Xamarin

Key Features
The purpose of this help article is to show you the key features of the RadBorder control.

Setting Border Color


You can use the BorderColor property to specify the color of RadBorder. The property has no effect
if BorderThickness is set to “0”.

Setting Border Thickness


The BorderThickness property is of type Xamarin.Forms.Thickness and is used to set the borders’
width. Type Thickness gives you the option to define different border on each side of the surrounded
element.

Here is a quick example on how to use BorderColor and BorderThickness properties:

XAML
<telerikPrimitives:RadBorder BorderColor="#4488F6" BorderThickness="1, 2, 1, 2">
<Label Text="Hello there" Margin="2" />
</telerikPrimitives:RadBorder>
 

Where:

XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
 

Defining Different Corners


The CornerRadius property represents the degree to which the corners of the Border are rounded.
CornerRadius is of type Xamarin.Forms.Thickness so it allows you to set separate values on the four
corners of the border.

XAML
<telerikPrimitives:RadBorder BorderColor="#4488F6" BorderThickness="1"
CornerRadius="15, 5, 15, 5">
<Label Text="Hello there" Margin="2" />
</telerikPrimitives:RadBorder>
 

Additionally, the wrapped content will be clipped according to each side’s specified corner radius.
The next example shows how you could have circle image by wrapping Image control with
RadBorder.

296
Telerik UI for Xamarin

XAML
<telerikPrimitives:RadBorder HorizontalOptions="Start" CornerRadius="25"
BorderThickness="2" BorderColor="Red">
<Image Source="XamarinIcon.png" WidthRequest="50" HeightRequest="50" />
</telerikPrimitives:RadBorder>
 

Here is the end result:

See Also
 Getting Started

297
Telerik UI for Xamarin

Overview
RadBusyIndicator for Xamarin allows you to display a notification whenever a longer-running
process is being handled by the application. This makes the UI more informative and the user
experience smoother.

Figure 1: RadBusyIndicator Overview

Key features
 Built-in animations: The busy indicator component provides few built-in animations which you
can use. Find more about this in the Animations help article.
 Custom busy content and animations: The control allows you to define a custom content and
animate it using RadAnimation. Find more about this in the Animations article.

See Also

298
Telerik UI for Xamarin

 Project Wizard
 Getting Started

299
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadBusyIndicator control in your
application.

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget packages following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadBusyIndicator control you have to install the
Telerik.UI.for.Xamarin.Primitives nuget package. This nuget will automatically refer the
Telerik.UI.for.Xamarin.Common and Telerik.UI.for.Xamarin.SkiaSharp nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadBusyIndicator component:

Platform Assemblies
Portable Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.SkiaSharp.dll
Android Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.SkiaSharp.dll
iOS Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.SkiaSharp.dll
UWP Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.SkiaSharp.dll
RadBusyIndicator is rendered via the SkiaSharp graphics library so you need to install also
SkiaSharp.Views.Forms in all projects of the xamarin solution (portable, android, ios, etc).
 

300
Telerik UI for Xamarin

3. Adding RadBusyIndicator control


The busy indicator is a layout control that can display two views depending on its current state - busy
and not-busy. You can define the state of the control via its IsBusy property. The default value is
False and the control's normal content is displayed. If you change it to True, the busy content is
displayed, which by default is a spinning balls animation. Check the Animations article to see the
built-in animations, how to change them and how to us a custom animation.

You could use one of the following approaches:

Drag the control from the Toolbox.

Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML or C#.

To use the busy indicator you can include the following namespaces:

C#
using Telerik.XamarinForms.Primitives;
 

Proceed with defining the component:

XAML
<telerikPrimitives:RadBusyIndicator x:Name="BusyIndicator"
AnimationContentHeightRequest="100"
AnimationContentWidthRequest="100"
IsBusy="True">
<telerikPrimitives:RadBusyIndicator.Content>
<Label Text="This is the content of the RadBusyIndicator control displayed when
the indicator is not busy." TextColor="Black" />
</telerikPrimitives:RadBusyIndicator.Content>
</telerikPrimitives:RadBusyIndicator>
 

C#
RadBusyIndicator radBusyIndicator = new RadBusyIndicator()
{
IsBusy = true,
Content = new Label() { Text = "This is the content of the RadBusyIndicator
control displayed when the indicator is not busy.", TextColor = Color.Black },
AnimationContentWidthRequest = 100,
AnimationContentHeightRequest = 100,
};
 

301
Telerik UI for Xamarin

Figure 1: RadBusyIndicator when IsBusy is True

SDK Browser and QSF applications contain different examples that show RadBusyIndicator's main
features. You can find the applications in the Examples and QSF folders of your local Telerik UI for
Xamarin installation.
 

See Also

 Animations
 Custom Busy Content

302
Telerik UI for Xamarin

Animations
Built-in Animations
RadBusyIndicator provides a set of built-in animations. You can change the selected animation
through the AnimationType property.

The AnimationType property is an enum that accepts values from Animation1 to Animation10.
Animation1 is the default.

The animation will be displayed only when the IsBusy property is set to True.
 

Changing animation size and color


You can use the following properties to change the size and color of the animated element
(animation content):

 AnimationContentWidthRequest
 AnimationContentHeightRequest
 AnimationColor

By default, the size of the animation content is 25x25 pixels.

The snippet below shows how to configure the predefined RadBusyIndicator animations:

XAML
<telerikPrimitives:RadBusyIndicator x:Name="BusyIndicator"

303
Telerik UI for Xamarin

AnimationType="Animation2"
AnimationContentColor="#2374FF"
AnimationContentHeightRequest="150"
AnimationContentWidthRequest="150"
IsBusy="True">
<telerikPrimitives:RadBusyIndicator.Content>
<Label Text="This is displayed when the indicator is not busy."
TextColor="Black" />
</telerikPrimitives:RadBusyIndicator.Content>
</telerikPrimitives:RadBusyIndicator>
 

Here is the result on different platforms:

AnimationContentWidthRequest, AnimationContentHeightRequest and AnimationColor won't be


applied if you use custom animations.
 

Custom animation
You can create a custom animation by using a combination of 3 properties - AnimationType,
BusyContent, and Animations:

 To tell the control that you use a custom animation, set the AnimationType to Custom.
 Add the content that you want to animate to BusyContent.
 The custom animation is added in the Animations collection of the busy indicator.

The following example demonstrates how to create a custom animation that changes the opacity of a

304
Telerik UI for Xamarin

text (blinking effect).

Defining custom animation in Xaml


XAML
<telerikPrimitives:RadBusyIndicator x:Name="radBusyIndicator"
AnimationType="Custom"
IsBusy="True">
<telerikPrimitives:RadBusyIndicator.Content>
<Label Text="This is the content of the RadBusyIndicator control displayed when
the indicator is not busy." />
</telerikPrimitives:RadBusyIndicator.Content>
<telerikPrimitives:RadBusyIndicator.BusyContent>
<Label HorizontalOptions="Center"
Text="Loading..."
VerticalOptions="Center" />
</telerikPrimitives:RadBusyIndicator.BusyContent>
</telerikPrimitives:RadBusyIndicator>
 

C#
RadDoubleAnimation annimation = new RadDoubleAnimation() { Duration = 800, From = 0.1,
To = 1, PropertyPath = "Opacity", Target = radBusyIndicator.BusyContent, RepeatForever
= true, AutoReverse = true };
radBusyIndicator.Animations.Add(annimation);

Device.StartTimer(TimeSpan.FromMilliseconds(5000),
() =>
{
radBusyIndicator.IsBusy = false;
return false;
});
 

Defining custom animation in code-behind


C#
RadBusyIndicator radBusyIndicator = new RadBusyIndicator()
{
IsBusy = true,
AnimationType = AnimationType.Custom,
Content = new Label() { Text = "This is the content of the RadBusyIndicator
control displayed when the indicator is not busy." },
BusyContent = new Label()
{
Text = "Loading...",
VerticalOptions = new LayoutOptions(LayoutAlignment.Center, false),
HorizontalOptions = new LayoutOptions(LayoutAlignment.Center, false),
},
};

RadDoubleAnimation annimation = new RadDoubleAnimation() { Duration = 800, From = 0.1,

305
Telerik UI for Xamarin

To = 1, PropertyPath = "Opacity", Target = radBusyIndicator.BusyContent, RepeatForever


= true, AutoReverse = true };
radBusyIndicator.Animations.Add(annimation);

Device.StartTimer(TimeSpan.FromMilliseconds(5000),
() =>
{
radBusyIndicator.IsBusy = false;
return false;
});
 

See Also
 Project Wizard
 Getting Started

306
Telerik UI for Xamarin

Custom Busy Content


Setting BusyContent property of RadBusyIndicator allows you to display any content together with
the built-in animations while the control is in Busy state. Additionally, you could customize the
BusyContentTemplate in order to arrange the custom content and the animated content per your
choice.

Here is a quick example demonstrating how BusyContent and BusyContentTemplate properties


could be applied.

XAML
<telerikPrimitives:RadBusyIndicator x:Name="BusyIndicator"
AnimationContentHeightRequest="100"
AnimationContentWidthRequest="100"
AnimationType="Animation6"
IsBusy="True">
<telerikPrimitives:RadBusyIndicator.BusyContent>
<Label Text="Working on it, just a moment, please..." />
</telerikPrimitives:RadBusyIndicator.BusyContent>
<telerikPrimitives:RadBusyIndicator.BusyContentTemplate>
<ControlTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<ContentPresenter Content="{TemplateBinding Path=AnimationContent}" />
<ContentPresenter Grid.Row="1"
Content="{TemplateBinding Path=BusyContent}"
HorizontalOptions="Center" />
</Grid>
</ControlTemplate>
</telerikPrimitives:RadBusyIndicator.BusyContentTemplate>
</telerikPrimitives:RadBusyIndicator>
 

Also you will need to add the telerikPrimitives namespace:

XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
 

You could check the result in the image below:

Figure 1: RadBusyIndicator with BusyContentTemplate

307
Telerik UI for Xamarin

Data Binding Custom Content


The BusyContent is rendered inside its own ContentView. This means that it has a different
BindingContext than the RadBusyIndicator. Therefore, if you would like to data bind the
BusyContent, you would need to use RelativeSource to connect to the same BindingContext as the
RadBusyIndicator.

Here is the previous example, but modified to support databinding:

xml
<telerikPrimitives:RadBusyIndicator x:Name="BusyIndicator"
AnimationContentHeightRequest="100"
AnimationContentWidthRequest="100"
AnimationType="Animation6"
IsBusy="True">
<telerikPrimitives:RadBusyIndicator.BusyContent>
<Grid BindingContext="{Binding BindingContext, Source={RelativeSource
AncestorType={x:Type telerikPrimitives:RadBusyIndicator}}}">
<Label Text="{Binding MyViewModelProperty}" />
</Grid>
</telerikPrimitives:RadBusyIndicator.BusyContent>
<telerikPrimitives:RadBusyIndicator.BusyContentTemplate>
<ControlTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>

308
Telerik UI for Xamarin

<ContentPresenter Content="{TemplateBinding Path=AnimationContent}" />


<ContentPresenter Grid.Row="1"
Content="{TemplateBinding Path=BusyContent}"
HorizontalOptions="Center" />
</Grid>
</ControlTemplate>
</telerikPrimitives:RadBusyIndicator.BusyContentTemplate>
</telerikPrimitives:RadBusyIndicator>
 

See Also
 Animations

309
Telerik UI for Xamarin

Integrate with ListView


RadBusyIndicator is useful in scenarios whether you'd like to display a notification to the end users
of the app while a long-running operation, such as loading data from a service, is currently in
progress.

The example below demonstrates a sample integration of RadBusyIndicator with RadListView


control. The ListView loads its data asynchronously (this is simulated for the purpose of the example)
and while the load operation is taking place, RadBusyIndicator IsBusy state is enabled.

First, create a sample Book class used for the ItemsSource of the ListView:

C#
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
}
 

Then, add a ViewModel class, which provides the following:

 Collection of Book objects that is used for binding the ListView;


 Boolean IsLoading property to control the BusyIndicator's busy state;
 LoadData command that starts the loading of the items;

C#
public class ViewModel : NotifyPropertyChangedBase
{
private bool _isLoading = false;
private ObservableCollection<Book> _source;
private bool hasStartedLoadingData;

public ViewModel()
{
this.LoadDataCommand = new Command(this.LoadDataAsync, this.CanLoadData);
}

public bool IsLoading


{
get { return this._isLoading; }
set { this.UpdateValue(ref this._isLoading, value); }
}
public ObservableCollection<Book> Source
{
get { return this._source; }
set { this.UpdateValue(ref this._source, value); }
}

310
Telerik UI for Xamarin

public Command LoadDataCommand { get; set; }

private bool CanLoadData()


{
return !this.hasStartedLoadingData;
}

public async void LoadDataAsync()


{
this.hasStartedLoadingData = true;
this.LoadDataCommand.ChangeCanExecute();
this.IsLoading = true;
this.Source = await GetItemsAsync();
this.IsLoading = false;
}

private Task<ObservableCollection<Book>> GetItemsAsync()


{
return Task.Run(async () =>
{
await Task.Delay(TimeSpan.FromSeconds(3));

return new ObservableCollection<Book>


{
new Book{ Title = "The Fault in Our Stars ", Author = "John Green"},
new Book{ Title = "Divergent", Author = "Veronica Roth"},
new Book{ Title = "Gone Girl", Author = "Gillian Flynn" },
new Book{ Title = "Clockwork Angel", Author = "Cassandra Clare"},
new Book{ Title = "The Martian", Author = "Andy Weir"},
new Book{ Title = "Ready Player One", Author = "Ernest Cline"},
new Book{ Title = "The Lost Hero", Author = "Rick Riordan"},
new Book{ Title = "All the Light We Cannot See", Author = "Anthony Doerr"},
new Book{ Title = "Cinder", Author = "Marissa Meyer"},
new Book{ Title = "Me Before You", Author = "Jojo Moyes"},
new Book{ Title = "The Night Circus", Author = "Erin Morgenstern"},
};
});
}
}
 

Add the ListView and BusyIndicator controls to the view:

XAML
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="40" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Button Text="Load Data" Command="{Binding LoadDataCommand}" />
<Grid Grid.Row="1">
<telerikDataControls:RadListView ItemsSource="{Binding Source}">
<telerikDataControls:RadListView.ItemTemplate>

311
Telerik UI for Xamarin

<DataTemplate>
<telerikListView:ListViewTextCell Text="{Binding Title}" Detail="{Binding
Author}" />
</DataTemplate>
</telerikDataControls:RadListView.ItemTemplate>
<telerikDataControls:RadListView.LayoutDefinition>
<telerikListView:ListViewLinearLayout ItemLength="80" VerticalItemSpacing="2"
/>
</telerikDataControls:RadListView.LayoutDefinition>
</telerikDataControls:RadListView>
<telerikPrimitives:RadBusyIndicator x:Name="BusyIndicator"
VerticalOptions="Center"
AnimationContentHeightRequest="100"
AnimationContentWidthRequest="100"
HeightRequest="100"
IsBusy="{Binding IsLoading}" />
</Grid>
</Grid>
 

Lastly, set the ViewModel class as BindingContext of the page:

C#
this.BindingContext = new ViewModel();
 

The image below shows the result:

312
Telerik UI for Xamarin

SDK Browser application contains a sample ListView Integration example. You can find it in the
BusyIndicator/HowTo folder.
 

See Also
 Animations

313
Telerik UI for Xamarin

Overview
Telerik Button for Xamarin is a button control that enhances the functionality of the standard Xamarin
Forms Button by providing means for customizing its look & feel. UI customization is possible
through the provided themes. Additionally, you can add borders, transparency, text alignment,
backgrounds, and images.

If you are new to the Telerik Button for Xamarin control, see the Getting Started guide for more
information on how to add the control to your application.

314
Telerik UI for Xamarin

Key features
 Content alignment options: With RadButton, you can easily control the horizontal and vertical
positioning of its content. For more details, see the Key Features: Content Alignment section
in RadButton's documentation.
 Setting border thickness: RadButton provides a BorderThickness property, which you can
use together with BorderColor. This combination allows you to apply various types of borders
around your buttons. See Key Features: Border Thickness for more information.
 Setting background image: You can customize RadButton's appearance by applying an
image as a background. See Key Features: Background Image for details.
 Creating circle button: You can create a circular button by adjusting the Width, Height and
BorderRadius of RadButton. See the How To: Create Circle Button topic for more details.
 Theming support: RadButton comes with built-in theming support that helps you achieve a
look consistent with the other controls from the Telerik UI for Xamarin suite. For more
information, see the Theme Overview article.

See Also
 Key Features
 Create Circle Button

315
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadButton control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadButton control

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadButton control you have to install the Telerik.UI.for.Xamarin.Input
nuget package. This nuget will automatically refer the Telerik.UI.for.Xamarin.Primitives,
Telerik.UI.for.Xamarin.Common, and Telerik.UI.for.Xamarin.DataControls nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadButton component:

Platform Assemblies
Portable Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.DataControls.dll
Android Telerik.Xamarin.Android.Common.dll
Telerik.Xamarin.Android.Data.dll
Telerik.Xamarin.Android.Input.dll
Telerik.Xamarin.Android.List.dll
Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.DataControls.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Common.dll

316
Telerik UI for Xamarin

Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.DataControls.dll
UWP Telerik.Core.dll
Telerik.Data.dll
Telerik.UI.Xaml.Controls.Data.UWP.dll
Telerik.UI.Xaml.Input.UWP.dll
Telerik.UI.Xaml.Primitives.UWP.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.DataControls.dll

3. Adding RadButton control


You could use one of the following approaches:

Drag the control from the Toolbox.

Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML or C#.

The snippet below shows a simple RadButton definition:

XAML
<telerikInput:RadButton x:Name="button"
Text="Click me!"
BorderThickness="2"
BorderColor="#4488F6"
Clicked="button_Clicked"/>
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

C#
using Telerik.XamarinForms.Input;
 

Then define the Click event handler:

C#

317
Telerik UI for Xamarin

private void button_Clicked(object sender, System.EventArgs e)


{
//implement your logic here.
}
 

Here is the result:

SDK Browser and Telerik Xamarin Samples applications contain different examples that show
RadButton's main features. For detailed information on this go to Xamarin Demos Applications topic.
 

See Also
 Key Features
 Circular Button
 Button with disabled text color

318
Telerik UI for Xamarin

Key Features
The purpose of this help article is to show you the key features of the RadButton control.

Content Alignment
RadButton exposes HorizontalContentAlignment and VerticalContentAlignment properties of type
Xamarin.Forms.TextAlignment which you can use to set different positioning of its content.

Here is a quick example how you can apply these:

XAML
<telerikInput:RadButton x:Name="buttonAlignment"
Text="Click me!"
BorderColor="#4488F6"
BorderThickness="1"
HorizontalContentAlignment="End"
VerticalContentAlignment="Start"
WidthRequest="200"
HeightRequest="60" />
 

Where:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

Border Thickness
The BorderThickness property is of type Xamarin.Forms.Thickness and is used to set the borders’
width. Type Thickness gives you the option to define different border on each side of the Button.

The snippet below demonstrates how BorderThickness could be defined.

XAML
<telerikInput:RadButton x:Name="buttonThickness"
Text="Click me!"
BorderThickness="6, 2, 2, 6"
BorderColor="#4488F6" />
 

Background Image
The BackgroundImage property is of type ImageSource and is used to set a graphic as a

319
Telerik UI for Xamarin

background of the RadButton control.

The next snippet shows how you can apply the background image.

XAML
<telerikInput:RadButton x:Name="buttonBackground"
Text="Click me!"
BackgroundImage="button_backgroundImage.png" />
 

In the example buttonBackground.png image is located in each of the application projects


(Resources folder in iOS, Resources/Drawable folder in Android, and application root in UWP; each
with the appropriate build action set). You can read more on loading and displaying images in
Xamarin.Forms here: Xamarin.Forms -> User Interface-> Images.
 
Here is the end result:

See Also
 Circular Button
 Button with disabled text color

320
Telerik UI for Xamarin

Create Circle Button


 

You could easily create circular buttons with RadButton by adjusting its Width, Height and
BorderRadius properties following the next instructions:

 Width should be equal to Height;


 BorderRadius should be set to half Width/Height value;

In some cases, you may need to set a BorderWidth value in order for BorderRadius to take effect.
 
Here is a quick example:

XAML
<telerikInput:RadButton WidthRequest="120"
HeightRequest="120"
Text="Circle Button"
FontSize="Micro"
TextColor="White"
BackgroundColor="DarkBlue"
BorderRadius="60" />
 

Appearance of different circular buttons:

321
Telerik UI for Xamarin

See Also
 Button Getting Started

322
Telerik UI for Xamarin

Set TextColor for Disabled RadButton


 

In order to set a different from the default text color when RadButton's IsEnabled property is set to
false, you can create custom renderers for the different platforms and set the color directly on the
native elements. This article will guide you on how to achieve the behavior on the different platforms.

1. As a first step, in order to use a custom renderer for the RadButton, you should create a custom
class that inherits from RadButton. Eventually, you can target your custom element within the
custom renderer.

Here is the custom class:

C#
public class MyRadButton : RadButton
{
}
 

And how it is declared within your page:

XAML
<myButton:MyRadButton x:Name="btn"
BackgroundColor="DarkOrange"
HorizontalOptions="FillAndExpand"
FontSize="Medium"
IsEnabled="False"
BorderRadius="15"
Text="Button is disabled!"/>
 

2. Once you have added the 'custom' control to your application, you can create the following custom
renderers for the different platforms in order to alter the TextColor when the button is disabled:

iOS Renderer
C#
[assembly: Xamarin.Forms.ExportRenderer(typeof(MyRadButton),
typeof(CustomButtonRenderer))]
namespace
SDKBrowser.iOS.Examples.ButtonControl.HowToCategory.ButtonDisabledTextColorExample
{
public class CustomButtonRenderer :
Telerik.XamarinForms.InputRenderer.iOS.ButtonRenderer
{
public CustomButtonRenderer() : base()
{

323
Telerik UI for Xamarin

protected override void


OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
{
base.OnElementChanged(e);
if (Control != null)
{
Control.SetTitleColor(UIColor.Gray, UIControlState.Disabled);
Control.SetTitleColor(UIColor.Red, UIControlState.Normal);
}
}
}
}
 

Android Renderer
C#
[assembly: Xamarin.Forms.ExportRenderer(typeof(MyRadButton),
typeof(CustomButtonRenderer))]
namespace
SDKBrowser.Droid.Examples.ButtonControl.HowToCategory.ButtonDisabledTextColorExample
{
public class CustomButtonRenderer :
Telerik.XamarinForms.InputRenderer.Android.ButtonRenderer
{
public CustomButtonRenderer(Android.Content.Context context) : base(context)
{
}

protected override void


OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
{
base.OnElementChanged(e);
this.ModifyTextColor();
}

protected override void OnElementPropertyChanged(object sender,


PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == Xamarin.Forms.Button.IsEnabledProperty.PropertyName)
{
this.ModifyTextColor();
}
}

private void ModifyTextColor()


{
if (this.Element.IsEnabled == true)
{
this.Control.SetTextColor(Android.Graphics.Color.Red);

324
Telerik UI for Xamarin

}
else
{
this.Control.SetTextColor(Android.Graphics.Color.Gray);
}
}
}
}
 

UWP Renderer
C#
[assembly: ExportRenderer(typeof(MyRadButton), typeof(CustomButtonRenderer))]
namespace
SDKBrowser.UWP.Examples.ButtonControl.HowToCategory.ButtonDisabledTextColorExample
{
public class CustomButtonRenderer :
Telerik.XamarinForms.InputRenderer.UWP.ButtonRenderer
{
public CustomButtonRenderer() : base()
{
}

protected override void


OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
this.ModifyTextColor();
}
}

protected override void OnElementPropertyChanged(object sender,


PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == Xamarin.Forms.Button.IsEnabledProperty.PropertyName)
{
ModifyTextColor();
}
}

private void ModifyTextColor()


{
if (this.Element.IsEnabled == true)
{
this.Control.Foreground = new SolidColorBrush(Windows.UI.Color.FromArgb(255,
255, 0, 0));
}
else
{

325
Telerik UI for Xamarin

this.Control.Foreground = new SolidColorBrush(Windows.UI.Color.FromArgb(255,


165, 0, 0));
}
}

}
}
 

Figure 1 shows the appearance of the disabled RadButton once the custom renderers have been
added to your application.

Figure 1: Text Color of disabled RadButton

See Also
 Button Getting Started
 Circular Button

326
Telerik UI for Xamarin

Overview
Calendar & Scheduling for Xamarin allows you to easily implement various scheduling scenarios in
your apps built with Xamarin.Forms. Whether you want to enable date selection or create a
full-blown scheduling functionality, the Xamarin Calendar would help achieve the desired scenario.

Key features
 Different view modes support: Telerik Xamarin Calendar features year, month, week,
multiday and day views. Read the View Modes topic for more information.
 Agenda View: Through the Agenda ViewMode you can quickly and easily check the
scheduled appointments grouped by date. Fore more details on how to set it up, go to
Agenda View topic.
 Date Selection: RadCalendar provides three different types of selection: Single, Multiple and
Range. The selected dates can be changed programmatically or when the user taps on a
calendar date cell. Read the Selection article for more details.
 Appointments: Using RadCalendar you can create appointments for a particular date
out-of-the-box. For more information on this check the Appointments topic.
 Recurrent Appointments: The control provides the functionality to configure repeating
appointments. The user has the ability to apply recurring scheduling patterns such as daily,
weekly, monthly or set a range of recurrence from date to date. Check Recurrence Overview
topic for more information on this.
 Scheduling UI: RadCalendar introduces built-in UI for creation and modification of
appointments, so you could provide users with the ability to directly schedule their meetings.
For more details on this check Scheduling UI topic.
 Special and restricted slots: You have the option to define a collection of special time slots in

327
Telerik UI for Xamarin

order to make them noticeable across the timeline of the Day and MultiDay views. Additionally,
time slots can be marked as read-only, meaning that end users wouldn't be able to create or
modify appointments at these slots. For detailed information on that functionality go to Special
and Restricted Slots topic.
 Flexible Styling API: Thanks to the control’s flexible API you have the freedom to style each
separate date cell as well as the appointments according to your specifications. Read more
about the Calendar styling capabilities in the Styling section.

Check out RadCalendar Getting Started help article that shows how to use it in a basic scenario.
 

See Also
 View Modes
 Selection
 Appointments
 Recurrence
 Scheduling UI

328
Telerik UI for Xamarin

Getting Started
This example will guide you through the steps needed to add a basic RadCalendar control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadCalendar control

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadCalendar control you have to install the
Telerik.UI.for.Xamarin.Input nuget package. This nuget will automatically refer the
Telerik.UI.for.Xamarin.Primitives, Telerik.UI.for.Xamarin.Common, and
Telerik.UI.for.Xamarin.DataControls nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadCalendar component:

Platform Assemblies
Portable Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll
Android Telerik.Xamarin.Android.Common.dll
Telerik.Xamarin.Android.Data.dll
Telerik.Xamarin.Android.Input.dll
Telerik.Xamarin.Android.List.dll
Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll

329
Telerik UI for Xamarin

UWP Telerik.Core.dll
Telerik.Data.dll
Telerik.UI.Xaml.Controls.Data.UWP.dll
Telerik.UI.Xaml.Input.UWP.dll
Telerik.UI.Xaml.Primitives.UWP.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll

3. Adding RadCalendar control


You could use one of the following approaches:

Drag the control from the Toolbox.

Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML or C#.

The snippet below shows a simple RadCalendar definition:

XAML
<telerikInput:RadCalendar x:Name="calendar"/>
 

C#
var calendar = new RadCalendar();
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

C#
using Telerik.XamarinForms.Input;
 

RadCalendar control requires its visual parent to provide vertical or horizontal space for the control
to fill into. Please avoid placing the control inside ScrollView as the calendar control has its own
scrolling.
 
Here is the result:

330
Telerik UI for Xamarin

SDK Browser and QSF applications contain different examples that show RadCalendar's main
features. You can find the applications in the Examples and QSF folders of your local Telerik UI for
Xamarin installation.
 

See Also
 Visual Structure
 Navigation and View Mode
 Selection

331
Telerik UI for Xamarin

Visual Structure
Here are described all visual elements and terms used in a standard RadCalendar control.

Legend
 Calendar title: The title element of the calendar.
 Day names: The names of the week days.
 Week numbers: The number of the weeks in the current year.
 Today date: The today date.
 Selected day: The selected date.
 Days from other month: Days that are not from the current month.

332
Telerik UI for Xamarin

View Modes
RadCalendar is a control that displays a calendar representation from which the user can select a
date. There are various View modes that specify what is visible in the Calendar views: a day, few
days, a month, a year.

The table below lists the supported view modes for each platform:

View Mode iOS Android UWP


Month ✔ ✔ ✔
Day ✔ ✔ ✔
MultiDay ✔ ✔ ✔
Agenda ✔ ✔ -
Year ✔ ✔ ✔
Week ✔ ✔ -
MonthNames ✔ - -
YearNumbers ✔ - ✔
Flow ✔ - -
Century - - ✔
You could check how the most used view modes look on different platforms below:

Day ViewMode

333
Telerik UI for Xamarin

Month ViewMode

Year ViewMode (available on Android and iOS only)

334
Telerik UI for Xamarin

You can refer to the MultiDay View topic for detailed information on the recently added MultiDay view
mode of RadCalendar.
 

Setting the ViewMode


ViewMode property is of type CalendarViewMode and is used to define the current view of
RadCalendar control. Starting with R1 2019 release of Telerik UI for Xamarin, you could directly
set/bind ViewMode property in order to apply a different View:

XAML
<telerikInput:RadCalendar x:Name="calendar" ViewMode="Month" />
 

Keep in mind that setting ViewMode property to a value that is not supported on the current platform
would throw a NotSupportedException.
 
You can also use any of the methods listed below for switching the Calendar ViewMode:

335
Telerik UI for Xamarin

 bool TrySetViewMode(CalendarViewMode view, bool isAnimated = true): Tries to set the


view mode of the calendar to the specified value. If the view mode is supported, the method
returns true, otherwise returns false.
 bool TryNavigateToUpperView (bool isAnimated = true): Navigates to upper view if possible.
Returns true if navigation has been successful, false otherwise.
 iOS: Month > MonthNames > YearNumbers
 Android: Month > Year
 UWP: Month > MonthNames > YearNumbers
 bool TryNavigateToLowerView (bool isAnimated = true): Navigates to lower view if possible.
Returns true if navigation has been successful, false otherwise.
 iOS: YearNumbers > MonthNames > Month
 Android: Year > Month
 UWP: YearNumbers > MonthNames > Month

All calendar navigation methods should be called after the native Calendar element has been
loaded. Here are the events that you can use:
 
Following is a quick example on how these could be used.

First, you need to attach to the NativeControlLoaded event:

XAML
<telerikInput:RadCalendar x:Name="calendar" NativeControlLoaded="CalendarLoaded" />
 

When the control is loaded, you can change the view mode.
C#
private void CalendarLoaded(object sender, EventArgs args)
{
(sender as RadCalendar).TrySetViewMode(CalendarViewMode.Day);
}
 

See Also
 Date Properties
 Day View
 MultiDay View
 Agenda View
 Events

336
Telerik UI for Xamarin

Day View
Day ViewMode allows you to display the schedule for a specific day in RadCalendar. You could also
take advantage of a few useful configuration and styling options, such as day start and end times,
timeline settings, appointments text color and font size, and more.

Day ViewMode provides a convenient way to display appointments for a certain day. For more
details on the Appointments feature of RadCalendar refer to Appointments topic.

You can also consider MultiDay ViewMode as it gives the option to select how many days to display
and provides work week support.
 

Timeline Settings
You can specify the initial and end hours displayed in the DayView through the DayViewSettings
property of RadCalendar. DayViewSettings provides the following configuration options:

 DayStartTime: Defines the time used to indicate the start of the Calendar timeline. The
default value of the DayStartTime is 00:00:00 or 12:00 AM.
 DayEndTime: Sets the time used to indicate the end of the timeline.
 TimelineInterval: This property is of type TimeSpan and defines the time intervals inside the
timeline.
 IsCurrentTimeIndicatorVisible: Boolean property that enables the option to visually mark the
current time. In addition, you could customize the way the current time indicator looks
through a few styling properties, for more details go to Styling section.

Through the DayViewSettings you can also configure Special and restricted slots and Non-working
hours features of RadCalendar.
 

Styling
This section presents the various properties you can use for customizing the visual appearance of
different parts of the Day view. All of them are applied through DayViewStyle property of
RadCalendar.

CurrentTimeIndicator

You can customize the way the current time indicator looks through the styling properties listed
below:

 CurrentTimeIndicatorColor
 CurrentTimeIndicatorWidth
 CurrentTimeIndicatorRadius: Specifies the radius of the round marker at the beginning of the
indicator on Android and iOS.

337
Telerik UI for Xamarin

AllDayArea

DayView provides all-day area at the top of the timeline to display appointments that continue a
whole day(s). Following are the styling properties related to AllDay area:

 AllDayAreaBackgroundColor: Specifies the background color of the AllDay area;


 AllDayAppointmentBackgroundColor: Specifies the background of the all-day appointments
shown inside AllDay area;
 AllDayLabelTextColor and AllDayLabelFontSize: Refer to the Text shown inside time ruler
next to the AllDay area;
 AllDayAppointmentTextColor and AllDayAppointmentFontSize: Refer to the all-day
appointments displayed inside AllDay area;

In order to create all-day appointments you just need to set IsAllDay bool property of the
Appointment class. For more details on the Appointments feature of RadCalendar refer to
Appointments topic.
 

Timeline

Through DayViewStyle you could define the background of the timeline as well as different
background to the current day, also the background and font-size of appointments inside timeline.

 TimelineBackgroundColor: Refers to the whole timeline area, except the current day;
 TimelineLabelsTextColor and TimelineLabelsFontSize: Refers to the text marking the time
intervals;
 AppointmentTextColor and AppointmentFontSize: Refer to the Titles of the appointments
inside the timeline area;
 AppointmentDetailsTextColor and AppointmentDetailsFontSize: Refer to the Detail
properties of the appointments inside the timeline area;

Example
Check the example below demonstrating how DayViewSettings and DaysViewStyle properties are
applied:

XAML
<telerikInput:RadCalendar x:Name="calendar"
ViewMode="Day">
<telerikInput:RadCalendar.DayViewSettings>
<telerikInput:DayViewSettings DayStartTime="9:00:00"
DayEndTime="18:00:00"
TimelineInterval="2:00"
IsCurrentTimeIndicatorVisible="True"/>
</telerikInput:RadCalendar.DayViewSettings>
<telerikInput:RadCalendar.DayViewStyle>
<telerikInput:DayViewStyle AllDayAppointmentBackgroundColor="Blue"
AllDayAppointmentTextColor="White"
AllDayAppointmentFontSize="12"
TimelineLabelsTextColor="DarkGray"

338
Telerik UI for Xamarin

TimelineLabelsFontSize="10"
AppointmentFontSize="12"
AppointmentDetailsFontSize="10"
CurrentTimeIndicatorColor="Red"
CurrentTimeIndicatorWidth="5"
CurrentTimeIndicatorRadius="5" />
</telerikInput:RadCalendar.DayViewStyle>
</telerikInput:RadCalendar>
 

And here is the result:

DayView Settings example can be found in the Calendar & Scheduling/Features folder of the SDK
Samples Browser application.

You can also explore the example code directly in the SDKBrowser Examples repository on GitHub.

See Also
 View Modes
 MultiDay ViewMode
 Agenda View
 Appointments
 Special and restricted slots
 Non-working hours

339
Telerik UI for Xamarin

MultiDay View
RadCalendar comes with MultiDay view mode which enables you to create a detailed view of the
schedule for a specific day (or days). In addition, you will have full control over the way the MultiDay
view is visualized through various configuration options such as day start and end times, timeline
settings, current time indicator, and more.

The main purpose of the MultiDay view is to display appointments to the end-users in a convenient
way. For more details on the Appointments feature of RadCalendar refer to Appointments topic.

Timeline Settings
This section lists the key properties of the MultiDay ViewMode so you could configure it to best suit
your needs.

 VisibleDays: Defines the number of days visualized on the view area. The default is 7 days.
 DayStartTime: Defines the time used to indicate the start of the Calendar timeline. The
default value of the DayStartTime is 00:00:00 or 12:00 AM.
 DayEndTime: Sets the time used to indicate the end of the timeline.
 IsWeekendVisible: Boolean property that will allow to exclude the weekends from the
timeline, so that only the work week is displayed.
 TimelineInterval: This property is of type TimeSpan and defines the time intervals inside the
timeline.
 IsCurrentTimeIndicatorVisible: Boolean property that enables the option to visually mark the
current time. In addition, you could customize the way the current time indicator looks
through a few styling properties, for more details go to Styling section.

All of the above are applied using the MultiDayViewSettings property of RadCalendar. Here is a
quick example on how they could be set:

XAML
<telerikInput:RadCalendar x:Name="calendar" ViewMode="MultiDay">
<telerikInput:RadCalendar.MultiDayViewSettings>
<telerikInput:MultiDayViewSettings VisibleDays="10"
DayStartTime="9:00:00"
DayEndTime="18:00:00"
TimelineInterval="2:00"
IsWeekendVisible="false"
IsCurrentTimeIndicatorVisible="true"/>
</telerikInput:RadCalendar.MultiDayViewSettings>
</telerikInput:RadCalendar>
 

The next image shows MultiDay view with the MultiDayViewSettings applied:

340
Telerik UI for Xamarin

Through the MultiDayViewSettings you can also configure Special and restricted slots and
Non-working hours features of RadCalendar.
 

Work Week Support


By setting IsWeekendVisible property through MultiDayViewSettings of RadCalendar, you can
exclude the weekends from the timeline and display only the work week. In addition, you can
configure DayStartTime and DayEndTime properties, so that only the working hours are present in
MultiDay view mode.

Styling
This section presents the various properties you can use for customizing the visual appearance of
different parts of the MultiDay view. All of them are applied through MultiDayViewStyle property of
RadCalendar.

CurrentTimeIndicator

You can customize the way the current time indicator looks through the styling properties listed
below:

 CurrentTimeIndicatorColor
 CurrentTimeIndicatorWidth
 CurrentTimeIndicatorRadius: Specifies the radius of the round marker at the beginning of the
indicator on Android and iOS.

341
Telerik UI for Xamarin

XAML
<telerikInput:RadCalendar x:Name="calendar" ViewMode="MultiDay">
<telerikInput:RadCalendar.MultiDayViewSettings>
<telerikInput:MultiDayViewSettings VisibleDays="1"
DayStartTime="9:00:00"
DayEndTime="18:00:00"
IsCurrentTimeIndicatorVisible="true"/>
</telerikInput:RadCalendar.MultiDayViewSettings>
<telerikInput:RadCalendar.MultiDayViewStyle>
<telerikInput:MultiDayViewStyle CurrentTimeIndicatorColor="Red"
CurrentTimeIndicatorWidth="5"
CurrentTimeIndicatorRadius="10" />
</telerikInput:RadCalendar.MultiDayViewStyle>
</telerikInput:RadCalendar>
 

And here is the result:

AllDayArea

MultiDayView provides all-day area at the top of the timeline to display appointments that continue a
whole day(s). Following are the styling properties related to AllDay area:

 AllDayAreaBackgroundColor: Specifies the background of AllDay area;


 AllDayAppointmentBackgroundColor: Specifies the background of the all-day appointments
shown inside AllDay area;
 AllDayLabelTextColor and AllDayLabelFontSize: Refer to the Text shown inside time ruler
next to the AllDay area;
 AllDayAppointmentTextColor and AllDayAppointmentFontSize: Refer to the all-day

342
Telerik UI for Xamarin

appointments displayed inside AllDay area;

In order to create all-day appointments you just need to set IsAllDay bool property of the
Appointment class. For more details on the Appointments feature of RadCalendar refer to
Appointments topic.
 
And here is a quick example on how AllDay-related properties could be applied:

XAML
<telerikInput:RadCalendar x:Name="calendar" ViewMode="MultiDay">
<telerikInput:RadCalendar.MultiDayViewSettings>
<telerikInput:MultiDayViewSettings VisibleDays="3"
IsWeekendVisible="true" />
</telerikInput:RadCalendar.MultiDayViewSettings>
<telerikInput:RadCalendar.MultiDayViewStyle>
<telerikInput:MultiDayViewStyle AllDayAreaBackgroundColor="Beige"
AllDayAppointmentBackgroundColor="Blue"
AllDayLabelTextColor="Black"
AllDayLabelFontSize="11"
AllDayAppointmentTextColor="White"
AllDayAppointmentFontSize="12" />
</telerikInput:RadCalendar.MultiDayViewStyle>
</telerikInput:RadCalendar>
 

Timeline Styling

Through MultiDayViewStyle you could define the background of the timeline as well as different
background to the current day, also the background and font-size of appointments inside timeline.

343
Telerik UI for Xamarin

 TodayBackgroundColor: Refers to the current day;


 TimelineBackgroundColor: Refers to the whole timeline area, except the current day;
 TimelineLabelsTextColor and TimelineLabelsFontSize: Refers to the text marking the time
intervals;
 AppointmentTextColor and AppointmentFontSize: Refer to the Titles of the appointments
inside the timeline area;
 AppointmentDetailsTextColor and AppointmentDetailsFontSize: Refer to the Detail
properties of the appointments inside the timeline area;

Check the example below demonstrating how the timeline styling properties are applied:

XAML
<telerikInput:RadCalendar x:Name="calendar" NativeControlLoaded="CalendarLoaded">
<telerikInput:RadCalendar.MultiDayViewSettings>
<telerikInput:MultiDayViewSettings VisibleDays="3"
IsWeekendVisible="true" />
</telerikInput:RadCalendar.MultiDayViewSettings>
<telerikInput:RadCalendar.MultiDayViewStyle>
<telerikInput:MultiDayViewStyle
TodayBackgroundColor="#F9F7EA"
TimelineBackgroundColor="#FFEAC6"
TimelineLabelsTextColor="DarkGray"
TimelineLabelsFontSize="10"
AppointmentTextColor="White"
AppointmentDetailsTextColor="Bisque"
AppointmentFontSize="11"
AppointmentDetailsFontSize="10" />
</telerikInput:RadCalendar.MultiDayViewStyle>
</telerikInput:RadCalendar>
 

344
Telerik UI for Xamarin

See Also
 View Modes
 Agenda View
 Appointments
 Special and restricted slots
 Non-working hours

345
Telerik UI for Xamarin

Agenda View
With R1 2020 RadCalendar comes with new Agenda view mode which shows a list of the scheduled
appointments grouped by date. With AgendaView you can enable the app users to quickly check on
everything coming up in their calendars.

In addition, you have full control over the way the Agenda view is visualized - you can set custom
date and time formats as well as modify the style (text color, font, alignment) of each text label
shown across the view separately.

AgendaView provides convenient way to display appointments chronologically. For more details on
the Appointments feature of RadCalendar refer to Appointments topic.
 
In order to enable AgendaView, just set ViewMode property of RadCalendar to "Agenda". The image
below shows Calendar AgendaView with its default look:

AgendaView is available only on Android and iOS.


 

Date and Time Format Settings

346
Telerik UI for Xamarin

You can find below a full list of the available date and time format settings for Agenda View:

 MonthItemFormat: Defines the format of the label shown at the beginning of each month.
 WeekItemStartDateFormat: Sets the format of the start date of each week;
 WeekItemEndDateFormat: Sets the format of the end date of each week;
 DayItemFormat: Specifies the format of the label shown at the beginning of each day;
 AppointmentItemTimeFormat: Defines the time format shown for the appointments;
 AppointmentItemStartDateFormat: Sets the format of the start date of the multi-day
appointments;
 AppointmentItemEndDateFormat: Specifies the format of the end date of the multi-day
appointments;
 StickyHeaderFormat: Specifies the format of the label shown in the "frozen" header at the
top of the view. For more details on this go to Sticky Headers section.

The next image shows more clearly which format property to which agenda item corresponds:

All of the above are applied using the AgendaViewSettings property of RadCalendar. Here is a quick
example on how they could be set:

XAML
<telerikInput:RadCalendar x:Name="calendar"
ViewMode="Agenda">
<telerikInput:RadCalendar.AgendaViewSettings>

347
Telerik UI for Xamarin

<telerikInput:AgendaViewSettings MonthItemFormat="YYYY MMM"


WeekItemStartDateFormat="dd MMMM"
WeekItemEndDateFormat="dd"
DayItemFormat="EEE d MMM"
AppointmentItemTimeFormat="HH mm"
AppointmentItemEndDateFormat="MMM d"
AppointmentItemStartDateFormat="MMM d"
IsHeaderSticky="True"
StickyHeaderFormat="YYYY MMM"/>
</telerikInput:RadCalendar.AgendaViewSettings>
</telerikInput:RadCalendar>
 

The next image shows Agenda view with the AgendaViewSettings applied:

Sticky Headers
Starting with R2 2020 AgendaView provides sticky month headers. This means the current month
header will "freeze" while scrolling through the items until the whole month is scrolled away. As you
scroll through the next month, the currently sticked month header will be pushed by the next month

348
Telerik UI for Xamarin

header.

Sticky headers behavior is enabled by default, you have the option to disable it by setting the
IsHeaderSticky property of the AgendaViewSettings to False.

XAML
<telerikInput:RadCalendar x:Name="calendar"
ViewMode="Agenda">
<telerikInput:RadCalendar.AgendaViewSettings>
<telerikInput:AgendaViewSettings IsHeaderSticky="False" />
</telerikInput:RadCalendar.AgendaViewSettings>
</telerikInput:RadCalendar>
 

In addition, AgendaView provides means for customizing the look & feel of the sticky header through
the StickyHeaderStyle property of the AgendaViewSettings.

StickyHeaderStyle is of type AgendaStickyHeaderStyle and exposes the following properties:

 DecorationColor, DecorationHeight - related to the decoration line which separates the sticky
header from the rest of the view;
 TextColor, Padding, FontSize, FontFamily, FontAttributes and HorizontalTextAlignment -
standard styling settings related to the header label.

Check below a quick example on how StickyHeaderStyle can be applied:

Let's have the following sample Calendar definition:

XAML
<telerikInput:RadCalendar x:Name="calendar"
ViewMode="Agenda">
<telerikInput:RadCalendar.AgendaViewSettings>
<telerikInput:AgendaViewSettings IsHeaderSticky="True"
StickyHeaderFormat="MMMM, YYYY"
StickyHeaderStyle="{StaticResource MyStickyHeaderStyle}"/>
</telerikInput:RadCalendar.AgendaViewSettings>
</telerikInput:RadCalendar>
 

Add the referenced Style in the Resources section of the page:

XAML
<telerikInput:AgendaStickyHeaderStyle x:Key="MyStickyHeaderStyle"
TextColor="#EE6D4C"
FontAttributes="Bold"
FontSize="20"
HorizontalTextAlignment="Center"
DecorationColor="#EE6D4C"
DecorationHeight="5"/>
 

349
Telerik UI for Xamarin

And here is the result on Android and iOS:

Agenda Items Styling


RadCalendar provides means for customizing the look & feel of each element of the AgendaView,
such as text labels for months, weeks and days as well as the appointments. This is implemented
through the AgendaItemStyleSelector property of the AgendaViewSettings class.

In order to modify the default styles, you would need to create a custom selector class based on the
AgendaItemStyleSelector and override the following methods that handle the styling of different
agenda view items:

 SelectMonthItemStyle: Sets the style of the labels shown at the beginning of each month;
Through the parameter of type AgendaMonthItem you can receive the exact month the style
refers to.
 SelectWeekItemStyle: Specifies the style of the labels shown for each week; Through the
parameter of type AgendaWeekItem you can get the start and end dates of the week the
style refers to.
 SelectDayItemStyle: Sets the style of the labels displayed for the days inside the agenda

350
Telerik UI for Xamarin

view; Through the parameter of type AgendaDayItem you can receive the date the style refers
to.

All of the above methods return an object of type AgendaTextItemStyle which provides
standard styling settings such as TextColor, Padding, FontSize, FontFamily, FontAttributes
and HorizontalTextAlignment.

 SelectAppointmentItemStyle: Specifies the style of the appointment agenda items; Through


the parameter of type AgendaAppointmentItem you can receive the date the appointment is
shown for (in case of multi-day appointments) as well as the Appointment instance;

SelectAppointmentItemStyle returns an object of type AgendaAppointmentItemStyle, which


in turn, provides the listed below settings:

 TitleTextColor, TitleFontSize, TitleFontFamily, TitleFontAttributes: Refer to the


appointment title label;
 DaysDurationTextColor, DaysDurationFontSize, DaysDurationFontFamily,
DaysDurationFontAttributes: Refer to the start and end dates of the multi-day
appointments;
 TimeDurationTextColor, TimeDurationFontSize, TimeDurationFontFamily,
TimeDurationFontAttributes: Refer to the start and end times of the appointments.

Below you can find a sample implementation of a custom class that derives from
AgendaItemStyleSelector and overrides its methods for selecting styles for various agenda items:

C#
public class CustomAgendaViewItemStyleSelector : AgendaItemStyleSelector
{
private DateTime now;
public CustomAgendaViewItemStyleSelector()
{
this.now = DateTime.Now;
}

public AgendaTextItemStyle CurrentMonthStyle { get; set; }


public AgendaTextItemStyle CurrentMonthWeeksStyle { get; set; }
public AgendaTextItemStyle TodayStyle { get; set; }
public AgendaAppointmentItemStyle AllDayAppointmentStyle { get; set; }

public override AgendaTextItemStyle SelectMonthItemStyle(AgendaMonthItem item)


{
if (this.now.Month == item.Date.Month && this.now.Year == item.Date.Year)
{
return this.CurrentMonthStyle;
}

return null;
}

public override AgendaTextItemStyle SelectWeekItemStyle(AgendaWeekItem item)


{
if (this.now.Month == item.StartDate.Month && this.now.Year ==

351
Telerik UI for Xamarin

item.StartDate.Year)
{
return this.CurrentMonthWeeksStyle;
}

return null;
}

public override AgendaTextItemStyle SelectDayItemStyle(AgendaDayItem item)


{
if (this.now.Date == item.Date.Date)
{
return this.TodayStyle;
}

return null;
}

public override AgendaAppointmentItemStyle


SelectAppointmentItemStyle(AgendaAppointmentItem item)
{
if (item.Appointment.IsAllDay)
{
return this.AllDayAppointmentStyle;
}

return null;
}
}
 

Next, you'd need to add the CustomAgendaViewItemStyleSelector as a resource to your page and
define the previously created AgendaTextItemStyle and AgendaAppointmentItemStyle properties:

XAML
<ResourceDictionary>
<local:CustomAgendaViewItemStyleSelector
x:Key="CustomAgendaViewItemStyleSelector">
<local:CustomAgendaViewItemStyleSelector.CurrentMonthStyle>
<telerikInput:AgendaTextItemStyle TextColor="#EE6D4C"
FontAttributes="Bold"
FontSize="20"
HorizontalTextAlignment="Start"/>
</local:CustomAgendaViewItemStyleSelector.CurrentMonthStyle>
<local:CustomAgendaViewItemStyleSelector.CurrentMonthWeeksStyle>
<telerikInput:AgendaTextItemStyle TextColor="#218CFF"
FontAttributes="Italic"
FontSize="16"
HorizontalTextAlignment="Center"/>
</local:CustomAgendaViewItemStyleSelector.CurrentMonthWeeksStyle>
<local:CustomAgendaViewItemStyleSelector.TodayStyle>
<telerikInput:AgendaTextItemStyle TextColor="#5EB1FF"
FontAttributes="Bold"

352
Telerik UI for Xamarin

FontSize="15"
HorizontalTextAlignment="Center"/>
</local:CustomAgendaViewItemStyleSelector.TodayStyle>
<local:CustomAgendaViewItemStyleSelector.AllDayAppointmentStyle>
<telerikInput:AgendaAppointmentItemStyle TitleTextColor="#4B5157"
TitleFontAttributes="Bold"
TitleFontSize="14"
DaysDurationFontAttributes="Italic"
DaysDurationFontSize="13"
DaysDurationTextColor="#4B5157"
TimeDurationFontAttributes="Bold"
TimeDurationFontSize="12"
TimeDurationTextColor="#929293"/>
</local:CustomAgendaViewItemStyleSelector.AllDayAppointmentStyle>
</local:CustomAgendaViewItemStyleSelector>
</ResourceDictionary>
 

Lastly, add RadCalendar with ViewMode set to "Agenda" and apply the
CustomAgendaViewItemStyleSelector through the AgendaViewSettings property:

XAML
<telerikInput:RadCalendar x:Name="calendar"
ViewMode="Agenda">
<telerikInput:RadCalendar.AgendaViewSettings>
<telerikInput:AgendaViewSettings AgendaItemStyleSelector="{StaticResource
CustomAgendaViewItemStyleSelector}"/>
</telerikInput:RadCalendar.AgendaViewSettings>
</telerikInput:RadCalendar>
 

Here is the result after running the example:

353
Telerik UI for Xamarin

See Also
 View Modes
 Day View
 MultiDay View
 Appointments

354
Telerik UI for Xamarin

Date Properties
This article lists the date properties you could use to configure RadCalendar control.

Setting the current Display Date


DisplayDate property allows you to set the current visible date. This is the date which will be
displayed when you show the calendar. Depending on the current ViewMode, DisplayDate defines
which day, month, week or year to be shown in RadCalendar. By default DisplayDate is
DateTime.Today.

Constraining visible Dates


You could restrict the visible/selectable dates in RadCalendar by utilizing MinDate and MaxDate
properties. By applying MinDate and MaxDate you can prevent navigating the calendar view to a
date outside of the defined date range.

If dates outside of the MinDate-MaxDate range are in the currently visible view, they will look
disabled.
 

Selecting a Date
SelectedDate property holds the currently selected date, null means that no date is selected. For
more details on the selection functionality, refer to Selection topic.

DisplayDate defines the current visible range depending on the ViewMode. This means that if you
change DisplayDate to a date outside the current view, the Calendar will be navigated accordingly.
SelectedDate, on the other hand, provides visual selection of the date to draw attention to it or is
used to raise an action when the date is tapped. Still, setting SelectedDate to a date outside of the
current view, will not navigate the view to display it.
 

Example
Here is a quick example to demonstrate how Date properties of RadCalendar would work:

XAML
<telerikInput:RadCalendar x:Name="calendar"
DisplayDate="2018/10/18"
MinDate="2018/10/15"
MaxDate="2018/12/31"
SelectedDate="2018/10/24" />
 

355
Telerik UI for Xamarin

C#
var calendar = new RadCalendar();
calendar.DisplayDate = new DateTime(2018, 10, 18);
calendar.MinDate = new DateTime(2018, 10, 15);
calendar.MaxDate = new DateTime(2018, 12, 31);
calendar.SelectedDate = new DateTime(2018, 10, 24);
 

And the result on different platforms is shown below:

See Also
 View Modes
 Calendar Selection

356
Telerik UI for Xamarin

Selection
Starting with R2 2019 RadCalendar provides three different types of selection: Single, Multiple and
Range. The selected dates can be changed programmatically or when the user taps on a calendar
cell.

Multiple and Range selection modes are supported only on Android and iOS.
 
The following members of RadCalendar control are related to the selection feature:

 SelectionMode: Enum property of type


Telerik.XamarinForms.Input.Calendar.CalendarSelectionMode which indicates what will be
the selection. It could receive the following values:
 None: Selection is disabled;
 Single: Each time a date cell is tapped it becomes selected and if another date cell has
already been selected it is unselected;
 Multiple: Each date cell that is tapped changes its selected state, this means that when a
date cell is tapped for first time it gets added to the current selection and when it is
tapped again it is removed from the selection.
 Range: Allows the users to pick a range of consecutive dates, for example to book a
hotel for this period. Here's how the control reacts to the user's gestures while in this
mode - the first date cell that is tapped gets selected and is considered start of the range.
When another cell is tapped, it is considered end of the range and all dates between the
start and the end of the range become selected.
 SelectedDate (of type DateTime?): Defines the currently selected date. When multiple
selection is enabled, this value is set to the first selected date.
 SelectedDates (of type ObservableCollection<DateTime>): Reads the collection with the
currently selected dates. When the selection is single, only one date could be selected – thus
the collection will have count = 1.
 SelectedRange (of type Telerik.XamarinForms.Input.Calendar.DateTimeRange): Used only
with Range selection to give information on the selected range through its FromDate and
ToDate DateTime properties.

The table below lists the supported selection modes for each view mode:

View \ Selection None Singe Multiple Range


Month ✔ ✔ ✔ ✔
Day ✔ ✔ - -
MultiDay ✔ - - -
Agenda - - - -
Year - - - -
Week ✔ ✔ ✔ ✔
MonthNames - - - -

357
Telerik UI for Xamarin

YearNumbers - - - -
Flow - - - -
MultiDay View mode does not provide support for Selection. DayView only supports Single
Selection.
 
For more details about the supported view modes for each platform, please check the Calendar and
Scheduling View Modes article.

The snippet belows shows how you could apply SelectionMode property to RadCalendar:

XAML
<telerikInput:RadCalendar x:Name="calendar"
ViewMode="Month"
SelectionMode="Range" />
 

The result can be seen on the picture bellow:

358
Telerik UI for Xamarin

See Also
 Date Properties
 View Modes
 Events

359
Telerik UI for Xamarin

Calendar Appointments Overview


RadCalendar can display appointments by setting its AppointmentsSource property.
AppointmentsSource accepts a collection of Telerik.XamarinForms.Input.Appointment objects. Each
Appointment defines the following members:

 StartDate (DateTime);
 EndDate (DateTime);
 Title (string): sets the subject of the appointment;
 Detail (string): adds additional information related to the appointment;
 Color (Color): : specifies the color marking the appointment when visualized in the timeline;
 IsAllDay (bool): indicates whether the appointment will take all day;
 RecurrenceRule (IRecurrenceRule): defines basic properties of the recurrence rule of the
appointment, for more details go to Recurrence topic.

The other alternative is to create custom appointment class that inherits from the
Telerik.XamarinForms.Input.Appointment class. The class includes also the RecurrenceRule
property. For more detals please check the Custom Appointments article.

Example: Creating an Appointment


Here is a quick example on how you can create Appointments collection and bind it to the
AppointmentsSource property of RadCalendar.

First, create a ViewModel class and add "Appointments" collection inside it:

C#
public class AppointmentsViewModel
{
public AppointmentsViewModel()
{
var date = DateTime.Today;
this.Appointments = new ObservableCollection<Appointment>
{
new Appointment {
Title = "Meeting with Tom",
Detail = "Sea Garden",
StartDate = date.AddHours(10),
EndDate = date.AddHours(11),
Color = Color.Tomato
},
new Appointment {
Title = "Lunch with Sara",
Detail = "Restaurant",
StartDate = date.AddHours(12).AddMinutes(30),
EndDate = date.AddHours(14),
Color = Color.DarkTurquoise
},

360
Telerik UI for Xamarin

new Appointment {
Title = "Elle Birthday",
StartDate = date,
EndDate = date.AddHours(11),
Color = Color.Orange,
IsAllDay = true
},
new Appointment {
Title = "Football Game",
StartDate = date.AddDays(2).AddHours(15),
EndDate = date.AddDays(2).AddHours(17),
Color = Color.Green
}
};
}
public ObservableCollection<Appointment> Appointments { get; set; }
}
 

Then, add the RadCalendar definition to your page:

XAML
<telerikInput:RadCalendar x:Name="calendar"
IsAddAppointmentButtonVisible="True"
AddAppointmentButtonClicked="calendar_AddAppointmentButtonClicked"
AppointmentsSource="{Binding Appointments}"
SchedulingUiEnabled="True">
<telerikInput:RadCalendar.BindingContext>
<local:AppointmentsViewModel />
</telerikInput:RadCalendar.BindingContext>
</telerikInput:RadCalendar>
 

Figure 1: Appearance of the RadCalendar control in month view mode

361
Telerik UI for Xamarin

Figure 2: Appearance of the RadCalendar control in day view mode

362
Telerik UI for Xamarin

See Also
 Custom Appointments
 Appointment Template
 Add Appointment Button
 Events
 Day View
 MultiDay View
 Agenda View
 Recurrence
 Calendar Selection

363
Telerik UI for Xamarin

Custom Appointment
A very common scenario when using RadCalendar for Xamarin is the usage of custom
appointments. When you create a Custom Appointment class you gain the ability to append
additional properties to the base Appointment class.

From R3 2020 Release you can customize the Scheduling UIs. In addition you can modify the
Scheduling UIs adding custom UI within you can change the property/data in the custom
appointment.
 

Example
We have a sample demo in our Telerik Sample Application where you can check how property from
the Custom Appointment class is added to the Scheduling UI - AddAppointmentView screen. For this
purpose you need to customze the AddAppointmentView ControlTemplate.

See Also
 Custom Scheduling UIs
 Add Appointment View
 Appointment Summery View
 Delete Appointment View
 Color Picker View
 Custom Recurrence View
 Repeat Appointment View

364
Telerik UI for Xamarin

Appointment Template for Calendar for


Xamarin
With R3 2019 Release of Telerik UI for Xamarin RadCalendar control provides the option to apply a
ContentTemplate to the Appointments for DayView and MultiDayView. You could easily set a
Template or TemplateSelector to the appointments through the AppointmentContentTemplate
property of the DayViewSettings or MultiDaySettings.

 AppointmentContentTemplate (DataTemplate): Defines the DataTemplate of the


Appointment based on the data object.

Appointment Template in DayView and MultiDayView

Appointment Template Example

365
Telerik UI for Xamarin

The following example shows how to set AppointmentContentTemplate in DayView Mode using
DataTemplateSelector.

First, create a ViewModel class with a collection of Appointment objects:

C#
public class AppointmentsTemplateViewModel
{
public AppointmentsTemplateViewModel()
{
var date = DateTime.Today;
this.Appointments = new ObservableCollection<Appointment>
{
new Appointment{ Title = "Tom Birthday", IsAllDay = true, Color =
Color.FromHex("#C1D8FF"), Detail ="Buy present!", StartDate = date, EndDate =
date.AddHours(12)},
new Appointment{ Title = "Lunch with Sara", IsAllDay = false, Color =
Color.FromHex("#EDFDE3"), Detail ="Discuss the new marketing strategy", StartDate =
date.AddDays(1).AddHours(12), EndDate = date.AddDays(1).AddHours(13).AddMinutes(30)},
new Appointment{ Title = "Security Training", IsAllDay = false, Color =
Color.FromHex("#EDFDE3"), Detail ="Details for the event come here", StartDate =
date.AddHours(15), EndDate = date.AddHours(16)},
new Appointment{ Title = "Elle Birthday", IsAllDay = true, Color =
Color.FromHex("#FFF1F9"), Detail ="Buy present!", StartDate = date.AddDays(1), EndDate
= date.AddDays(1).AddHours(12)},
new Appointment{ Title = "One to One Meeting", IsAllDay = false, Color =
Color.FromHex("#EBF2FD"), Detail ="Details for the event come here - for example
place, participants and add information", StartDate = date.AddHours(16), EndDate =
date.AddHours(17)},
new Appointment{ Title = "Marathon", IsAllDay = false, Color =
Color.FromHex("#FDE2AC"), Detail ="Enjoy running", StartDate = date.AddHours(8),
EndDate = date.AddHours(11)},
};
}
public ObservableCollection<Appointment> Appointments { get; set; }
}
 

Create a custom appointment template selector class which inherits from DataTemplateSelector and
override the OnSelectTemplate method:

C#
public class DayViewAppointmentTemplateSelector : DataTemplateSelector
{
public DataTemplate AllDay { get; set; }
public DataTemplate NotAllDay { get; set; }

protected override DataTemplate OnSelectTemplate(object item, BindableObject


container)
{
var appointmentsTemplate = item as Appointment;

if (appointmentsTemplate.IsAllDay)
{

366
Telerik UI for Xamarin

return this.AllDay;
}
return this.NotAllDay;
}
}
 

Add the created DayViewAppointmentTemplateSelector as a Resource and define both


DataTemplates:

XAML
<local:DayViewAppointmentTemplateSelector x:Key="DayViewAppointmentTemplateSelector">
<local:DayViewAppointmentTemplateSelector.AllDay>
<DataTemplate>
<Grid>
<Label Text="{Binding Title}" FontSize="16" TextColor="Black"/>
</Grid>
</DataTemplate>
</local:DayViewAppointmentTemplateSelector.AllDay>
<local:DayViewAppointmentTemplateSelector.NotAllDay>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<StackLayout>
<Label Text="{Binding Title}" FontSize="20" TextColor="Black"/>
<Label Text="{Binding Detail}" FontSize="14" TextColor="Black"/>
</StackLayout>
<Image Source="favourite.png" VerticalOptions="Center"
HorizontalOptions="Center" Grid.Column="1"/>
</Grid>
</DataTemplate>
</local:DayViewAppointmentTemplateSelector.NotAllDay>
</local:DayViewAppointmentTemplateSelector>
 

Finally, set the AppointmentContentTemplate property of the DayViewSettings:

XAML
<telerikInput:RadCalendar x:Name="calendar"
ViewMode="Day"
AppointmentsSource="{Binding Appointments}"
SchedulingUiEnabled="True">
<telerikInput:RadCalendar.BindingContext>
<local:AppointmentsTemplateViewModel/>
</telerikInput:RadCalendar.BindingContext>
<telerikInput:RadCalendar.DayViewSettings>
<telerikInput:DayViewSettings AppointmentContentTemplate="{StaticResource
DayViewAppointmentTemplateSelector}"/>
</telerikInput:RadCalendar.DayViewSettings>

367
Telerik UI for Xamarin

</telerikInput:RadCalendar>
 

Here is the result:

SDK Browser application contains a sample Appointments Template example. You can find it in the
Calendar & Scheduling /Features folder.
 

See Also
 View Modes
 Day View
 MultiDay View
 Agenda View
 Recurrence
 Calendar Selection

368
Telerik UI for Xamarin

Add Appointment Button


With R2 2020 Release of Telerik UI for Xamarin RadCalendar control provides you the option to add
appointments using the calendar's Add Appointment Button. By default the add appointment button
is not visible. In order to display it on the screen you need to use the following porperty:

 IsAddAppointmentVisible(bool): Specifies whether the add appointment button will be visible.


If you want to add appointments using the button you need to set the
IsAddAppointmentVisible to True.

XAML
<telerikInput:RadCalendar x:Name="calendar"
IsAddAppointmentButtonVisible="True"
AddAppointmentButtonClicked="calendar_AddAppointmentButtonClicked"
AppointmentsSource="{Binding Appointments}"
SchedulingUiEnabled="True">
<telerikInput:RadCalendar.BindingContext>
<local:AppointmentsViewModel />
</telerikInput:RadCalendar.BindingContext>
</telerikInput:RadCalendar>
 

 In addition the add appointment button has an event AddAppointmentButtonClicked which


occurs when the Button within the Calendar is tapped.
Telerik.XamarinForms.Input.IsAddAppointmentButtonVisible controls the visibility of the
button.

C#
private void calendar_AddAppointmentButtonClicked(object sender,
AddAppointmentButtonClickedEventArgs e)
{
// implement your logic here
}
 

The image below shows where is the button position when IsAddAppointmentVisible="True":

369
Telerik UI for Xamarin

See Also
 View Modes
 Day View
 MultiDay View
 Agenda View
 Recurrence
 Calendar Selection

370
Telerik UI for Xamarin

Appointment Event
Calendar Appointments for Xamarin exposes the following event:

AppointmentTapped(AppointmentTappedEventArgs): Occurs when you tap over a specific


appointment when in DayView or MultiDayView mode. It can be used to get all the information
regarding the appointment.

AppointmentTapped Example
First you need to set the ViewMode to Day:

C#
calendar.ViewMode = CalendarViewMode.Day;
 

Eventually, you can utilize the event:

C#
calendar.AppointmentTapped += (sender, e) =>
{
Application.Current.MainPage.DisplayAlert(e.Appointment.Title,
e.Appointment.Detail, "OK");
};
 

See Also
 View Modes
 Day View
 MultiDay View
 Agenda View
 Recurrence
 Calendar Selection

371
Telerik UI for Xamarin

Overview
RadCalendar provides the functionality to configure repeating appointments. The user has the ability
to apply recurring scheduling patterns such as daily, weekly, monthly or set a range of recurrence
from date to date. The flexible rule mechanism covers the most common recurrence scenarios.
Furthermore, you also have the option to handle the exceptions from this rule.

The purpose of this overview is to give you a straight-forward way how to create and apply a
recurrence pattern, rule and exception. If you want to dive deeper into the recurrence feature of the
RadCalendar, check out the following topics:

 Recurrence Pattern
 Recurrence Rule

RadCalendar includes support for recurring events on daily, weekly, monthly and yearly basis.
Exceptions to the recurrence rules are also permitted. To support this recurrence behavior, the
Telerik.XamarinForms.Input.Appointment class includes the RecurrenceRule property. When an
appointment is promoted into a recurring event its RecurrenceRule is set with correct
RecurrencePattern.

If the user modifies an individual appointment occurrence, an exception is created. This exception is
added to the RecurrenceRule of the master appointment along with its specific date.
 
Consider the following example:

 Create a sample appointment that starts at 11:00 AM and lasts half an hour:

C#
var date = DateTime.Today;
var appointment = new Appointment()
{
Title = "Daily appointment",
StartDate = date.AddHours(11),
EndDate = date.AddHours(11).AddMinutes(30),
Color = Color.Tomato
};
 

 Create a daily recurrence pattern, that specifies a limit of 5 occurrences for the appointment:

C#
var pattern = new RecurrencePattern()
{
Frequency = RecurrenceFrequency.Daily,
DaysOfWeekMask = RecurrenceDays.EveryDay,
MaxOccurrences = 5
};
 

372
Telerik UI for Xamarin

 Set the recurrence rule to appointment:

C#
appointment.RecurrenceRule = new RecurrenceRule(pattern);
 

 Add exception date to the recurrence rule:

C#
appointment.RecurrenceRule.Exceptions.Add(new ExceptionOccurrence() { ExceptionDate =
date.AddDays(1) });
 

 Create an exception appointment:

C#
var exceptionAppointment = new Appointment()
{
Title = appointment.Title,
StartDate = appointment.StartDate.AddDays(3).AddHours(1),
EndDate = appointment.EndDate.AddDays(3).AddHours(1),
Color = appointment.Color
};
appointment.RecurrenceRule.Exceptions.Add(new ExceptionOccurrence() {
ExceptionDate = date.AddDays(3),
Appointment = exceptionAppointment
});
 

Finally when you add the created appointment to the AppointmentsSource of RadCalendar, you'll get
the following generated appointments:

373
Telerik UI for Xamarin

See Also
 Appointments
 Recurrence Pattern

374
Telerik UI for Xamarin

Recurrence Pattern
Calendar & Scheduling component includes support for recurring events on daily, weekly, monthly
and yearly basis. Exceptions to the recurrence rules are also permitted. To support this recurrence
behavior, the Telerik.XamarinForms.Input.Appointment class includes the RecurrenceRule property.
When an appointment is promoted into a recurring event its RecurrenceRule is set with correct
RecurrencePattern.

The RecurrenceRule class is the engine for creating and evaluating recurrence rules. It has a
mandatory property Pattern of type RecurrencePattern.

The purpose of this tutorial is to show you:

 The main properties exposed by the RecurrencePattern class:


 Frequency
 DaysOfWeekMask
 Interval
 DayOfMonth
 DayOrdinal
 MonthOfYear
 MaxOccurrences
 RepeatUntil

RecurrencePattern Class
While the RecurrenceRule class is the engine for creating and evaluating recurrence rules, the
Telerik.XamarinForms.Input.RecurrencePattern class carries the main information about the
occurrence.

The next several sections describe the main properties and methods exposed by the
RecurrencePattern class.

Frequency
If you want to set the frequency of the recurrence, you need to set the RecurrencePattern's
Frequency property. Its values are predefined in the RecurrenceFrequency enumeration, which
exposes the following values:

 Daily: Use it whenever you want the appointment to occur every day.
 Weekly: Use it whenever you want the appointment to occur every week.
 Monthly: Use it whenever you want the appointment to occur every month.
 Yearly: Use it whenever you want the appointment to occur every year.

DaysOfWeekMask
When you want to set the days of the week of the recurrence, you need to set the

375
Telerik UI for Xamarin

RecurrencePattern's DaysOfWeekMask property. Its values are predefined in the RecurrenceDays


enumeration, which exposes the following values:

 Sunday
 Monday
 Tuesday
 Wednesday
 Thursday
 Friday
 WeekDays
 Saturday
 WeekendDays
 EveryDay

RecurrenceDays.WeekDays is equivalent to RecurrenceDays.Monday | RecurrenceDays.Tuesday |


RecurrenceDays.Wednesday | RecurrenceDays.Thursday | RecurrenceDays.Friday.
 
RecurrenceDays.WeekendDays is equivalent to RecurrenceDays.Saturday |
RecurrenceDays.Sunday.
 
RecurrenceDays.EveryDay is equivalent to RecurrenceDays.Monday | RecurrenceDays.Tuesday |
RecurrenceDays.Wednesday | RecurrenceDays.Thursday | RecurrenceDays.Friday |
RecurrenceDays.Saturday | RecurrenceDays.Sunday.
 
Enum members are often used in logical operation to create a combination of values. Often you
would need to set more than one value of the DaysOfWeekMask property.
 

Interval
If you want to set the number of days between each recurrence, you need to specify the
RecurrencePattern's Interval property.

The default value of the RecurrencePattern's Interval property is 1.


 
Combining the Interval property with the DaysOfWeekMask and Frequency pattern gives you even
more flexibility when creating recurring appointments.
 

DayOfMonth
When you want to specify on which day of the month the appointment occurs, you need to set the
DayOfMonth property.

DayOrdinal
When you want to specify the day ordinal (first, second, third, fourth, etc.), you need to set the
DayOrdinal property. For example, you may want to create an appointment that occurs on every

376
Telerik UI for Xamarin

second Monday of every third month.

MonthOfYear
When you want to specify on which month of the year the appointment occurs, you need to set the
MonthOfYear property. This property is used mainly in the Yearly appointments.

MaxOccurrences
When you want to specify a limit of the occurrences for the appointment, then you need to set the
MaxOccurrences property.

RepeatUntil
When you want to specify the end date of the appointment's occurrences, then you need to set the
RepatUntil property.

See Also
 Appointments
 Recurrence Overview

377
Telerik UI for Xamarin

Recurrence Rule
RadCalendar includes support for recurring events on daily, weekly, monthly and yearly basis.
Exceptions to the recurrence rules are also permitted. To support this recurrence behavior, the
Telerik.XamarinForms.Input.Appointment class includes the RecurrenceRule property. When an
appointment is promoted into a recurring event its RecurrenceRule is set with correct
RecurrencePattern.

The purpose of this tutorial is to show you:

 The main properties exposed by the RecurrenceRule class:


 RecurrencePattern
 Exceptions
 How to create a recurrence rule and associate it with an appointment
 How to add exception occurrences to the recurrence rule

RecurrenceRule Class
While the RecurrencePattern class carries the main information about the occurrences, the
RecurrenceRule class is the engine for creating and evaluating recurrence rules.

The next several sections describe which are the main properties and methods exposed by the
RecurrenceRule class.

RecurrencePattern
The RecurrenceRule class exposes a RecurrencePattern property, which allows you to get\set the
recurrence pattern associated with the current rule. For more information about creating various
recurrence patterns, take a look at the RecurrencePattern topic.

Exceptions
The RecurrenceRule class exposes an Exceptions property, which allows you to get or set all
exception occurrences associated with the current rule. For more information read How to Add
Exception Occurrences to the Recurrence Rule

How to Create a Recurrence Rule and Associate it With


an Appointment
C#
var startDate = new DateTime(2019, 01, 09, 8, 0, 0);

var fitnessAppointment = new Appointment()


{
Title = "Fitness",

378
Telerik UI for Xamarin

StartDate = startDate,
EndDate = startDate.AddHours(2),
Color = Color.Blue
};
var recurrencePattern = new RecurrencePattern()
{
Frequency = RecurrenceFrequency.Weekly,
MaxOccurrences = 30,
DaysOfWeekMask = RecurrenceDays.Monday | RecurrenceDays.Wednesday |
RecurrenceDays.Friday
};
fitnessAppointment.RecurrenceRule = new RecurrenceRule(recurrencePattern);
calendar.AppointmentsSource = new List<Appointment> { fitnessAppointment };
 

The above example shows you how to create a recurrence pattern, then how to associate it with a
recurrence rule. Finally the recurrence rule is assigned to an appointment.

How to Add Exception Occurrences to the Recurrence


Rule
RadCalendar's API permits you to add exception occurrences to the recurrence rule. You could add
exceptions directly to the RecurrenceRule's Exceptions collection.

Exceptions collection contains a list of ExceptionOccurrence objects where each


ExceptionOccurrence includes:

 ExceptionDate: DateTime which indicates when the exception occurs. You can set only
ExceptionDate to remove the given occurrence from the recurrence.
 Appointment: Refers to the exception appointment.

One possible scenario of adding an exception to a recurrence rule is shown in the next example:

C#
var startDate = new DateTime(2019, 01, 09, 8, 0, 0);
var recurrencePattern = new RecurrencePattern()
{
Frequency = RecurrenceFrequency.Weekly,
MaxOccurrences = 30,
DaysOfWeekMask = RecurrenceDays.Monday | RecurrenceDays.Wednesday |
RecurrenceDays.Friday
};
var recurrenceRule = new RecurrenceRule(recurrencePattern);
recurrenceRule.Exceptions.Add(new ExceptionOccurrence() { ExceptionDate =
startDate.AddDays(2) });
var fitnessAppointment = new Appointment()
{
Title = "Fitness",
StartDate = startDate,
EndDate = startDate.AddHours(2),
Color = Color.Blue,

379
Telerik UI for Xamarin

RecurrenceRule = recurrenceRule
};
calendar.AppointmentsSource = new List<Appointment> { fitnessAppointment };
 

See Also
 Appointments
 Recurrence Overview
 Recurrence Pattern

380
Telerik UI for Xamarin

RecurrencePatternHelper
When working with saving recurrence patterns, the RadCalendar's API provides he
RecurrencePatternHelper class, which comes from the Telerik.XamarinForms.Input namespace. The
helper provides two main functions - turning a recurrence pattern into a nicely serialized string for
storage and producing a recurrence pattern when you provide that string back to it.

The purpose of this tutorial is to show you how to:

 Serialize a recurrence pattern to string.


 Deserialize a recurrence pattern from string.

Serialize a RecurrencePattern to String


When you want to turn (serialize) a recurrence pattern into a string, then you need to use the
RecurrencePatternHelper's RecurrencePatternToString() static method. The method accepts one
argument - the pattern that must be serialized and returns the result string.

For example, consider the following RecurrencePattern declaration:

C#
var pattern = new RecurrencePattern()
{
Frequency = RecurrenceFrequency.Daily,
DaysOfWeekMask = RecurrenceDays.WeekDays,
Interval = 3,
MaxOccurrences = 10
};
 

A new daily recurrence pattern is created that occurs only in the week days. The interval between
each occurrence is three days. The pattern has a limit of ten occurrences.The next code snippet
demonstrates you how to use the __RecurrencePatternToString()__ static method.
C#
var serializedPattern = RecurrencePatternHelper.RecurrencePatternToString(pattern);
 

After executing the above example the result string will be:
FREQ=DAILY;COUNT=10;INTERVAL=3;BYDAY=MO,TU,WE,TH,FR.

Deserialize a RecurrencePattern from String


When you want to produce (deserialize) a recurrence pattern from a string, then you need to use the
RecurrencePatternHelper's TryParseRecurrencePattern static method. The method accepts two
arguments:

 The source string - the string which the recurrence pattern will be parsed from.

381
Telerik UI for Xamarin

 The second parameter is an out parameter. This is the parsed pattern.

Consider the serialized string from the previous example:


FREQ=DAILY;COUNT=10;INTERVAL=3;BYDAY=MO,TU,WE,TH,FR. If you want to produce a
recurrence pattern from that string, invoke the TryParseRecurrencePattern method like in the
example below.

C#
var serializedPattern = "FREQ=DAILY;COUNT=10;INTERVAL=3;BYDAY=MO,TU,WE,TH,FR";
RecurrencePattern pattern;
RecurrencePatternHelper.TryParseRecurrencePattern(serializedPattern, out pattern);
 

The result will be a new daily recurrence pattern that occurs only in the week days. The interval
between each occurrence is three days. The pattern has a limit of ten occurrences.

See Also
 Appointments
 Recurrence Overview

382
Telerik UI for Xamarin

Scheduling UI
Telerik Xamarin RadCalendar control exposes built-in UI for creation and modification of
appointments, so you can provide users with the ability to directly schedule their meetings.

This article gives an overview of the available scheduling views in Calendar & Scheduling control
used for managing appointments.

Overview
In order to allow users to create and modify appointments by tapping on a time slot or an existing
appointment, you would need to set SchedulingUiEnabled Boolean property of RadCalendar to True
(by default it is False).

XAML
<telerikInput:RadCalendar x:Name="calendar"
SchedulingUiEnabled="True"
ViewMode="MultiDay">
<telerikInput:RadCalendar.MultiDayViewSettings>
<telerikInput:MultiDayViewSettings DayStartTime="8:00:00" />
</telerikInput:RadCalendar.MultiDayViewSettings>
</telerikInput:RadCalendar>
 

Please note the scheduling UIs can be shown in MonthView, DayView, MultiDayView and WeekView
modes. You can refer to View Modes topic for more information on the available in RadCalendar view
modes. For MonthView and WeekView Modes the scheduling UIs can be shown using the
AddAppointmentButton. You will need to set the IsAddAppointmentButtonVisible to True".
 
If you have a collection of custom appointments as a source for RadCalendar, the custom
appointment class should inherit from the Telerik.XamarinForms.Input.Appointment class. You
should also make sure to add a default constructor for the custom appointment. These requirements
are needed in order to properly create appointments through Scheduling UI.
 

 Appointment Summary View: When the end user taps on an appointment or use the
AddAppointmentButton, the following screen appears, giving the option to edit or delete the
appointment:

383
Telerik UI for Xamarin

 Add Appointment View: Next, you could see the edit appointment screen which is displayed
with pre-selected values when "Edit" from the previous screen is tapped, or with empty fields
(except "Starts" and "Ends") when the user has tapped on an empty time slot in order to
create a new appointment:

384
Telerik UI for Xamarin

 Color Picker View: Note the "Color" field inside Add Appointment View used to apply a color
to the appointment. Users can choose between any of the predefined colors:

385
Telerik UI for Xamarin

 Repeat Appointment View: Note the "Repeats" field which is used to set a recurrence rule to
the appointment. You could choose between any of the predefined recurrences or create a
custom recurrence:

386
Telerik UI for Xamarin

 Custom Recurrence View: If you choose to create a custom recurrence rule, the next screen
is shown:

387
Telerik UI for Xamarin

 End Repeat Appointment View: When a recurrence rule is defined, users will have the option
to choose when the recurrent appointments end:

388
Telerik UI for Xamarin

 Save Recurring Appointment View: If you're modifying a recurrent appointment, you'll be


prompted whether the changes should be applied to the whole series or only to the current
occurrence, thus making an exception of the recurrence rule:

389
Telerik UI for Xamarin

 Delete Appointment View: In order to delete an appointment, you would need to choose
"Delete Event" option from the first screen shown after tapping an appointment. You would
need to confirm the deletion as shown in the image below:

390
Telerik UI for Xamarin

 Delete Recurring Appointment View: If you choose to delete a recurrent appointment, you'll
prompted whether the deletion operation should be applied only to the current occurrence or
to the whole series:

391
Telerik UI for Xamarin

Prevent Scheduling UIs for concrete appointments


In addition, you can prevent the appearance of the scheduling screens for individual appointments or
time slots by handling AppointmentTapped/TimeSlotTapped events respectively and setting
e.Handled to True inside the event handler.

Check below a quick example on how you could prevent creating an appointment before certain
time.

First, subscribe to the TimeSlotTapped event:

C#
calendar.TimeSlotTapped += CalendarTimeSlotTapped;
 

Then, add the following event handler:

C#
private void CalendarTimeSlotTapped(object sender, TimeSlotTapEventArgs e)

392
Telerik UI for Xamarin

{
if (e.StartTime.Hour >= 18)
{
e.Handled = true;
Application.Current.MainPage.DisplayAlert("Cannot add appointment", "Adding
appointments after 6 PM is not allowed.", "OK");
}
}
 

API for showing Add/Edit Appointment Screens


Since R2 2020 RadCalendar provides API for manually showing the default Add/Edit Appointment
views used for creating and modifying appointments.

Below you will find a list of the exposed methods and commands related to the Scheduling UIs.

Methods

 ShowAddAppointmentView()
 ShowAddAppointmentView(DateTime appointmentStartTime, DateTime
appointmentEndTime)

Both methods can be used to display the "New Appointment" Scheduling UI with which users
can add appointments to the Calendar AppointmentSource. The second method gives you
the option to define the StartTime and EndTime applied in the corresponding fields when the
New Appointment view is displayed.

 ShowEditAppointmentView(Appointment appointment) - displays the "Edit Appointment"


Scheduling UI with which users can edit or delete the appointment set as a method
parameter.

Commands
If you prefer the MVVM pattern, you can take advantage of the exposed commands which provide
the same functionality as the methods:

 ShowAddAppointmentViewCommand: Displays the "New Appointment" view for adding


appointments to the Calendar AppointmentSource.

When using the ShowAddAppointmentViewCommand, you would need to pass an object of


type ShowAddAppointmentViewCommandContext as a command parameter. Through the
ShowAddAppointmentViewCommandContext you can define the StartDate and EndDate of
the new appointment.

 ShowEditAppointmentViewCommand: Displays the "Edit Appointment" view for modifying an


existing appointment.

When using the ShowEditAppointmentViewCommand, you would need to pass an object of


type ShowEditAppointmentViewCommandContext as a command parameter. Through the

393
Telerik UI for Xamarin

ShowEditAppointmentViewCommandContext you can define the Appointment that will be


edited.

Example

Let's have the following Calendar instance with both ShowAddAppointmentViewCommand and
ShowEditAppointmentViewCommand added to Calendar's Commands collection:

XAML
<telerikInput:RadCalendar x:Name="calendar"
SchedulingUiEnabled="True"
AppointmentsSource="{Binding Appointments}"
ViewMode="Day">
<telerikInput:RadCalendar.Commands>
<calendarCommands:ShowAddAppointmentViewCommand />
<calendarCommands:ShowEditAppointmentViewCommand />
</telerikInput:RadCalendar.Commands>
</telerikInput:RadCalendar>
 

Add the following namespaces:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
xmlns:calendarCommands="clr-namespace:Telerik.XamarinForms.Input.Calendar.Commands;ass
embly=Telerik.XamarinForms.Input"
 

For the purpose of the example, the commands will be called from two buttons:

XAML
<StackLayout Grid.Row="1" Orientation="Horizontal">
<Button Command="{Binding Source={x:Reference calendar}, Path=Commands[0]}"
CommandParameter="{Binding AddNewAppointmentContext}"
Text="Create Appointment"/>
<Button Command="{Binding Source={x:Reference calendar}, Path=Commands[1]}"
CommandParameter="{Binding EditAppointmentContext}"
Text="Edit First Appointment"/>
</StackLayout>
 

Let's take a look at the ViewModel class where both AddNewAppointmentContext and
EditAppointmentContext objects are defined:

C#
public class ViewModel
{
public ViewModel()
{
var date = DateTime.Today;

394
Telerik UI for Xamarin

this.Appointments = new ObservableCollection<Appointment> {


new Appointment {
Title = "Meeting with Tom",
Detail = "Sea Garden",
StartDate = date.AddHours(10),
EndDate = date.AddHours(11),
Color = Color.Tomato
},
new Appointment {
Title = "Lunch with Sara",
Detail = "Restaurant",
StartDate = date.AddHours(12).AddMinutes(30),
EndDate = date.AddHours(14),
Color = Color.DarkTurquoise
}
};

this.AddNewAppointmentContext = new ShowAddAppointmentViewCommandContext();


this.AddNewAppointmentContext.StartDate = DateTime.Now;
this.AddNewAppointmentContext.EndDate = DateTime.Now.AddHours(1);

this.EditAppointmentContext = new ShowEditAppointmentViewCommandContext();


this.EditAppointmentContext.Appointment = this.Appointments.FirstOrDefault();
}

public ObservableCollection<Appointment> Appointments { get; set; }

public ShowAddAppointmentViewCommandContext AddNewAppointmentContext { get; set; }

public ShowEditAppointmentViewCommandContext EditAppointmentContext { get; set; }


}
 

AddNewAppointmentContext sets a new 1-hour appointment from now on, while


EditAppointmentContext specifies the first appointment from the AppointmentsSource for editing.

See Also
 Appointments
 View Modes
 Calendar Selection

395
Telerik UI for Xamarin

Customizing Scheduling UIs


With R3 2020 Release the views used within the built-in Scheduling UI control can be customized.
You can edit the control templates of the different views and apply customizations.

The following Scheduling UI Views can be customized


 AddAppointmentView – view that allows the user to change the main appointment properties
like Title, Start and End Date, Detail, Recurrence, whether it will be All Day
appointment. For more details check our help article.
 AppointmentSummaryView – view that shows brief information about the appointment.
Check our Appointment Summary article.
 ColorPickerView – view for picking color which is applied to the appointment. For more
details check our help article.
 DeleteAppointmentView – view for choosing appointment deleting options. For more details
check our help article.
 SaveRecurringAppointmentView – view for choosing recurring appointment saving options.
Go to our help article.
 DeleteRecurringAppointmentView – view for choosing recurring appointments deleting
options. Please check our help article for more information.
 RepeatAppointmentView – view for choosing predefined repeat options like EveryDay,
Every Month, Every Year, etc. For more details check our help article.
 EndRepeatAppointmentView – view for choosing when recurring appointments end. Refer to
the End Repeat AppointmentView article.
 CustomRecurrenceView – view for choosing custom recurring intervals of an appointment.
Check the Custom Recurrence View help topic.

Scheduling screens can be shown in MonthView, DayView, MultiDayView and WeekView modes.
You could refer to the View Modes topic for more information on the available in RadCalendar views.
For MonthView and WeekView Modes the scheduling screens can be shown using the
AddAppointmentButton. You will need to set the IsAddAppointmentButtonVisible True.
 

Customization Properties
In addition, to avoid editing the whole control template, there are additional properties which you can
use to customize the look of the UIs, such as SeparatorThickness, ButtonBackgroundColor, etc.

These properties are different for different views. For more details which properties can be set for the
concrete view refer to the articles of the separate views inside the Scheduling UI Views section.

These properties or the ControlTemplates can be changed by applying styles that target a specific
view in the “App.xaml” file of your application.

Example
396
Telerik UI for Xamarin

A sample demo code with custom Scheduling UI can be found in our Telerik Sample Application.

See Also
 Appointments
 Custom Appointments
 Custom Scheduling UIs
 Add Appointment View
 Appointment Summery View
 Delete Appointment View
 Color Picker View
 Custom Recurrence View
 Repeat Appointment View
 End Repeat Appointment View

397
Telerik UI for Xamarin

Add Appointment View


Add Appointment View allows the user to change the main appointment properties like Title,
Start and End Date, Detail, Recurrence, whether it will be All Day appointment.

Visual Structure of Add Appointment View

Control Template
The control template for the AddAppointmentView can be found at the following location in our
SDKBrowser Application.
 

Customization Properties

398
Telerik UI for Xamarin

In addition, to avoid editing the whole control template, there are additional properties which you can
use to customize the look of the AddAppointmnetView:

 ControlTemplate(controlTemplate): Defines the Control Template of the AddAppintmentView.


 AllDaySwitchBackgroundColor(Xamarin.Forms.Color): Defines the background color of the
AllDay switch.
 AllDaySwitchOnColor(Xamarin.Forms.Color): Defines the switch on color.
 TitleFontSize(double): Defines the font size of the appointment title.
 TitleTextColor(Xamarin.Forms.Color): Defines the text color of the appointment title.
 SeparatorColor(Xamarin.Forms.Color): Defines the color of the separator (the lines which
devide each appointment property).
 SeparatorThickness(Xamarin.Forms.Thickness): Defines the thickness of the separators (the
lines which devide each appointment property).
 ButtonBackgroundColor(Xamarin.Forms.Color): Defines the background color for the OK and
Cancel buttons.
 ButtonTextColor(Xamarin.Forms.Color): Defines the text color of the OK and Cancel buttons.
 EditorTextColor(Xamarin.Forms.Color): Defines the text color of the editors.
 EditorFontSize(double): Defines the font size of the editor: Title Editor, Detail Editor, etc.
 BackgroundColor(Xamarin.Forms.Color): Defines the background color of the
AddAppointmentView.

These properties or the ControlTemplate can be changed by applying style with


TargetType="telerikInput:AddAppointmentView" in the resources of the “App.xaml” file of your

399
Telerik UI for Xamarin

application.
 

Example
XAML
<ControlTemplate x:Key="AddAppointmentViewControlTemplate">
<Grid RowSpacing="0"
BackgroundColor="Transparent"
BindingContext="{TemplateBinding BindingContext}">
<telerikPrimitives:RadPopup.Popup>
<telerikPrimitives:RadPopup IsOpen="{Binding IsPopupOpen}"
Content="{Binding PopupContent}"
VerticalOffset="{Binding PopupVerticalOffset}"
Placement="Center"
AnimationType="Fade"
OutsideBackgroundColor="#6F000000">
</telerikPrimitives:RadPopup>
</telerikPrimitives:RadPopup.Popup>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ScrollView >
<StackLayout Padding="16, 20, 16, 0"
Spacing="0">

<!--Screen Title-->
<Label Text="{telerikCommon:Localize Calendar_AppointmentEventTitle}"
FontAttributes="Bold"
HorizontalOptions="Start" />

<!--Appointment Title-->
<telerikPrimitives:RadBorder BorderColor="Red"
Margin="{OnPlatform iOS='0, 23, 0, 20', Default='0, 23, 0, 14'}"
BorderThickness="{OnPlatform iOS=1, Default=0}"
CornerRadius="{OnPlatform iOS=10}">

<Entry Text="{Binding Appointment.Title, Mode=TwoWay}"


Placeholder="{telerikCommon:Localize Calendar_AppointmentTitlePlaceholder}">
</Entry>

</telerikPrimitives:RadBorder>

<!--Appointment Details-->
<Editor Text="{Binding Appointment.Detail}"
AutoSize="TextChanges"
Margin="{OnPlatform iOS='0, 23, 0, 20', Default='0, 23, 0, 14'}"
Placeholder="{telerikCommon:Localize Calendar_DetailsEditorPlaceholderText}">
<Editor.Effects>
<telerikCommon:NoTextOffsetEffect />
</Editor.Effects>

400
Telerik UI for Xamarin

</Editor>
</StackLayout>
</ScrollView>

<telerikPrimitives:RadBorder BorderColor="#C8C7CC"
BorderThickness="0, 1, 0, 0"
Grid.Row="1">
<Grid ColumnSpacing="0">
<Button Grid.Column="0"
Command="{Binding SaveAppointmentCommand}"

Text="{telerikCommon:Localize Calendar_AppointmentOKButton}" />


<Button Grid.Column="1"
Command="{Binding CancelCommand}"

Text="{telerikCommon:Localize Calendar_AppointmentCancelButton}" />

</Grid>
</telerikPrimitives:RadBorder>
</Grid>
</ControlTemplate>

<Style TargetType="telerikInput:AddAppointmentView">
<Setter Property="SeparatorThickness" Value="2"/>
<Setter Property="ControlTemplate" Value="{StaticResource
AddAppointmentViewControlTemplate}"/>
</Style>
 

In addition you will need to add the following namespace:

XAML
xmlns:telerikCommon="clr-namespace:Telerik.XamarinForms.Common;assembly=Telerik.Xamari
nForms.Common"
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
 

Here is the Result:

401
Telerik UI for Xamarin

If you customize the control template using ControlTemplate property, you need to define first the
control template then the style in the App.xaml Resources. Also when the control template is defined
in the App.xaml resources it will be applied for all RadCalendar controls used in the application. If
you want to apply the control template on a concreate calendar control, you will need to merge the
resource dictionary to the concreate page where the calendar is defines. Example can be found in
out Telerik Sample Application.
 

See Also
 Appointment Summery View
 Delete Appointment View
 Color Picker View
 Custom Recurrence View
 Repeat Appointment View

402
Telerik UI for Xamarin

Appointment Summary View


Appointment Summary View displays brief information about the appointment. The Appointment's
Title, Details, Start Date and End Date, Recurrence, Detail.

Visual Structure of Appointment Summary View

Control Template
The control template for the AppointmentSummaryView can be found at the following location in our
SDKBrowser Application.
 

Customization Properties

403
Telerik UI for Xamarin

In addition, to avoid editing the whole control template, there are additional properties which you can
use to customize the look of the AppointmentSummaryView:

 ControlTemplate(controlTemplate): Defines the Control Template of the


AppintmentSummaryView.
 AppointmentTitleFontSize(double): Defines the font size of the appointment title.
 AppointmentTitleTextColor(Xamarin.Forms.Color): Defines the text color of the appointment
title.
 DetailsTextColor(Xamarin.Forms.Color): Defines the text color of the appointment detail.
 DetailsFontSize(Xamarin.Forms.Color): Defines the font size of the appointment detail text.
 ButtonBackgroundColor(Xamarin.Forms.Color): Defines the background color for the Delete
event button.
 ButtonTextColor(Xamarin.Forms.Color): Defines the text color of the Delete event button.
 BackgroundColor(Xamarin.Forms.Color): Defines the background color of the
AppintmentSummaryView.

These properties or the ControlTemplate can be changed by applying style with


TargetType="telerikInput:AppointmentSummaryView" in the resources of the “App.xaml” file of your
application.
 

404
Telerik UI for Xamarin

If you customize the control template using ControlTemplate property, you need to define first the
control template then the style in the App.xaml Resources. Also when the control template is defined
in the App.xaml resources it will be applied for all RadCalendar controls used in the application. If
you want to apply the control template on a concreate calendar control, you will need to merge the
resource dictionary to the concreate page where the calendar is defines. Example can be found in
out Telerik Sample Application.
 

Example
XAML
<Style TargetType="telerikInput:AppointmentSummaryView">
<Setter Property="DetailsFontSize" Value="24"/>
<Setter Property="AppointmentTitleTextColor" Value="LightBlue"/>
<Setter Property="BackTextColor" Value="Blue"/>
</Style>
 

In addition, you will need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

See Also
 Delete Appointment View
 Color Picker View

405
Telerik UI for Xamarin

Color Picker View


ColorPickerView is a view for picking color which is applied to the appointment.

Visual Structure of Color Picker View

Control Template
The control template for the ColorPickerView can be found at the following location in our SDKBrowser
Application.
 

Customization Properties
In addition, to avoid editing the whole control template, there are additional properties which you can

406
Telerik UI for Xamarin

use to customize the look of the ColorPickerView:

 ControlTemplate(controlTemplate): Defines the Control Template of the ColorPickerView.


 TitleFontSize(double): Defines the font size of the color picker title.
 TitleTextColor(Xamarin.Forms.Color): Defines the text color of the color picker title.
 ButtonBackgroundColor(Xamarin.Forms.Color): Defines the background color of the Cancel
button.
 ButtonTextColor(Xamarin.Forms.Color): Defines the text color of the Cancel button.
 BackgroundColor(Xamarin.Forms.Color): Defines the background color of the
ColorPickerView.

These properties or the ControlTemplate can be changed by applying style with


TargetType="telerikInput:ColorPickerView" in the resources of the “App.xaml” file of your application.
 
If you customize the control template using ControlTemplate property, you need to define first the
control template then the style in the App.xaml Resources. Also when the control template is defined
in the App.xaml resources it will be applied for all RadCalendar controls used in the application. If
you want to apply the control template on a concreate calendar control, you will need to merge the
resource dictionary to the concreate page where the calendar is defines. Example can be found in
out Telerik Sample Application.

407
Telerik UI for Xamarin

Example:
XAML
<Style TargetType="telerikInput:ColorPickerView">
<Setter Property="ButtonBackgroundColor" Value="Blue"/>
<Setter Property="TitleFontSize" Value="16"/>
<Setter Property="BackgroundColor" Value="LightGray"/>
</Style>
 

In addition, you will need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

See Also
 Appointment Summery View
 Delete Appointment View
 Custom Recurrence View
 Repeat Appointment View

408
Telerik UI for Xamarin

Delete Appointment View


DeleteAppointmentView – view for choosing appointment deleting options.

Visual Structure of Delete Appointment View

Control Template
The control template for the DeleteAppointmentView can be found at the following location in our
SDKBrowser Application.
 

Customization Properties
 ControlTemplate(ControlTemplate): Defines the control template of the

409
Telerik UI for Xamarin

DeleteAppointmentView.
 BackgroundColor(Xamarin.Forms.Color): Defines the background color of the
DeleteAppointmentView.

These properties or the ControlTemplates can be changed by applying style with


TargetType="telerikInput:DeleteAppointmentView" in the resources of the “App.xaml” file of your
application.
 
If you customize the control template using ControlTemplate property, you need to define first the
control template then the style in the App.xaml Resources. Also when the control template is defined
in the App.xaml resources it will be applied for all RadCalendar controls used in the application. If
you want to apply the control template on a concreate calendar control, you will need to merge the
resource dictionary to the concreate page where the calendar is defines. Example can be found in
out Telerik Sample Application.
 

Example:
XAML
<Style TargetType="telerikInput:DeleteAppointmentView">
<Setter Property="BackgroundColor" Value="Red"/>
</Style>
 

In addition you will need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

See Also
 Add Appointment View
 Appointment Summery View
 Color Picker View
 Custom Recurrence View
 Repeat Appointment View
 End Repeat Appointment View

410
Telerik UI for Xamarin

Save Recurring Appointment View


SaveRecurringAppointmentView is a view for choosing recurring appointment saving options.

Control Template
The control template for the SaveRecurringAppointmentView can be found at the following location in
our SDK Browse Application.
 

Customization Properties
In addition, to avoid editing the whole control template, there are additional properties which you can
use to customize the look of the UIs, such as SeparatorThickness, ButtonBackgroundColor, etc.

 ControlTemplate(controlTemplate): Defines the Control Template of the


SaveRecurringAppointmentView.
 BackgroundColor(Xamarin.Forms.Color): Defines the background color of the
SaveRecurringAppointmentView.

These properties or the ControlTemplate can be changed by applying style with


TargetType="telerikInput:SaveRecurringAppointmentView" in the resources of the “App.xaml” file of
your application.
 
If you customize the control template using ControlTemplate property, you need to define first the
control template then the style in the App.xaml Resources. Also when the control template is defined
in the App.xaml resources it will be applied for all RadCalendar controls used in the application. If
you want to apply the control template on a concreate calendar control, you will need to merge the
resource dictionary to the concreate page where the calendar is defines. Example can be found in
out Telerik Sample Application.
 

Example
XAML
<Style TargetType="telerikInput:SaveRecurringAppointmentView">
<Setter Property="BackgroundColor" Value="Blue"/>
</Style>
 

In addition, you will need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

411
Telerik UI for Xamarin

See Also
 Add Appointment View
 Appointment Summery View
 Delete Appointment View
 Color Picker View
 Custom Recurrence View
 Repeat Appointment View
 End Repeat Appointment View

412
Telerik UI for Xamarin

Delete Recurring Appointment View


DeleteRecurringAppointmentView is a view for choosing recurring appointments deleting options.

Control Template
The control template for the DeleteRecurringAppointmentView can be found at the following location
in our SDKBrowser Application.
 

Customization Properties
In addition, to avoid editing the whole control template, there are additional properties which you can
use to customize the look of the UIs, such as SeparatorThickness, ButtonBackgroundColor, etc.

 ControlTemplate(ControlTemplate): Defines the control template of the


DeleteRecurringAppointmentView.
 BackgroundColor(Xamarin.Forms.Color): Defines the background color of the
DeleteRecurringAppointmentView.

These properties or the ControlTemplates can be changed by applying style with


TargetType="telerikInput:DeleteRecurringAppointmentView" in the resources of the “App.xaml” file of
your application.
 
If you customize the control template using ControlTemplate property, you need to define first the
control template then the style in the App.xaml Resources. Also when the control template is defined
in the App.xaml resources it will be applied for all RadCalendar controls used in the application. If
you want to apply the control template on a concreate calendar control, you will need to merge the
resource dictionary to the concreate page where the calendar is defines. Example can be found in
out Telerik Sample Application.
 

Example:
XAML
<Style TargetType="telerikInput:DeleteRecurringAppointmentView">
<Setter Property="BackgroundColor" Value="Red"/>
</Style>
 

In addition you will need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

413
Telerik UI for Xamarin

See Also
 Add Appointment View
 Appointment Summery View
 Delete Appointment View
 Color Picker View
 Custom Recurrence View
 Repeat Appointment View
 End Repeat Appointment View

414
Telerik UI for Xamarin

Repeat Appointment View


RepeatAppointmentView is a view for choosing predefined repeat options like EveryDay, Every
Month, Every Year, etc.

Visual Structure of Repeat Appointment View

Control Template
The control template for the RepeatAppointmentView can be found at the following location in our
SDKBrowser Application.
 

Customization Properties

415
Telerik UI for Xamarin

In addition, to avoid editing the whole control template, there are additional properties which you can
use to customize the look of the UIs, such as SeparatorThickness, ButtonBackgroundColor, etc.

 ControlTemplate(controlTemplate): Defines the Control Template of the


RepeatAppointmentView.
 TitleFontSize(double): Defines the font size of the RepeatAppointmentView title.
 TitleTextColor(Xamarin.Forms.Color): Defines the text color of the RepeatAppointmentView
title.
 FontSize(double): Defines the font size of the repeat appointment options.
 TextColor(Xamarin.Forms.Color): Defines the text color of the repeat appointment options.
 SeparatorColor(Xamarin.Forms.Color): Defines the color of the separator (the lines which
devide each repeat appointment option).
 SeparatorThickness(Xamarin.Forms.Thickness): Defines the thickness of the separators (the
lines which devide each repeat appointment option).
 ButtonBackgroundColor(Xamarin.Forms.Color): Defines the background color for the OK and
Cancel buttons.
 ButtonTextColor(Xamarin.Forms.Color): Defines the text color of the OK and Cancel buttons.
 BackgroundColor(Xamarin.Forms.Color): Defines the background color of the
RepeatAppointmentView.

These properties or the ControlTemplate can be changed by applying style with


TargetType="telerikInput:RepeatAppointmentView" in the resources of the “App.xaml” file of your
application.
 
If you customize the control template using ControlTemplate property, you need to define first the
control template then the style in the App.xaml Resources. Also when the control template is defined
in the App.xaml resources it will be applied for all RadCalendar controls used in the application. If
you want to apply the control template on a concreate calendar control, you will need to merge the
resource dictionary to the concreate page where the calendar is defines. Example can be found in
out Telerik Sample Application.
 

416
Telerik UI for Xamarin

Example
XAML
<Style TargetType="telerikInput:RepeatAppointmentView">
<Setter Property="TextColor" Value="Red"/>
<Setter Property="TitleTextColor" Value="Red"/>
<Setter Property="TitleFontSize" Value="20"/>
...
</Style>
 

In addition, you will need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

See Also

417
Telerik UI for Xamarin

 Add Appointment View


 Appointment Summery View
 Delete Appointment View
 Color Picker View
 Custom Recurrence View
 End Repeat Appointment View

418
Telerik UI for Xamarin

End Repeat Appointment View


EndRepeatAppointmentView is a view for choosing when recurring appointments end.

Visual Structure of End Repeat Appointment View

Control Template
The control template for the EndRepeatAppointmentView can be found at the following location in our
SDKBrowser Application.
 

Customization Properties
In addition, to avoid editing the whole control template, there are additional properties which you can

419
Telerik UI for Xamarin

use to customize the look of the EndRepeatAppointmentView:

 ControlTemplate(controlTemplate): Defines the Control Template of the


EndRepeatAppointmentView.
 TitleFontSize(double): Defines the font size of the EndRepeatAppointmentView title.
 TitleTextColor(Xamarin.Forms.Color): Defines the text color of the
EndRepeatAppointmentView title.
 FontSize(double): Defines the font size of the end repeat appointment options.
 TextColor(Xamarin.Forms.Color): Defines the text color of the end repeat appointment
options.
 SeparatorColor(Xamarin.Forms.Color): Defines the color of the separator (the lines which
devide each end repeat appointment option).
 SeparatorThickness(Xamarin.Forms.Thickness): Defines the thickness of the separators (the
lines which devide each end repeat appointment option).
 ButtonBackgroundColor(Xamarin.Forms.Color): Defines the background color for the OK and
Cancel buttons.
 ButtonTextColor(Xamarin.Forms.Color): Defines the text color of the OK and Cancel buttons.
 SelectionSymbolColor(Xamarin.Forms.Color): Defines the color of the symbol when end
repeat appointment option is selected.
 SummaryTextColor(Xamarin.Forms.Color): Defines the text color of the summary text (when
the repeat appointment ends).
 SummaryFontSize(double): Defines the font size of the summary text (when the repeat
appointment ends).
 BackgroundColor(Xamarin.Forms.Color): Defines the background color of the
EndRepeatAppointmentView.

420
Telerik UI for Xamarin

These properties or the ControlTemplate can be changed by applying style with


TargetType="telerikInput:EndRepeatAppointmentView" in the resources of the “App.xaml” file of your
application.
 
If you customize the control template using ControlTemplate property, you need to define first the
control template then the style in the App.xaml Resources. Also when the control template is defined
in the App.xaml resources it will be applied for all RadCalendar controls used in the application. If
you want to apply the control template on a concreate calendar control, you will need to merge the
resource dictionary to the concreate page where the calendar is defines. Example can be found in
out Telerik Sample Application.
 

Example
XAML
<Style TargetType="telerikInput:EndRepeatAppointmentView">
<Setter Property="TextColor" Value="Red"/>
<Setter Property="TitleTextColor" Value="Red"/>
<Setter Property="TitleFontSize" Value="20"/>
...
</Style>
 

421
Telerik UI for Xamarin

In addition, you will need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

See Also
 Add Appointment View
 Appointment Summery View
 Delete Appointment View
 Color Picker View
 Custom Recurrence View
 Repeat Appointment View

422
Telerik UI for Xamarin

Custom Recurrence View


CustomRecurrenceView is a view for choosing custom recurring intervals of an appointment.

Visual Structure of Custom Recurrence View

Control Template
The control template for the CustomRecurrenceView can be found at the following location in our
SDKBrowser Application.
 

Customization Properties
In addition, to avoid editing the whole control template, there are additional properties which you can

423
Telerik UI for Xamarin

use to customize the look of the CustomRecurrenceView:

 ControlTemplate(controlTemplate): Defines the Control Template of the


CustomRecurrenceView.
 TitleFontSize(double): Defines the font size of the custom recurrence title.
 TitleTextColor(Xamarin.Forms.Color): Defines the text color of the custom recurrence title.
 TextColor(Xamarin.Forms.Color): Defines the text color of the frequency text, interval text,
etc.
 SeparatorColor(Xamarin.Forms.Color): Defines the color of the separator (the lines which
devide each custom recurrence option).
 SeparatorThickness(Xamarin.Forms.Thickness): Defines the thickness of the separators (the
lines which devide each custom recurrence option).
 DetailsTextColor(Xamarin.Forms.Color): Defines the text color of the recurence detail.
 DetailsFontSize(Xamarin.Forms.Color): Defines the font size of the recurrence detail text.
 ButtonBackgroundColor(Xamarin.Forms.Color): Defines the background color for the OK and
Cancel buttons.
 ButtonTextColor(Xamarin.Forms.Color): Defines the text color of the OK and Cancel buttons.
 BackgroundColor(Xamarin.Forms.Color): Defines the background color of the
CustomRecurrenceView.

424
Telerik UI for Xamarin

These properties or the ControlTemplate can be changed by applying style with


TargetType="telerikInput:CustomRecurrenceView" in the resources of the “App.xaml” file of your
application.
 
If you customize the control template using ControlTemplate property, you need to define first the
control template then the style in the App.xaml Resources. Also when the control template is defined
in the App.xaml resources it will be applied for all RadCalendar controls used in the application. If
you want to apply the control template on a concreate calendar control, you will need to merge the
resource dictionary to the concreate page where the calendar is defines. Example can be found in
out Telerik Sample Application.
 

Example
XAML
<Style TargetType="telerikInput:CustomRecurrenceView">
<Setter Property="TextColor" Value="Red"/>
<Setter Property="TitleTextColor" Value="Red"/>
<Setter Property="TitleFontSize" Value="20"/>
</Style>
 

In addition, you will need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

See Also
 Add Appointment View
 Appointment Summery View
 Delete Appointment View
 Color Picker View
 Repeat Appointment View
 End Repeat Appointment View

425
Telerik UI for Xamarin

Scheduling UI Events
Since R3 2021 Service Pack Calendar's Scheduling UIs for Xamarin exposes events for
appointments changes:

 AppointmentAdded(AppointmentChangedEventAgrs): Occurs when appointment is added


throught the Scheduling UI.
 The sender argument which is of type object, but can be cast to the RadCalendar type.
 An AppointmentChangedEventAgrs object which provides the following properties:
 Appointment property of type IAppointment and could be cast to the appointment
implementation that is used in RadCalendar.
 Occurrence property of type IExceptionOccurrence which gets the occurance. If the
appointment is not recurrent, the value is null.
 OccurrenceAction property of type OccurrenceAction which gets the action
performed over the occurrence.
 AppointmentUpdated(AppointmentChangedEventAgrs): Occurs when appointment is
updated. The event is also raised for recurrent appointment when there is an action over the
exception occurence - add/delete/update.
 The sender argument which is of type object, but can be cast to the RadCalendar type.
 An AppointmentChangedEventAgrs object which provides the following properties:
 Appointment property of type IAppointment and could be cast to the appointment
implementation that is used in RadCalendar.
 Occurrence property of type IExceptionOccurrence which gets the occurance. If the
appointment is not recurrent, the value is null.
 OccurrenceAction property of type OccurrenceAction which gets the action
performed over the occurrence.

The OccurrenceAction enumeration specifies an action performed over an exception occurrence.


The actions are:

 None: No action is performed over the exception occurrence of the recurrent appointment.
 Add: When an exception occurence of the recurrent appointment is added.
 Update: When an exception occurence of the recurrent appointment is updated.
 Delete: When an exception occurence of the recurrent appointment is deleted.
 AppointmentDeleted(AppointmentChangedEventAgrs): Occurs when appointment is deleted.
 The sender argument which is of type object, but can be cast to the RadCalendar type.
 An AppointmentChangedEventAgrs object which provides the following properties:
 Appointment property of type IAppointment and could be cast to the appointment
implementation that is used in RadCalendar.
 Occurrence property of type IExceptionOccurrence which gets the occurance. If the
appointment is not recurrent, the value is null.
 OccurrenceAction of type OccurrenceAction which gets the action performed over
the occurrence.

In order to use these events, set SchedulingUiEnabled to True.


 

426
Telerik UI for Xamarin

Example
This example demonstrates a sample usage of appointment added, appointment updated and
appointment deleted events. The ViewMode is set to MultiDayView.

Calendar definition in XAML:

XAML
<telerikInput:RadCalendar x:Name="calendar"
SchedulingUiEnabled="True"
ViewMode="MultiDay"
AppointmentAdded="CalendarAppointmentAdded"
AppointmentUpdated="CalendarAppointmentUpdated"
AppointmentDeleted="CalendarAppointmentDeleted">
<telerikInput:RadCalendar.MultiDayViewSettings>
<telerikInput:MultiDayViewSettings DayStartTime="8:00:00" />
</telerikInput:RadCalendar.MultiDayViewSettings>
</telerikInput:RadCalendar>
 

Events:

C#
private void CalendarAppointmentAdded(object sender, AppointmentChangedEventAgrs e)
{
Application.Current.MainPage.DisplayAlert("Appointment Change",
String.Format("Appointment with title `{0}` was created.", e.Appointment.Title),
"OK");
}

private void CalendarAppointmentUpdated(object sender, AppointmentChangedEventAgrs e)


{
string notification;
switch(e.OccurrenceAction)
{
case OccurrenceAction.Add:
notification = String.Format("Exception occurence on {0:d} of the recurrent
Appointment `{1}` was created.", e.Occurrence.ExceptionDate, e.Appointment.Title);
break;
case OccurrenceAction.Update:
notification = String.Format("Exception occurence on {0:d} of the recurrent
Appointment `{1}` was updated.", e.Occurrence.ExceptionDate, e.Appointment.Title);
break;
case OccurrenceAction.Delete:
notification = String.Format("The occurence on {0:d} of the recurrent
Appointment `{1}` was deleted.", e.Occurrence.ExceptionDate, e.Appointment.Title);
break;
default:
notification = String.Format("Appointment `{0}` was updated",
e.Appointment.Title);
break;
}

427
Telerik UI for Xamarin

Application.Current.MainPage.DisplayAlert("Appointment Change", notification,


"OK");
}

private void CalendarAppointmentDeleted(object sender, AppointmentChangedEventAgrs e)


{
Application.Current.MainPage.DisplayAlert("Appointment Change",
String.Format("Appointment with title `{0}` was deleted.", e.Appointment.Title),
"OK");
}
 

428
Telerik UI for Xamarin

See Also
 View Modes
 Day View
 MultiDay View
 Agenda View
 Recurrence
 Calendar Selection

429
Telerik UI for Xamarin

Special and Restricted Slots


With R3 2019 release of Telerik UI for Xamarin RadCalendar provides the option to define a
collection of special and restricted time slots in order to make them noticeable across the timeline of
the Day and MultiDay views.

You just need to prepare a collection of SpecialSlot objects and assign it to SpecialSlotsSource
collection of the DayViewSettings / MultiDayViewSettings for Day/MultiDay view, respectively.

Every SpecialSlot has the following properties:

 StartDate;
 EndDate;
 RecurrencePattern: Defines whether the slot will be displayed for repeating days;
 IsReadOnly: When set to True the slot is disabled (restricted), meaning the end user
wouldn't be able to create or modify appointments at that slot (tapping over a read-only slot
will not show Create Appointment screen).

Appointments that cover restricted and non restricted slots at the same time can still be modified
through the Scheduling UIs.
 
Below you can find a quick example how to create special and restricted slots.

First, create a ViewModel class with a collection of SpecialSlot objects. In the example two repeating
special slots are added for rest hours during weekdays. In addition, the first slot which represents a
lunch break, is set as restricted time.

C#
public class ViewModel
{
public ViewModel()
{
this.RestHours = new ObservableCollection<SpecialSlot>();

var today = DateTime.Today;


var dailyRecurrence = new RecurrencePattern()
{
DaysOfWeekMask = RecurrenceDays.WeekDays,
Frequency = RecurrenceFrequency.Weekly,
MaxOccurrences = 30
};

this.RestHours.Add(new SpecialSlot(today.AddHours(12), today.AddHours(13))


{
RecurrencePattern = dailyRecurrence,
IsReadOnly = true
});
this.RestHours.Add(new SpecialSlot(today.AddHours(16),
today.AddHours(16).AddMinutes(15))

430
Telerik UI for Xamarin

{
RecurrencePattern = dailyRecurrence
});
}

public ObservableCollection<SpecialSlot> RestHours { get; set; }


}
 

Then, add RadCalendar definition with MultiDay ViewMode and MultiDayViewSettings applied:

XAML
<telerikInput:RadCalendar x:Name="calendar"
ViewMode="MultiDay"
SchedulingUiEnabled="True">
<telerikInput:RadCalendar.MultiDayViewSettings>
<telerikInput:MultiDayViewSettings VisibleDays="7"
SpecialSlotsSource="{Binding RestHours}" />
</telerikInput:RadCalendar.MultiDayViewSettings>
</telerikInput:RadCalendar>
 

Last step is to set the BindingContext to the ViewModel class:

C#
this.BindingContext = new ViewModel();
 

Here is the result after executing the example above on different platforms:

431
Telerik UI for Xamarin

Setting a separate Style for different slots


Through the SpecialSlotStyleSelector property of the DayViewSettings (or MultiDayViewSettings)
you can apply different background color to slots depending on certain condition. The
SpecialSlotStyleSelector provides SelectStyle method with the SpecialSlot as a parameter. The
method should return an object of type CalendarSpecialSlotStyle which exposes a BackgroundColor
property.

The sample below extends the previous example by applying separate styles to both types of special
slots through a SpecialSlotStyleSelector.

Create a custom style selector class which inherits from SpecialSlotStyleSelector and override
SelectStyle method:

C#
public class RestHoursStyleSelector : SpecialSlotStyleSelector
{
public CalendarSpecialSlotStyle LunchBreakStyle { get; set; }
public CalendarSpecialSlotStyle ShortBreakStyle { get; set; }

public override CalendarSpecialSlotStyle SelectStyle(object item)


{
var specialSlot = item as SpecialSlot;
if (specialSlot.StartDate.Hour == 12)
return this.LunchBreakStyle;

return this.ShortBreakStyle;
}

432
Telerik UI for Xamarin

}
 

Add the created RestHoursStyleSelector as a Resource and define both Styles:

XAML
<ResourceDictionary>
<local:RestHoursStyleSelector x:Key="RestHoursStyleSelector">
<local:RestHoursStyleSelector.LunchBreakStyle>
<telerikInput:CalendarSpecialSlotStyle BackgroundColor="#FFD09E"/>
</local:RestHoursStyleSelector.LunchBreakStyle>
<local:RestHoursStyleSelector.ShortBreakStyle>
<telerikInput:CalendarSpecialSlotStyle BackgroundColor="#FFEAC6"/>
</local:RestHoursStyleSelector.ShortBreakStyle>
</local:RestHoursStyleSelector>
</ResourceDictionary>
 

All that is left, is to set the SpecialStyleSelector property of the MultiDayViewSettings:

XAML
<telerikInput:RadCalendar x:Name="calendar"
ViewMode="MultiDay"
SchedulingUiEnabled="True">
<telerikInput:RadCalendar.MultiDayViewSettings>
<telerikInput:MultiDayViewSettings VisibleDays="7"
SpecialSlotsSource="{Binding RestHours}"
SpecialSlotStyleSelector="{StaticResource RestHoursStyleSelector}"/>
</telerikInput:RadCalendar.MultiDayViewSettings>
</telerikInput:RadCalendar>
 

Check the result in the image below:

433
Telerik UI for Xamarin

Applying a ContentTemplate to the slots


By default the special slots are marked with a different background. In addition you could show a
content of your choice inside special slots through the SpecialSlotContentTemplate property of the
DayViewSettings / MultiDaySettings.

For the example, create a custom slot that inherits from SpecialSlot class:

C#
public class BreakSlot : SpecialSlot
{
private string title;

public string Title


{
get
{
return this.title;
}
set
{
if (this.title != value)
{
this.title = value;
this.OnPropertyChanged();
}
}
}

434
Telerik UI for Xamarin

}
 

In the ViewModel class, add a collection of BreakSlot objects that will be then assigned as a
SpecialSlotsSource:

C#
public class ViewModel
{
public ViewModel()
{
this.RestHours = new ObservableCollection<BreakSlot>();

var today = DateTime.Today;


var dailyRecurrence = new RecurrencePattern()
{
DaysOfWeekMask = RecurrenceDays.WeekDays,
Frequency = RecurrenceFrequency.Weekly,
MaxOccurrences = 30
};

this.RestHours.Add(new BreakSlot()
{
Title = "Lunch time",
StartDate = today.AddHours(12),
EndDate = today.AddHours(13),
IsReadOnly = true,
RecurrencePattern = dailyRecurrence
});
this.RestHours.Add(new BreakSlot()
{
Title = "Coffee break",
StartDate = today.AddHours(16),
EndDate = today.AddHours(16).AddMinutes(30),
RecurrencePattern = dailyRecurrence
});
}

public ObservableCollection<BreakSlot> RestHours { get; set; }


}
 

Here is the RadCalendar definition where SpecialSlotContentTemplate property is applied:

XAML
<telerikInput:RadCalendar x:Name="calendar"
ViewMode="MultiDay"
SchedulingUiEnabled="True">
<telerikInput:RadCalendar.MultiDayViewSettings>
<telerikInput:MultiDayViewSettings VisibleDays="7"
SpecialSlotsSource="{Binding RestHours}"
SpecialSlotContentTemplate="{StaticResource RestHoursTemplate}"/>

435
Telerik UI for Xamarin

</telerikInput:RadCalendar.MultiDayViewSettings>
</telerikInput:RadCalendar>
 

And, lastly, add the RestHoursDataTemplate referenced earlier as a StaticResource:

XAML
<DataTemplate x:Key="RestHoursTemplate">
<Label Text="{Binding Title}"
Margin="5"
TextColor="#29398D"
FontSize="10" />
</DataTemplate>
 

Below you can check the result on different platforms:

All the Special Slots examples can be found in the Calendar & Scheduling/Features folder of the
SDK Samples Browser application.
 

See Also
 Date Properties
 View Modes
 Appointments
 Scheduling UI

436
Telerik UI for Xamarin

Non-Working Hours
 

RadCalendar provides the option to define the day working hours of the work week in DayView and
MultiDay Views. This means that you can set work start/end times, and in this case the remaining
hours of the day will be styled differently, so they are easily noticeable across the timeline as
non-working time.

Weekends are by default considered as non-working time.

Here is a list of the properties related to non-working hours feature:

 WorkStartTime (TimeSpan): Defines the start time of the working day;


 WorkEndTime (TimeSpan): Specifies the end time of the working day;
 AreNonWorkingHoursReadOnly (bool): Defines whether non-working hours will be marked
as restricted time. If AreNonWorkingHoursReadOnly is true, end users wouldn't be able to
create or modify appointments at the non-working time slots.
 NonWorkingTimeSlotsStyle (CalendarSpecialSlotStyle): Used to set the background color of
the non-working time slots.

All of the listed above properties can be applied to RadCalendar through DayViewSettings /
MultiDayViewSettings property of the DayView / MultiDayView, respectively.

Non-working hours feature is implemented through the special slots functionality of RadCalendar,
you could learn more about it in the Special and Restricted Slots article.
 

Example
Here is a sample RadCalendar definition with MultiDay ViewMode as well the the non-working hours
feature-related properties applied:

XAML
<telerikInput:RadCalendar x:Name="calendar"
ViewMode="MultiDay"
SchedulingUiEnabled="True">
<telerikInput:RadCalendar.MultiDayViewSettings>
<telerikInput:MultiDayViewSettings VisibleDays="7"
WorkStartTime="9:00:00"
WorkEndTime="18:00:00"
AreNonWorkingHoursReadOnly="True"
NonWorkingTimeSlotsStyle="{StaticResource MyNonWorkingHoursStyle}"/>
</telerikInput:RadCalendar.MultiDayViewSettings>
</telerikInput:RadCalendar>
 

Add the referenced MyNonWorkingHoursStyle as a Resource of type CalendarSpecialSlotStyle and

437
Telerik UI for Xamarin

set its BackgroundColor:

XAML
<ResourceDictionary>
<telerikInput:CalendarSpecialSlotStyle x:Key="MyNonWorkingHoursStyle"
BackgroundColor="#FFE6D8" />
</ResourceDictionary>
 

Check the result in the image below:

A Non-Working Hours example can be found in the Calendar & Scheduling/Features folder of the
SDK Samples Browser application.
 

See Also
 Date Properties
 View Modes
 Appointments

438
Telerik UI for Xamarin

Programmatic Scrolling
This article will explain how you could set up RadCalendar, so that the view is scrolled to specific
time or a particular appointment in DayView and MultiDayView modes.

ScrollTimeIntoView method
ScrollTimeIntoView method scrolls the current View (Day or MultiDay) to the specified time. It accept
a single parameter of type TimeSpan. The snippet below shows how the method could be used:

C#
TimeSpan time = TimeSpan.FromHours(16);
calendar.ScrollTimeIntoView(time);
 

And here is the result after the method is invoked:

ScrollAppointmentIntoView method
Through ScrollAppointmentIntoView method you could configure the current View (Day or MultiDay)
to scroll down and display the specified as a parameter appointment. Check the snippet below on
how this method is called:

C#

439
Telerik UI for Xamarin

var app = (calendar.AppointmentsSource as ObservableCollection<Appointment>).First();


calendar.ScrollAppointmentIntoView(app);
 

The next screenshot shows the result:

A sample Programmatic Scrolling example can be found in the Calendar & Scheduling/Features
folder of the SDK Samples Browser application.
 

See Also
 Date Properties
 View Modes
 Appointments

440
Telerik UI for Xamarin

Localization
RadCalendar for Xamarin provides language localization. In short, you can translate the used across
the Calendar & Scheduling UI texts and phrases to other languages, so that your app can be
adapted to different regions.

To learn in details about the localization process of Telerik UI for Xamarin components, please go
through the common Localization and Globalization topic.
 
The sections below list all the localization keys used in RadCalendar grouped by the views they
appear in.

Calendar Views Localization Keys


Localization Key Default Value Refers to
Calendar_AllDayAreaText ALL-DAY All-day area text in DayView
and MultiDayView on Android
and iOS
Calendar_AllDayAreaTextUW All-day All-day area text in DayView
P and MultiDayView on UWP
Calendar_AgendaAllDay All-Day All-day appointments label in
AgendaView
Calendar_AgendaStartTimeT Starts Multi-day appointments that
ext have Start and End times (so
they are not all-day)
Calendar_AgendaEndTimeTe Ends Multi-day appointments that
xt have Start and End times (so
they are not all-day)
Check in the image below how the localization strings are presented in AgendaView:

441
Telerik UI for Xamarin

Scheduling UIs Localization Keys


The next localization keys are related to RadCalendar Scheduling UIs. These include built-in views
for creating and modifying appointments, including applying recurrence rules.

Appointment Summary View

Localization Key Default Value


Calendar_EditButton Edit
Calendar_DeleteButton Delete Event
Calendar_AppointmentSummaryFromDate from
Calendar_AppointmentSummaryToDate to

442
Telerik UI for Xamarin

For detailed information on the view go to Appointment Summary View topic.


 

Add Appointment View

Localization Key Default Value


Calendar_AppointmentEventTitle Event
Calendar_EditEventTitle Event Title
Calendar_AppointmentStarts Starts
Calendar_AppointmentEnds Ends
Calendar_AppointmentAllDay All-day
Calendar_AppointmentRepeats Repeats
Calendar_AppointmentEndRepeats End Repeat
Calendar_AppointmentColor Color
Calendar_ColorPickerTitle Color
Calendar_DetailsEditorPlaceholderText Details

443
Telerik UI for Xamarin

Calendar_AppointmentOKButton OK
Calendar_AppointmentCancelButton Cancel

For detailed information on the view go to Add Appointment View topic.


 

Repeat Appointment View

Localization Key Default Value


Calendar_RepeatTitle Repeat
Calendar_AppointmentRepeatOptionsNever Never
Calendar_AppointmentRepeatOptionsEveryDa Every Day
y
Calendar_AppointmentRepeatOptionsEveryW Every Week
eek
Calendar_AppointmentRepeatOptionsEvery2 Every 2 Weeks
Weeks
Calendar_AppointmentRepeatOptionsEveryM Every Month

444
Telerik UI for Xamarin

onth
Calendar_AppointmentRepeatOptionsEveryYe Every Year
ar
Calendar_AppointmentRepeatOptionsCustom Custom

For detailed information on the view go to Repeat Appointment View topic.


 

End Repeat Appointment View

Localization Key Default Value


Calendar_EndRepeatLabel End Repeat Date
Calendar_EndRepeatOptionsAfter After number of occurrences
Calendar_EndRepeatOptionsNever Never
Calendar_EndRepeatOptionsOnDate On Date
Calendar_EndRepeatTitle End Repeat
Calendar_OccurencesLabel Number of occurrences

445
Telerik UI for Xamarin

For detailed information on the view go to End Repeat Appointment View topic.
 

Delete Appointment View

Localization Key Default Value


Calendar_Android_DeleteRecurringEventTitle Delete recurring event?
Calendar_Android_DeleteSeries All events in the series
Calendar_Android_DeleteSingleEvent Delete this event?
Calendar_Android_DeleteSingleRecurringEve This event
nt
Calendar_DeleteSingleEventAndroid Delete this event?
Calendar_iOS_DeleteSeries Delete All Events in the Series
Calendar_iOS_DeleteSingleEvent Delete event
Calendar_iOS_DeleteSingleRecurringEvent Delete This Event Only

446
Telerik UI for Xamarin

For detailed information on the view go to Delete Appointment View topic.


 

Save Recurring Appointment View

Localization Key Default Value


Calendar_Android_SaveRecurringEventTitle Save recurring event?
Calendar_Android_SaveSeries All events in the series
Calendar_Android_SaveSeriesNotification The changes will be applied to all events in the
series
Calendar_Android_SaveSingleRecurringEvent This event
Calendar_iOS_SaveSeries Save All Events in the Series

447
Telerik UI for Xamarin

For detailed information on the view go to Save Recurring Appointment View topic.
 

Custom Recurrence View

Localization Key Default Value


Calendar_CustomRecurrenceTitle Custom Recurrence
Calendar_CustomRecurrenceFrequency Frequency
Calendar_CustomReccurence_FrequencyPick Day
erTitle_Day
Calendar_CustomReccurence_FrequencyPick month
erTitle_Month
Calendar_CustomReccurence_FrequencyPick week
erTitle_Week
Calendar_CustomReccurence_FrequencyPick year
erTitle_Year
Calendar_CustomReccurenceAdditionalOption Each
s_Each

448
Telerik UI for Xamarin

Calendar_CustomReccurenceAdditionalOption On the...
s_OnThe
Calendar_CustomReccurenceMessage_DotC .
haracter
Calendar_CustomReccurenceMessage_First Event will occur every
Calendar_CustomReccurenceMessage_In in
Calendar_CustomReccurenceMessage_Month 5th
IndexFifth
Calendar_CustomReccurenceMessage_Month 1st
IndexFirst
Calendar_CustomReccurenceMessage_Month 4th
IndexFourth
Calendar_CustomReccurenceMessage_Month last
IndexLast
Calendar_CustomReccurenceMessage_Month 2nd
IndexSecond
Calendar_CustomReccurenceMessage_Month 3rd
IndexThird
Calendar_CustomReccurenceMessage_On on
Calendar_CustomReccurenceMessage_Prefix on the
Calendar_CustomReccurenceMessage_Suffix s
Calendar_CustomRecurrenceEvery Every
Calendar_FrequencyOptionsDaily Daily
Calendar_FrequencyOptionsMonthly Monthly
Calendar_FrequencyOptionsWeekly Weekly
Calendar_FrequencyOptionsYearly Yearly
Calendar_MonthFrequencyFifth Fifth
Calendar_MonthFrequencyFirst First
Calendar_MonthFrequencyFourth Fourth
Calendar_MonthFrequencyLast Last
Calendar_MonthFrequencySecond Second
Calendar_MonthFrequencyThird Third

449
Telerik UI for Xamarin

For detailed information on the view go to Custom Recurrence View topic.


 

Days/Months Names

Localization Key Default Value


Calendar_AdditionalInfoMonthDay Day
Calendar_AdditionalInfoMonthFriday Friday
Calendar_AdditionalInfoMonthMonday Monday
Calendar_AdditionalInfoMonthSaturday Saturday
Calendar_AdditionalInfoMonthSunday Sunday
Calendar_AdditionalInfoMonthThursday Thursday
Calendar_AdditionalInfoMonthTuesday Tuesday
Calendar_AdditionalInfoMonthWednesday Wednesday
Calendar_AdditionalInfoMonthWeekday Weekday
Calendar_AdditionalInfoMonthWeekendDay Weekend Day

450
Telerik UI for Xamarin

Calendar_MonthAbbreviationApril Apr
Calendar_MonthAbbreviationAugust Aug
Calendar_MonthAbbreviationDecember Dec
Calendar_MonthAbbreviationFebruary Feb
Calendar_MonthAbbreviationJanuary Jan
Calendar_MonthAbbreviationJuly Jul
Calendar_MonthAbbreviationJune Jun
Calendar_MonthAbbreviationMarch Mar
Calendar_MonthAbbreviationMay May
Calendar_MonthAbbreviationNovember Nov
Calendar_MonthAbbreviationOctober Oct
Calendar_MonthAbbreviationSeptember Sep
Calendar_WeekDayAbbreviationFriday F
Calendar_WeekDayAbbreviationMonday M
Calendar_WeekDayAbbreviationSaturday S
Calendar_WeekDayAbbreviationSunday S
Calendar_WeekDayAbbreviationThursday T
Calendar_WeekDayAbbreviationTuesday T
Calendar_WeekDayAbbreviationWednesday W

See Also
 Localization and Globalization
 View Modes
 Agenda View
 Scheduling UIs

451
Telerik UI for Xamarin

Events
The RadCalendar component exposes the following events:

 DisplayDateChanged: Occurs when the current display date is changed. The


DisplayDateChanged event handler receives two parameters:
 The sender argument which is of type object, but can be cast to the RadCalendar type.
 A ValueChangedEventArgs<object> object which provides both old and new values of
the DisplayDate property. The values are of type object, but can be cast to the DateTime
type.
 ViewChanged: Occurs when the calendar view mode is changed. The ViewChanged event
handler receives two parameters:
 The sender argument which is of type object, but can be cast to the RadCalendar type.
 A ValueChangedEventArgs<CalendarViewMode> object which provides both old and
new value of the ViewMode property. The values are of type CalendarViewMode.
 SelectionChanged: Occurs when the selected date is changed programmatically or due to
user interaction. The SelectionChanged event handler receives two parameters:
 The sender argument which is of type object, but can be cast to the RadCalendar type.
 A ValueChangedEventArgs<object> object which provides old and new value of the
SelectedDate. The values are of type object, but can be cast to the DateTime type.
 MonthChanged: Occurs when the calendar month is changed in Month ViewMode.
 The sender argument which is of type object, but can be cast to the RadCalendar type.
 A ValueChangedEventArgs<object> object which provides both NewValue and
PreviousValue. The values are of type object.
 TimeSlotTapped: Occurs when the end-user taps on a time slot.
 The sender argument which is of type object, but can be cast to the RadCalendar type.
 A TimeSlotTapEventArgs object which provides StartTime and EndTime properties of
type DateTime that define the time slot.
 AppointmentTapped: Occurs when you tap over a specific appointment when in
DayView/MultiDayView mode. It can be used to get all the information regarding the
appointment.
 The sender argument which is of type object, but can be cast to the RadCalendar type.
 An AppointmentTappedEventArgs object which provides Appointment property. The
Appointment is of type IAppointment and could be cast to the appointment
implementation that is used in RadCalendar.

In addition, RadCalendar provides the following eventa relating to the native Calendar control
renderer:

 NativeControlLoaded : Occurs when the renderer has finished preparing the native control.
 NativeControlUnloaded : Occurs when the native control is in invalid state.

Both event handlers receives two parameters:

 The sender argument which is of type object, but can be cast to the RadCalendar type.
 A System.EventArgs object.

With R3 2021 Service Pack Scheduling UIs exposes events for appointments changes:

452
Telerik UI for Xamarin

AppointmentAdded, AppointmentUpdated and AppointmentDeleted events. For more details


check the SchedulingUI Events article.
 

See Also
 Date Properties
 View Modes
 Appointments

453
Telerik UI for Xamarin

Elements Display Mode


Sometimes you would like to change the appearance of the calendar by hiding the day names or
week numbers. This article will explain how you can acheive this.

The calendar provides properties that control the visibility of its elements.

 DayNamesDisplayMode (DisplayMode): Gets or sets a value that specifies whether the day
names will be visible.
 WeekNumbersDisplayMode (DisplayMode): Gets or sets a value that specifies whether the
day names will be visible.

The two described properties are both of type DisplayMode, which is enumeration and has the
following values:

 Show: The element will be visible.


 Hide: The element will not be visible.
 Automatic: The visibility of the element will be determined by the value defined in the
platform specific resources.

Example

This example demonstrates how you can display the week numbers and hide the day names of the
calendar:

C#
var calendar = new RadCalendar();
calendar.WeekNumbersDisplayMode = DisplayMode.Show;
calendar.DayNamesDisplayMode = DisplayMode.Hide;
 

Here are the results from the code above:

454
Telerik UI for Xamarin

455
Telerik UI for Xamarin

Grid Lines Style


 GridLinesDisplayMode (DisplayMode): Gets or sets a value that specifies whether the grid
lines will be visible.
 GridLinesColor (Color): Gets or sets the color of the grid lines.
 GridLinesWidth (double): Gets or sets the width of the grid lines.

Example

This example demonstrates how you can customize the calendar grid lines.

var calendar = new RadCalendar();


calendar.GridLinesDisplayMode = DisplayMode.Show;
calendar.GridLinesColor = Color.FromRgb(229, 173, 241);
calendar.GridLinesWidth = 3;
 

This is the result:

456
Telerik UI for Xamarin

Cell Styling
This article describes the APIs used to customize the look of the calendar cells.

CalendarCell types
The CalendarCell objects are not actual visual elements, but they provide context that the user can
use to style different parts of the calendar. Here you can find more information about the calendar
visual structure.

All cells share a common base class - the CalendarCell. Here are its properties:

 Text (string): Gets the text displayed in the cell.


 Type (CalendarCellType): Gets the type of the cell. The possible values are:
 Date: all cells that correspond to actual dates has this type
 WeekNumber: cells that hold week numbers
 DayName: cells that hold the days of the week

Below are described the specific calendar cells and their properties.

CalendarDateCell
These cells hold date values (days, months, years). The Type of CalendarDateCell is Date.

 IsEnabled (bool): Gets a value that specifies whether the cell is enabled (inside the calendar
MinDate and MaxDate range).
 IsSelected (bool): Gets a value that specifies whether the cell is currently selected.
 Date (DateTime): Gets the date that corresponds to the cell.

CalendarDayCell
These cells hold dates in Month and Week view. The CalendarDayCell inherits from
CalendarDateCell and its Type is also Date.

 IsFromCurrentMonth (bool): Gets a value that specifies whether the cell is from the current
month in month view.
 IsToday (bool): Gets a value that specifies whether the cell date is today.

CalendarTextCell
These cells hold elements different from dates: week numbers and week day names and
correspondingly have Type WeekNumber or DayName.

CalendarCellStyle

457
Telerik UI for Xamarin

The CalendarCellStyle class provides the following properties:

 BackgroundColor (Color)
 BorderColor (Color)
 BorderThickness (Thickness)
 FontSize (double)
 FontWeight (FontWeight): Bold or Normal.
 ForegroundColor (Color)

The RadCalendar component exposes the following properties which enable you to style the
calendar cells:

 TitleCellStyle(Telerik.XamarinForms.Input.CalendarCellStyle): Defines the style for the title


cell.
 DayCellStyle(Telerik.XamarinForms.Input.CalendarCellStyle): Defines the style for the day
cell.
 DayNameCellStyle(Telerik.XamarinForms.Input.CalendarCellStyle): Defines the style for the
cells where the day names are.
 TodayCellStyle(Telerik.XamarinForms.Input.CalendarCellStyle): Defines the style for today
cell.
 WeekNumberCellStyle(Telerik.XamarinForms.Input.CalendarCellStyle): Defines the style for
the week number cell.
 DisabledCellStyle(Telerik.XamarinForms.Input.CalendarCellStyle): Defines the style for the
disabled cells.
 SelectedCellStyle(Telerik.XamarinForms.Input.CalendarCellStyle): Defines the style for the
selected cell.
 WeekendCellStyle(Telerik.XamarinForms.Input.CalendarCellStyle): Defines the style for the
weekend cell.
 OtherMonthCellStyle(Telerik.XamarinForms.Input.CalendarCellStyle): Defines the style for
other month cell.
 SetStyleForCell (Func<CalendarCell, CalendarCellStyle>): method which can be used for
styling the different calendar cells. We do not recommend using this method when applying a
Theming mechanisum the styling values set using the SetStyleForCell method are overriden.
So we can suggest using the separate properties for cell styling.

Example with Calendar Cell Styles properties


Here is the RadCalendar definition with the above properties set:

XAML
<input:RadCalendar WeekNumbersDisplayMode="Show">
<input:RadCalendar.TitleCellStyle>
<input:CalendarCellStyle BackgroundColor="LightBlue"
TextColor="Gray"
FontSize="20"/>
</input:RadCalendar.TitleCellStyle>

<input:RadCalendar.DayCellStyle>
<input:CalendarCellStyle TextColor="Black"/>
</input:RadCalendar.DayCellStyle>

458
Telerik UI for Xamarin

<input:RadCalendar.DayNameCellStyle>
<input:CalendarCellStyle TextColor="Black"/>
</input:RadCalendar.DayNameCellStyle>

<input:RadCalendar.TodayCellStyle>
<input:CalendarCellStyle BorderColor="LightBlue"
TextColor="Black"
BorderThickness="2" />
</input:RadCalendar.TodayCellStyle>

<input:RadCalendar.WeekNumberCellStyle>
<input:CalendarCellStyle TextColor="Black"/>
</input:RadCalendar.WeekNumberCellStyle>

<input:RadCalendar.DisabledCellStyle>
<input:CalendarCellStyle TextColor="LightGray"/>
</input:RadCalendar.DisabledCellStyle>

<input:RadCalendar.SelectedCellStyle>
<input:CalendarCellStyle BorderColor="LightGreen"
BorderThickness="2"
TextColor="Black"
FontSize="20"/>
</input:RadCalendar.SelectedCellStyle>

<input:RadCalendar.WeekendCellStyle>
<input:CalendarCellStyle TextColor="Red"/>
</input:RadCalendar.WeekendCellStyle>

<input:RadCalendar.OtherMonthCellStyle>
<input:CalendarCellStyle TextColor="LightGray" />
</input:RadCalendar.OtherMonthCellStyle>
</input:RadCalendar>
 

and the final result:

459
Telerik UI for Xamarin

Example with SetStyleForCell method


We do not recommend using this method when applying a Theming mechanisum the styling values
set using the SetStyleForCell method are overriden. So we can suggest using the separate
properties for cell styling.
 
This example demonstrates how you can apply styles to different calendar cell types.

C#
var calendar = new RadCalendar();
calendar.SetStyleForCell = this.EvaluateCellStyle;
calendar.GridLinesDisplayMode = DisplayMode.Show;
calendar.GridLinesColor = Color.Silver;
calendar.GridLinesWidth = 1;
 

And this is the method:

C#

460
Telerik UI for Xamarin

private CalendarCellStyle EvaluateCellStyle(CalendarCell cell)


{
Color background = default(Color);
Color selectedCellForegroundColor = default(Color);
Color todayBorderColor = Color.FromRgb(115, 174, 239);
double dayNamesFontSize = default(double);
double fontSize = default(double);
Thickness todayBorderThickness = default(Thickness);

switch (Device.RuntimePlatform)
{
case "iOS":
background = Color.White;
selectedCellForegroundColor = Color.White;
fontSize = 14;
dayNamesFontSize = 14;
todayBorderThickness = new Thickness(2);
break;
case "Android":
background = Color.White;
selectedCellForegroundColor = Color.FromHex("FF0066CC");
fontSize = 15;
dayNamesFontSize = 15;
todayBorderThickness = new Thickness(1);
break;
case "UWP":
background = Color.FromRgb(30, 30, 30);
selectedCellForegroundColor = Color.White;
fontSize = 17;
dayNamesFontSize = 17;
todayBorderThickness = new Thickness(2);
break;
}

if (cell.Type == CalendarCellType.DayName)
{
return new CalendarCellStyle
{
BackgroundColor = Color.LightGray,
FontSize = dayNamesFontSize,
FontAttributes = FontAttributes.Bold,
TextColor = Color.FromRgb(0, 122, 255)
};
}

var defaultStyle = new CalendarCellStyle


{
BackgroundColor = background,
FontSize = fontSize,
FontAttributes = FontAttributes.None,
TextColor = Color.FromRgb(139, 209, 0)
};

461
Telerik UI for Xamarin

if (cell is CalendarDayCell dayCell)


{
if (dayCell.IsFromCurrentMonth)
{
if (dayCell.IsToday)
{
defaultStyle.TextColor = Color.FromRgb(0, 122, 255);
defaultStyle.FontAttributes = FontAttributes.Bold;
defaultStyle.BorderColor = todayBorderColor;
defaultStyle.BorderThickness = todayBorderThickness;
}
}
else
{
if (dayCell.IsToday)
{
defaultStyle.TextColor = todayBorderColor;
defaultStyle.BorderColor = todayBorderColor;
defaultStyle.BorderThickness = todayBorderThickness;
}
else
{
defaultStyle.TextColor = Color.FromRgb(166, 181, 137);
}
}

if (dayCell.IsSelected)
{
defaultStyle.TextColor = selectedCellForegroundColor;
defaultStyle.BorderColor = Color.FromHex("FF0066CC");
}

return defaultStyle;
}

return null; // default style


}
 

Here is the result:

462
Telerik UI for Xamarin

463
Telerik UI for Xamarin

Appointments Styling
Appointments can be customized only in iOS and Android.
 
This article's purpose is to get users familiar with the AppointmentsStyle property of the
RadCalendar component. It is of type CalendarAppointmentsStyle that exposes number of
properties that will help you customize the calendar appointments in the most common scenarios.

Visual Structure
The events can be rendered as text or shapes or a combination of these. The images below explain
the the visual structure and the elements in the different display modes.

Text Mode

Shapes Mode

CalendarAppointmentsStyle Properties
Common properties

464
Telerik UI for Xamarin

 DisplayMode (AppointmentDisplayMode): Specifies how the appointments are visualized.


The possible modes are:
 Text
 TextWithShape
 TextWithBackground
 Shape
 MaxCount: Defines the maximum count of displayed events.
 Padding: Specifies the padding of the rectangle that holds the events.
 Spacing: Defines the empty space between two appointments in the same date.

Text Specific Properties

 FontSize: Defines a value controlling the size of the text of an appointment.


 TextColor: Defines the color for all appointments that are not marked as all day. This color
will be applied if the TextColorFromAppointment property is set to false.
 AllDayTextColor: Specifies the text color for the all-day appointments.
 MoreTextColor: Defines the color for the text indicating there are appointments that are not
displayed due to lack of space.
 TextPadding: Defines the padding of the appointments text.
 AllDayTextPadding: Defines the padding of the all-day appointments text.
 TextColorFromAppointment: It is a boolean value indicating whether the appointment text
should take its color from the IAppointment.Color value or the TextColor property value
should be used.
 TextVerticalLocation (VerticalLocation): Defines the vertical position of the text.
 TextHorizontalLocation (HorizontalLocation): Defines the horizontal position of the text.
 MoreTextFormatString: Specifies the format string that will be used to modify the text
displaying how many appointments remain hidden, e.g.: " {0} more"
 BackgroundRectBorderRadius: Defines the border radius of the text background rectangle.

Shapes Specific Properties

 ShapeSize (Size): Defines the dimensions that will be user when drawing the separate
shapes.
 ShapesOrientation: Specifies the orientation of the shapes.
 ShapeSize (Size): Specifies the size of the events shapes.
 ShapesVerticalLocation: Specifies the vertical position of the events shapes.
 ShapesHorizontalLocation: Specifies the horizontal position of the events shapes.
 AllDayShapesDisplayMode (AllDayDisplayMode): Specifies a value defining how the all-day
events will be visualized. The available options are:
 Indicator
 WithShapes
 AllDayIndicatorWidth: Specifies the width of the all-day indicator. It will take all available
space for its other dimension depending on its location.
 AllDayIndicatorPadding (Thickness): Sets the padding of the all-day indicator rectangle.
 ShapeType (CalendarAppointmentShapeType): Specifies the shape representing an
appointment. The available options are:
 Rectangle
 Ellipse
 TriangleUp
 TriangleDown

465
Telerik UI for Xamarin

 Rhombus

 AllDayShapeType (CalendarAppointmentShapeType): Defines the shape type of the all-day


appointments. If this property is not set, the ShapeType value will be used.
 AllDayIndicatorLocation (Location): Specifies the location where the all day indicators are
visualized.
 None
 Top
 Bottom
 Left
 Right

 ReserveIndicatorSpace: In scenarios where appointments are rendered as shapes with


all-day indicator, but there are no all-day events for a specific day. This boolean property
specifies whether the shapes will keep the space where the indicator is drawn or they will
take all available space.

Example
XAML
<telerikInput:RadCalendar x:Name="calendar">
<telerikInput:RadCalendar.AppointmentsStyle>
<telerikInput:CalendarAppointmentsStyle
DisplayMode="Shape"
Padding="5, 25, 5, 5"
MaxCount="10"
Spacing="1"
ShapeType="Rectangle"
ShapesHorizontalLocation = "Right"
ShapesVerticalLocation = "Bottom"
ShapesOrientation = "Vertical"
AllDayShapesDisplayMode="Indicator"
AllDayIndicatorLocation="Top"
AllDayIndicatorPadding="5, 2"
AllDayIndicatorWidth="2">

466
Telerik UI for Xamarin

<telerikInput:CalendarAppointmentsStyle.ShapeSize>
<Size Width="8" Height="6" />
</telerikInput:CalendarAppointmentsStyle.ShapeSize>
</telerikInput:CalendarAppointmentsStyle>
</telerikInput:RadCalendar.AppointmentsStyle>
</telerikInput:RadCalendar>
 

C#
calendar.AppointmentsStyle = new CalendarAppointmentsStyle
{
DisplayMode = AppointmentDisplayMode.Shape,
Padding = new Thickness(5, 25, 5, 5),
MaxCount = 10,
Spacing = 1,
ShapeType = CalendarAppointmentShapeType.Rectangle,
ShapesHorizontalLocation = HorizontalLocation.Right,
ShapesVerticalLocation = VerticalLocation.Bottom,
ShapesOrientation = Orientation.Vertical,
ShapeSize = new Size(6, 4),
AllDayShapesDisplayMode = AllDayDisplayMode.Indicator,
AllDayIndicatorLocation = Location.Top,
AllDayIndicatorPadding = new Thickness(5, 2),
AllDayIndicatorWidth = 2,
};
 

Here is the end result:

467
Telerik UI for Xamarin

See Also
 Appointments

468
Telerik UI for Xamarin

Custom Calendar Renderer


Sometimes, you might find that certain feature is available in the native control on a given platform,
but is not exposed in Xamarin Forms or you might want to customize the calendar look for each
platform. This is when you would need to create a custom renderer. This will allow you to access the
native control and configure it as per your needs.

The native Calendar control documentation can be found here.


 

Example
Let us consider the following example: we need to customize how the calendar looks on Android.
Create a class which inherits from Telerik.XamarinForms.InputRenderer.Android.CalendarRenderer
and override the OnElementChanged method:

C#
[assembly: ExportRenderer(typeof(CustomCalendar), typeof(CustomCalendarRenderer))]
namespace
SDKBrowser.Droid.Examples.CalendarControl.StylingCategory.CustomRendererExample
{
public class CustomCalendarRenderer : CalendarRenderer
{
public CustomCalendarRenderer(Context context) : base(context)
{
}

protected override void OnElementChanged(ElementChangedEventArgs<RadCalendar>


e)
{
base.OnElementChanged(e);

if (this.Control != null)
{
this.Control.CustomizationRule = new CustomizationRule();

this.Control.CellDecorationsLayer.Color =
Android.Graphics.Color.ParseColor("#0044FF");
}
}
}
}
 

The CellDecorationsLayer.Color property changes the border color of the currently selected cell. The
CustomizationRule property takes an object which implements the
Com.Telerik.Android.Common.IProcedure interface:

C#

469
Telerik UI for Xamarin

public class CustomizationRule : Java.Lang.Object, IProcedure


{
private Java.Util.Calendar calendar = Java.Util.Calendar.Instance;

public void Apply(Java.Lang.Object p0)


{
if (!(p0 is CalendarDayCell))
{
return;
}

CalendarDayCell calendarCell = p0.JavaCast<CalendarDayCell>();


if (calendarCell.CellType != CalendarCellType.Date)
{
return;
}

calendarCell.SetBackgroundColor(
Android.Graphics.Color.ParseColor("#F8F8F8"), // used when the cell is enabled
Android.Graphics.Color.ParseColor("#E0E0E0")); // used when the cell is
disabled

calendarCell.SetTextColor(
Android.Graphics.Color.ParseColor("#000000"), // used when the cell is enabled
Android.Graphics.Color.ParseColor("#FFFFFF")); // used when the cell is
disabled

calendar.TimeInMillis = calendarCell.Date;

var weekDay = calendar.Get(Java.Util.CalendarField.DayOfWeek);


if (weekDay == 1 || weekDay == 7)
{
calendarCell.SetBackgroundColor(
Android.Graphics.Color.ParseColor("#EEEEEE"), // used when the cell is enabled
Android.Graphics.Color.ParseColor("#E0E0E0")); // used when the cell is
disabled

calendarCell.SetTextColor(
Android.Graphics.Color.ParseColor("#999999"), // used when the cell is enabled
Android.Graphics.Color.ParseColor("#AAAAAA")); // used when the cell is
disabled
}

var currentDate =
Java.Util.Calendar.Instance.Get(Java.Util.CalendarField.Date);
var currentMoth =
Java.Util.Calendar.Instance.Get(Java.Util.CalendarField.Month);
var currentYear =
Java.Util.Calendar.Instance.Get(Java.Util.CalendarField.Year);

var boldTypeface = Android.Graphics.Typeface.Create(


calendarCell.TextPaint.Typeface, Android.Graphics.TypefaceStyle.Bold);

if (calendar.Get(Java.Util.CalendarField.Date) == currentDate &&


calendar.Get(Java.Util.CalendarField.Month) == currentMoth &&

470
Telerik UI for Xamarin

calendar.Get(Java.Util.CalendarField.Year) == currentYear)
{
calendarCell.BorderColor = Android.Graphics.Color.ParseColor("#00FF44");
calendarCell.BorderWidth = global::Android.App.Application.Context.ToPixels(2);

calendarCell.Typeface = boldTypeface;
}

if (calendarCell.Selected)
{
calendarCell.Typeface = boldTypeface;
}
}
}
 

Here is the result:

471
Telerik UI for Xamarin

Custom Calendar Renderer


Sometimes, you might find that certain feature is available in the native control on a given platform,
but is not exposed in Xamarin Forms or you might want to customize the calendar look for each
platform. This is when you would need to create a custom renderer. This will allow you to access the
native control and configure it as per your needs.

The native Calendar control documentation can be found here.


 

Example
Let us consider the following example: we need to customize how the calendar looks on iOS. Create
a class which inherits from Telerik.XamarinForms.InputRenderer.iOS.CalendarRenderer and
override the CreateCalendarDelegateOverride method:

C#
[assembly: ExportRenderer(typeof(CustomCalendar), typeof(CustomCalendarRenderer))]
namespace
SDKBrowser.iOS.Examples.CalendarControl.StylingCategory.CustomRendererExample
{
public class CustomCalendarRenderer : CalendarRenderer
{
protected override CalendarDelegate CreateCalendarDelegateOverride()
{
return new CustomCalendarDelegate();
}
}
}
 

The method should return object of class delivered from


Telerik.XamarinForms.InputRenderer.iOS.CalendarDelegate:

C#
public class CustomCalendarDelegate : CalendarDelegate
{
public override void UpdateVisualsForCell(TKCalendar calendar, TKCalendarCell
cell)
{
var dayCell = cell as TKCalendarDayCell;

if (dayCell != null)
{
this.SetBordersWidth(dayCell, 0);

TKCalendarDayState currentMonthState = TKCalendarDayState.CurrentMonth;


if ((dayCell.State & currentMonthState) == currentMonthState)
{

472
Telerik UI for Xamarin

dayCell.Style.BackgroundColor = Color.FromHex("#F8F8F8").ToUIColor();
dayCell.Style.TextColor = Color.FromHex("#000000").ToUIColor();
}
else
{
dayCell.Style.BackgroundColor = Color.FromHex("#E0E0E0").ToUIColor();
dayCell.Style.TextColor = Color.FromHex("#FFFFFF").ToUIColor();
}

TKCalendarDayState weekendState = TKCalendarDayState.Weekend;


if ((dayCell.State & weekendState) == weekendState)
{
if ((dayCell.State & currentMonthState) == currentMonthState)
{
dayCell.Style.BackgroundColor = Color.FromHex("#EEEEEE").ToUIColor();
dayCell.Style.TextColor = Color.FromHex("#999999").ToUIColor();
}
else
{
dayCell.Style.BackgroundColor = Color.FromHex("#D0D0D0").ToUIColor();
dayCell.Style.TextColor = Color.FromHex("#AAAAAA").ToUIColor();
}
}

TKCalendarDayState todayState = TKCalendarDayState.Today;


if ((dayCell.State & todayState) == todayState)
{
var borderColor = Color.FromHex("#00FF44");

dayCell.Style.ShapeFill = null;

this.SetBordersColor(dayCell, borderColor);
this.SetBordersWidth(dayCell, 2);
}

TKCalendarDayState selectedState = TKCalendarDayState.Selected;


if ((dayCell.State & selectedState) == selectedState)
{
var borderColor = Color.FromHex("#0044FF");

dayCell.Style.ShapeFill = null;

this.SetBordersColor(dayCell, borderColor);
this.SetBordersWidth(dayCell, 2);
}
}
}

private void SetBordersWidth(TKCalendarDayCell cell, int width)


{
cell.Style.TopBorderWidth = width;
cell.Style.LeftBorderWidth = width;
cell.Style.RightBorderWidth = width;
cell.Style.BottomBorderWidth = width;

473
Telerik UI for Xamarin

private void SetBordersColor(TKCalendarDayCell cell, Color color)


{
var uiColor = color.ToUIColor();

cell.Style.TopBorderColor = uiColor;
cell.Style.LeftBorderColor = uiColor;
cell.Style.RightBorderColor = uiColor;
cell.Style.BottomBorderColor = uiColor;
}
}
 

Here is the result:

474
Telerik UI for Xamarin

Custom Calendar Renderer


Sometimes, you might find that certain feature is available in the native control on a given platform,
but is not exposed in Xamarin Forms or you might want to customize the calendar look for each
platform. This is when you would need to create a custom renderer. This will allow you to access the
native control and configure it as per your needs.

The native Calendar control documentation can be found here.


 

Example
Let us consider the following example: we need to customize how the calendar looks on UWP.
Create a class which inherits from Telerik.XamarinForms.InputRenderer.UWP.CalendarRenderer
and override the OnElementChanged method:

C#
[assembly: ExportRenderer(typeof(CustomCalendar), typeof(CustomCalendarRenderer))]
namespace
SDKBrowser.UWP.Examples.CalendarControl.StylingCategory.CustomRendererExample
{
public class CustomCalendarRenderer : CalendarRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<RadCalendar>
e)
{
base.OnElementChanged(e);

if (this.Control != null)
{
var content = Window.Current.Content as Frame;
var page = content.Content as Page;
var resources = page.Resources;

this.Control.NormalCellStyle =
new Telerik.UI.Xaml.Controls.Input.CalendarCellStyle()
{
ContentStyle = (Style)resources["NormalCellContentStyle"],
DecorationStyle = (Style)resources["NormalCellDecorationStyle"]
};

this.Control.SelectedCellStyle =
new Telerik.UI.Xaml.Controls.Input.CalendarCellStyle()
{
ContentStyle = (Style)resources["NormalCellContentStyle"],
DecorationStyle = (Style)resources["SelectedCellDecorationStyle"]
};

this.Control.AnotherViewCellStyle =

475
Telerik UI for Xamarin

new Telerik.UI.Xaml.Controls.Input.CalendarCellStyle()
{
ContentStyle = (Style)resources["AnotherViewCellContentStyle"],
DecorationStyle = (Style)resources["AnotherViewCellDecorationStyle"],
};

this.Control.CurrentCellStyle =
new Telerik.UI.Xaml.Controls.Input.CalendarCellStyle()
{
ContentStyle = (Style)resources["NormalCellContentStyle"],
DecorationStyle = (Style)resources["CurrentCellDecorationStyle"],
};

this.Control.HighlightedCellStyle =
new Telerik.UI.Xaml.Controls.Input.CalendarCellStyle()
{
ContentStyle = (Style)resources["HighlightedCellContentStyle"],
DecorationStyle = (Style)resources["HighlightedCellDecorationStyle"],
};

this.Control.DayNameCellStyle =
new Telerik.UI.Xaml.Controls.Input.CalendarCellStyle()
{
ContentStyle = (Style)resources["DayNameCellContentStyle"],
DecorationStyle = (Style)resources["DayNameCellDecorationStyle"],
};
}
}
}
}
 

The styles used in the code snippet above are defined in a XAML resource dictionary merged with
the main page resources of the application:

XAML
<Style x:Key="NormalCellContentStyle" TargetType="TextBlock">
<Setter Property="FontSize" Value="17" />
<Setter Property="FontWeight" Value="Bold" />
<Setter Property="Foreground" Value="Black" />
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>

<Style x:Key="NormalCellDecorationStyle" TargetType="Border" >


<Setter Property="BorderBrush" Value="DarkGray" />
<Setter Property="BorderThickness" Value="4, 3, 2, 1" />
<Setter Property="Background" Value="LightGray" />
<Setter Property="CornerRadius" Value="0" />
</Style>

<Style x:Key="SelectedCellDecorationStyle" TargetType="Border"


BasedOn="{StaticResource ResourceKey=NormalCellDecorationStyle}" >

476
Telerik UI for Xamarin

<Setter Property="BorderBrush" Value="SlateGray" />


<Setter Property="Background" Value="DarkGray" />
</Style>

<Style x:Key="AnotherViewCellContentStyle" TargetType="TextBlock"


BasedOn="{StaticResource ResourceKey=NormalCellContentStyle}" >
<Setter Property="FontWeight" Value="ExtraLight" />
<Setter Property="Foreground" Value="Gray" />
</Style>

<Style x:Key="AnotherViewCellDecorationStyle" TargetType="Border"


BasedOn="{StaticResource ResourceKey=NormalCellDecorationStyle}" >
<Setter Property="BorderBrush" Value="DarkGray" />
</Style>

<Style x:Key="CurrentCellDecorationStyle" TargetType="Border"


BasedOn="{StaticResource ResourceKey=NormalCellDecorationStyle}" >
<Setter Property="BorderBrush" Value="Green" />
<Setter Property="Background" Value="Transparent" />
</Style>

<Style x:Key="HighlightedCellContentStyle" TargetType="TextBlock"


BasedOn="{StaticResource ResourceKey=NormalCellContentStyle}" >
<Setter Property="FontWeight" Value="Black" />
</Style>

<Style x:Key="HighlightedCellDecorationStyle" TargetType="Border"


BasedOn="{StaticResource ResourceKey=NormalCellDecorationStyle}" >
<Setter Property="BorderBrush" Value="Blue" />
</Style>

<Style x:Key="DayNameCellContentStyle" TargetType="TextBlock"


BasedOn="{StaticResource ResourceKey=NormalCellContentStyle}" >
<Setter Property="FontWeight" Value="Bold" />
</Style>

<Style x:Key="DayNameCellDecorationStyle" TargetType="Border"


BasedOn="{StaticResource ResourceKey=NormalCellDecorationStyle}" >
<Setter Property="BorderBrush" Value="Gray" />
</Style>
 

Here is the result:

477
Telerik UI for Xamarin

478
Telerik UI for Xamarin

Commands
The Command design-pattern is very important and widely used in the XAML and MVVM world.
RadCalendar control strictly follows these best practices and provides commands support.

CommandId Enumaration
Calendar control exposes the following commands included in the CommandId enumeration:

 CellTap: A command associated with the Tap event that occurs on tapping a calendar cell.
 AppointmentTap: Occurs when you tap over a specific appointment when in
DayView/MultiDayView mode. It can be used to get all the information regarding the
appointment. This command is associated with the AppointmentTapped event
 TimeSlotTap: Occurs when the end-user taps on a time slot. This command is associated
with the Tap event.

AppointmentTap and TimeSlotTap commands are available for DayView and MultiDayView modes.
 
Command Context
CellTap Cell
AppointmentTap AppointmentTapCommandContext
TimeSlotTap TimeSlotTapCommandContext

Binding CalendarUserCommand
With this approach you could directly handle the needed commands in the ViewModel or page's
code behind.

CellTap Command Example


Here is a sample RadCalendar definition:

XAML
<telerikInput:RadCalendar DisplayDate="2020,03,24">
<telerikInput:RadCalendar.Commands>
<commands:CalendarUserCommand Id="CellTap" Command="{Binding CellTapCommand}"/>
</telerikInput:RadCalendar.Commands>
</telerikInput:RadCalendar>
 

Then add the following namespaces:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF

479
Telerik UI for Xamarin

orms.Input"
xmlns:commands="clr-namespace:Telerik.XamarinForms.Input.Calendar.Commands;assembly=Te
lerik.XamarinForms.Input"
 

How the command is defined in page's code behind:

C#
public partial class CellTap : ContentView
{
public CellTap()
{
InitializeComponent();

this.CellTapCommand = new Command(this.OnCellTapped);


this.BindingContext = this;
}

public ICommand CellTapCommand { get; set; }

private void OnCellTapped(object obj)


{
var args = (CalendarDayCell)obj;
Application.Current.MainPage.DisplayAlert("Cell Tap Command", "You have
selected " + args.Date.ToString("dd/MMMM/yyyy"), "OK");
}
}
 

Sample CellTap Command example can be found in the SDK Browser


application/Examples/Calendar/Commands section.
 

TimeSlotTap Command Example


Sample Calendar definition:

XAML
<telerikInput:RadCalendar ViewMode="Day"
DisplayDate="2020,03,24">
<telerikInput:RadCalendar.Commands>
<commands:CalendarUserCommand Id="TimeSlotTap"
Command="{Binding TimeSlotTapCommand}"/>
</telerikInput:RadCalendar.Commands>
</telerikInput:RadCalendar>
 

Then add the following namespaces:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF

480
Telerik UI for Xamarin

orms.Input"
xmlns:commands="clr-namespace:Telerik.XamarinForms.Input.Calendar.Commands;assembly=Te
lerik.XamarinForms.Input"
 

How the TimeSlotTapCommand is defined in the pade's code behind:

C#
public partial class TimeSlotTap : ContentView
{
public TimeSlotTap()
{
InitializeComponent();

this.TimeSlotTapCommand = new Command(this.OnTimeSlotTapped);


this.BindingContext = this;
}

public ICommand TimeSlotTapCommand { get; set; }

private void OnTimeSlotTapped(object obj)


{
var args = (TimeSlotTapCommandContext)obj;
Application.Current.MainPage.DisplayAlert("TimeSlotTap Command", "Start Time is
" + args.StartTime + " and Endtime is " + args.EndTime, "OK");
}
}
 

The following namespace is needed when TimeSlotTap Command context is used:

C#
using Telerik.XamarinForms.Input.Calendar.Commands;
 

Sample TimeSlotTap Command example can be found in the SDK Browser


application/Examples/Calendar/Commands section.
 

Inheriting from CalendarCommands


this approach allows you to create a class that inherits from the CalendarCommand class.

Let's, for example, handle AppointmentTap action as a Command.

AppointmentTap Command Example


First, create a class that inherits from CalendarCommand and set its Id property accordingly. You
would also need to override CanExecute and Execute methods as demonstrated in the example
below:

481
Telerik UI for Xamarin

C#
public class AppointmentTapUserCommand : CalendarCommand
{
public AppointmentTapUserCommand()
{
Id = CommandId.AppointmentTap;
}

public override bool CanExecute(object parameter)


{
return true;
}

public override void Execute(object parameter)


{
var tappedAppointment = ((AppointmentTapCommandContext)parameter).Appointment;
Application.Current.MainPage.DisplayAlert("AppointmentTap Command", "Info: " +
tappedAppointment.Title, "OK");
}
}
 

Sample RadCalendar definition:

XAML
<telerikInput:RadCalendar x:Name="calendar"
ViewMode="MultiDay"
DisplayDate="2020,03,24"
AppointmentsSource="{Binding Appointments}">
<telerikInput:RadCalendar.BindingContext>
<local:ViewModel/>
</telerikInput:RadCalendar.BindingContext>
</telerikInput:RadCalendar>
 

Add the following namespaces:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
xmlns:commands="clr-namespace:Telerik.XamarinForms.Input.Calendar.Commands;assembly=Te
lerik.XamarinForms.Input"
 

Then add this Command to the Commands collection of the RadCalendar instance:

C#
this.calendar.Commands.Add(new AppointmentTapUserCommand());
 

Create a sample ViewModel with appointments:

482
Telerik UI for Xamarin

C#
public class ViewModel
{
public ViewModel()
{
var date = new DateTime(2020,03,24);
this.Appointments = new ObservableCollection<Appointment>
{
new Appointment {
Title = "Meeting with Tom",
Detail = "Sea Garden",
StartDate = date.AddHours(10),
EndDate = date.AddHours(11),
Color = Color.Tomato
},
new Appointment {
Title = "Lunch with Sara",
Detail = "Restaurant",
StartDate = date.AddHours(12).AddMinutes(30),
EndDate = date.AddHours(14),
Color = Color.DarkTurquoise
},
new Appointment {
Title = "Elle Birthday",
StartDate = date.AddDays(1),
EndDate = date.AddDays(1).AddHours(12),
IsAllDay = true
},
new Appointment {
Title = "Football Game",
StartDate = date.AddDays(2).AddHours(15),
EndDate = date.AddDays(2).AddHours(17),
Color = Color.Green
}
};
}

public ObservableCollection<Appointment> Appointments { get; set; }


}
 

Sample AppointmentTap Command example can be found in the SDK Browser


application/Examples/Calendar/Commands section.
 

See Also
 Events
 Date Properties
 View Modes
 Appointments

483
Telerik UI for Xamarin

Custom Calendar Renderer


Sometimes, you might find that certain feature is available in the native control on a given platform,
but is not exposed in Xamarin Forms. This is when you would need to create a custom renderer.
This will allow you to access the native control and configure it as per your needs.

Examples
You can find Custom Renderer examples at each of the following RadCalendar articles:

 Android
 iOS
 UWP

484
Telerik UI for Xamarin

RadChart Overview
Telerik Chart for Xamarin is a feature-rich, intuitive and easy to use data visualization control which
employs the Xamarin.Forms technology and allows you to build native iOS, Android and Windows
Phone apps in C#. For the Xamarin wrapper lovers, Telerik Chart comes also in the form of
Xamarin.iOS and Xamarin.Android wrappers on top of the native Telerik iOS and Android suites.

While Chart for Xamarin capitalizes all the innate benefits of the native UI, it exposes its objects and
properties in C#, allowing for no-compromise customization and flexibility. Using Telerik Chart along
with the Xamarin.Forms technology allows developers to easily implement various chart scenarios in
their apps from a single shared C# code base.

The intuitive object model and public API allow complex charts to be easily setup either in XAML or
in code-behind. RadChart is completely data aware as the binding mechanism of the control is used
to create the appropriate data points from the raw data. Chart types and series are organized in
hierarchies, depending on the coordinate system, used to plot data points.

Chart Types
RadCartesianChart
As the name hints, the RadCartesianChart control uses the Cartesian coordinate system to plot the
data points in its chart series. The X and Y axes define how each point's coordinates in the plot area
are calculated.

Axes

The following Cartesian axes are available:

485
Telerik UI for Xamarin

 Categorical: Arranges the plotted data points in categories where the key of each category is
the point’s value (if available) for that axis or its index within the points collection. The point’s
coordinate, specified by this axis, is discrete and is calculated depending on the size of the
category slot where the point resides.
 Numerical: Calculates the coordinate of each data point, depending on the actual numerical
value this point provides for the axis. Exposes Minimum and Maximum properties to allow
explicit definition of the range of values visible on this axis. If these properties are not
specified, the axis will automatically calculate the range, depending on the minimum and
maximum data point values.
 Date-Time Continuous: A special axis that expects each data point to provide a
System.DateTime structure as its value for this axis. Think of this axis as a time line where
the coordinate of each data point is calculated depending on the position of its associated
DateTime on the time line. The base unit (or the step) of the axis is calculated depending on
the smallest difference between any two dates.

Series

The following Cartesian series are available:

 Categorical: Categorical series need a Numerical and a Categorical/Date-Time Continuous


axis in order to get properly plotted.
 Bar: Data points are represented by a box where the height (width) of the box is the
distance between the point’s numerical value and the categorical axis that plots the point.
Bars may be either "horizontal" or "vertical" depending on whether the categorical axis is
specified as an "X-axis" or as a "Y-axis".
 Line: Data points are connected with straight line segments.
 Spline: Data points are connected with smooth line segments.
 Area: Data points and the corresponding coordinate axis enclose an area that may be
optionally stroked and/or filled.
 SplineArea: An area, where points are connected with smooth rather than straight
segments.

Each of the above series of the same type may be combined in either stacks or clusters.
Combinations are formed when more than one data point from different series fall within the same
category. The "Cluster" combine mode will position such points next to each other while the "Stack"
combine mode will arrange such points in a stack-like structure. When stacks are formed, the
numerical axis (if present) will consider each stack as a single entity and its sum will be the actual
value used rather than each point’s one.

 Scatter: Scatter series need two Numerical axes in order to get properly plotted. Scatted data
provides both the X and the Y coordinate.
 ScatterPoint: Data points are represented by an arbitrary template.
 ScatterLine: Data points are connected with straight line segments.
 ScatterSpline: Data points are connected with smooth line segments.
 ScatterArea: Data points and the horizontal axis enclose an area that may be optionally
stroked and/or filled.
 ScatterSplineArea: A ScatterArea, where points are connected with smooth rather than
straight segments.

CartesianChartGrid

486
Telerik UI for Xamarin

The Cartesian chart may be optionally decorated with grid-like visuals that support horizontal and
vertical lines, associated with axis ticks and horizontal and vertical stripes – the area between two
adjacent ticks. For more information you can see the CartesianChartGrid section.

PieChart
The RadPieChart control visualizes its data points using a discrete polar coordinate system. Each
point is represented as an arc segment. The arc’s length represents the point’s value percentage of
the total sum.

Behaviors
Optionally, each chart may be enabled with interactivity through its Behaviors property. A behavior is
generally an abstraction that handles user input in a RadChart instance and optionally provides
visual feedback upon some action. The following behaviors are available:

 PanAndZoomBehavior: This behavior handles Manipulation events and/or


MouseMove/MouseWheel to enable panning and zooming of the associated chart plot area.
 TooltipBehavior: This behavior handles Hold and/or MouseMove events to enable
context-sensitive information about a data point. It differs from the TrackballBehavior in terms
of visual information and trigger action.
 SelectionBehavior: This behavior handles the Tap event to enable selection/deselection of
data points and/or chart series. When a data point becomes "Selected", the Chart's
SelectionPalette property is used to visualize the selected point.
 ChartTrackBallBehavior: This behavior handles Hold events to enable context-sensitive
information about a data point.

Annotations
Another feature of RadChart is the ability to show annotations. They are visual elements that can be
used to highlight certain areas on the plot area and denote statistical significance. The provided
types of annotations include:

 CartesianGridLine: In the case of the Cartesian chart, the grid line represents a vertical or
horizontal line which crosses the entire plot area.
 CartesianPlotBand: The Cartesian Plot Band annotation is either a horizontal or a vertical
stripe that crosses entirely the vertical or horizontal axis, respectively.

Palettes
The chart palettes are a set of predefined values that you can use to set colors of a chart.

Labels
Chart can display different labels for the series and axes that are displayed. The labels can be
customized according to your preferences.

487
Telerik UI for Xamarin

Platform-Specific Features
You can customize the control for a specific platform by creating a custom renderer.

488
Telerik UI for Xamarin

Visual Structure
Here are described all visual elements and terms used in a standard RadChart control.

Legend
 PlotArea: The area that contains the data series (on the image it is the area inside the
rectangle defined by the axes).
 Series: The visual representation of the data.
 SeriesLabels: Labels that provide specific information about the data points in the series.
 VerticalAxis/HorizontalAxis: Axes that define the coordinate system used to plot the data.
 Tick: Marks specific values on the axes.
 AxisLabel: Labels for specific values on the axes.
 ChartGrid: Grid lines that mark specific values on the chart area.

489
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadChart control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadChart control
 Populating RadChart with data

1. Setting up the app


Take a look at these articles and follow the instructions to set up your app:

 Set up app with Telerik UI for Xamarin on Windows


 Set up app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to install a
separate nuget package. For RadChart control you have to install the Telerik.UI.for.Xamarin.Chart
nuget package. This nuget will automatically refer the Telerik.UI.for.Xamarin.Common nuget
package.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadChart component:

Platform Assemblies
Portable Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Chart.dll
Android Telerik.Xamarin.Android.Common.dll
Telerik.Xamarin.Android.Chart.dll
Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Chart.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Chart.dll
UWP Telerik.Core.dll

490
Telerik UI for Xamarin

Telerik.UI.Xaml.Chart.UWP.dll
Telerik.UI.Xaml.Primitives.UWP.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Chart.dll

3. Adding RadChart control


You could use one of the following approaches:

Drag the control from the Toolbox.

Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML or C#.

The snippet below shows a simple RadChart definition:

XAML
<telerikChart:RadCartesianChart x:Name="chart">
<telerikChart:RadCartesianChart.BindingContext>
<local:ViewModel />
</telerikChart:RadCartesianChart.BindingContext>
<telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:CategoricalAxis />
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:NumericalAxis />
</telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:RadCartesianChart.Series>
<telerikChart:BarSeries CategoryBinding="Category"
ValueBinding="Value"
ItemsSource="{Binding Data}" />
</telerikChart:RadCartesianChart.Series>
</telerikChart:RadCartesianChart>
 

C#
var chart = new RadCartesianChart
{
HorizontalAxis = new CategoricalAxis(),
VerticalAxis = new NumericalAxis(),
BindingContext = new ViewModel()
};

var series = new BarSeries();

series.SetBinding(ChartSeries.ItemsSourceProperty, new Binding("Data"));

491
Telerik UI for Xamarin

series.ValueBinding = new PropertyNameDataPointBinding { PropertyName = "Value" };


series.CategoryBinding = new PropertyNameDataPointBinding { PropertyName = "Category"
};

chart.Series.Add(series);
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
 

C#
using Telerik.XamarinForms.Chart;
 

4. Populating RadChart with data


Here is how the business model is defined:

C#
public class CategoricalData
{
public object Category { get; set; }

public double Value { get; set; }


}
 

Here is the sample data used as binding context:

C#
public class ViewModel
{
public ViewModel()
{
this.Data = GetCategoricalData();
}

public ObservableCollection<CategoricalData> Data { get; set; }

private static ObservableCollection<CategoricalData> GetCategoricalData()


{
var data = new ObservableCollection<CategoricalData> {
new CategoricalData { Category = "A", Value = 0.63 },
new CategoricalData { Category = "B", Value = 0.85 },
new CategoricalData { Category = "C", Value = 1.05 },
new CategoricalData { Category = "D", Value = 0.96 },

492
Telerik UI for Xamarin

new CategoricalData { Category = "E", Value = 0.78 },


};

return data;
}
}
 

Here is the result:

SDK Browser and QSF applications contain different examples that show RadChart's main features.
You can find the applications in the Examples and QSF folders of your local Telerik UI for Xamarin
installation.
 

See Also
 Cartesian Chart
 Pie Chart
 Chart Legend

493
Telerik UI for Xamarin

RadCartesianChart
This chart visualizes its data points using the Cartesian coordinate system. The X and Y axes define
how the coordinates of each point in the plot area are calculated and the series type defines the way
these data points will be visualized.

Properties
The RadCartesianChart control has the following properties:

 HorizontalAxis (CartesianAxis): Gets or sets the visual Axis instance that will be used to plot
points along the horizontal (X) axis.
 VerticalAxis (CartesianAxis): Gets or sets the visual Axis instance that will be used to plot
points along the vertical (Y) axis.
 Series (ElementsCollection): Gets a collection of all series presented by the chart instance.
 Palette (ChartPalette): Gets or sets the ChartPalette instance that defines the appearance of
the chart.
 PaletteName (PaletteNames): Gets or sets the name of the predefined Palette that will be
applied to the chart.
 SelectionPalette (ChartPalette): Gets or sets the ChartPalette instance that defines the
appearance of the chart for selected series and/or data points.
 SelectionPaletteName (PaletteNames): Gets or sets the name of the predefined
SelectionPalette that will be applied to the chart.
 ChartBehaviors (ObservableCollection): Gets a collection of all enabled behaviors.
 Grid (CartesianChartGrid): Gets or sets the CartesianChartGrid instance used to decorate
the chart plot area with grid and strip lines.
 Annotations (ObservableCollection): Gets a collection of all annotations presented by the
chart instance.
 MaxZoom (Size): Gets or sets the maximum allowed zoom.
 Zoom(Size zoom): Gets or sets the zoom of the chart.
 PanOffset(Point offset): Gets or sets an offset to the chart. Note that the offset will be specific
for every platform depending on the values that the platform works with (absolute pixels or
normed to the axis range) and the axis type.

Supported Axes
RadCartesianChart needs to have two axes which will be used to calculate correctly the position of
each data point. Usually one of the axes will be used to display the category of each data point and
the other will represent its value. Here are the supported axes:

 Categorical: Arranges the plotted data points in categories where the key of each category is
the point's value (if available) for that axis or its index within the points collection. The point's
coordinate, specified by this axis is discrete and is calculated depending on the size of the
category slot where the point resides.
 Numerical: Calculates the coordinate of each data point, depending on the actual numerical
value this point provides for the axis. A NumericalAxis exposes Minimum and Maximum
properties to allow for explicit definition of the range of values visible on this axis. If these

494
Telerik UI for Xamarin

properties are not specified, the axis will automatically calculate the range, depending on the
minimum and maximum data point values.
 Date-Time Continuous: This is a special axis that expects each data point to provide a
DateTime structure as its value for this axis. You can think of DateTimeContinuousAxis as a
timeline where the coordinate of each data point is calculated depending on the position of
its associated DateTime on the timeline. The base unit (or the timeline step) of the axis is
calculated depending on the smallest difference between any two dates.

Supported Series
The following Cartesian series are available:

 Categorical: Categorical series need a Numerical and a Categorical/Date-Time Continuous


axis in order to get properly plotted.
 Bar: Data points are represented by a box where the height (width) of the box is the
distance between the point’s numerical value and the categorical axis that plots the point.
Bars may be either "horizontal" or "vertical" depending on whether the categorical axis is
specified as an "X-axis" or as a "Y-axis".
 Line: Data points are connected with straight line segments.
 Spline: Data points are connected with smooth line segments.
 Area: Data points and the corresponding coordinate axis enclose an area that may be
optionally stroked and/or filled.
 SplineArea: An area, where points are connected with smooth rather than straight
segments.

Each of the above series of the same type may be combined in either stacks or clusters.
Combinations are formed when more than one data point from different series fall within the same
category. The "Cluster" combine mode will position such points next to each other while the "Stack"
combine mode will arrange such points in a stack-like structure. When stacks are formed, the
numerical axis (if present) will consider each stack as a single entity and its sum will be the actual
value used rather than each point’s one.

 Scatter: Scatter series need two Numerical axes in order to get properly plotted. Scatted data
provides both the X and the Y coordinate.
 ScatterPoint: Data points are represented by an arbitrary template.
 ScatterLine: Data points are connected with straight line segments.
 ScatterSpline: Data points are connected with smooth line segments.
 ScatterArea: Data points and the horizontal axis enclose an area that may be optionally
stroked and/or filled.
 ScatterSplineArea: A ScatterArea, where points are connected with smooth rather than
straight segments.
 Financial: Financial series need a Numerical and a Date-Time Continuous/Categorical axis in
order to get properly plotted.
 Ohlc: Each data point is visualized as a line with open and close value indicators on its
side.
 Candlestick: Data points are plotted as visuals that resemble candlesticks.
 Financial Indicators: The financial, or also called stock indicators, are mainly used for
keeping track of stock prices and patterns of price changes over time.

Step by Step Chart Definition

495
Telerik UI for Xamarin

1. Define RadCartesianChart:

XAML" class="hljs"><telerikChart:RadCartesianChart>
</telerikChart:RadCartesianChart>
 

<telerikChart:RadCartesianChart>
</telerikChart:RadCartesianChart>
 

var chart = new RadCartesianChart();


 

2. The RadCartesianChart control needs two axes - horizontal and vertical to plot its data.

XAML" class="hljs"><telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:CategoricalAxis/>
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:NumericalAxis/>
</telerikChart:RadCartesianChart.VerticalAxis>
 

<telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:CategoricalAxis/>
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:NumericalAxis/>
</telerikChart:RadCartesianChart.VerticalAxis>
 

chart.HorizontalAxis = new CategoricalAxis();


chart.VerticalAxis = new NumericalAxis();
 

3. After that you can add the series to the RadCartesianChart.Series collection:

XAML" class="hljs"><telerikChart:RadCartesianChart>
<telerikChart:RadCartesianChart.Series>
<telerikChart:BarSeries ItemsSource="{Binding Data}">
<telerikChart:BarSeries.ValueBinding>
<telerikChart:PropertyNameDataPointBinding PropertyName="Value"/>
</telerikChart:BarSeries.ValueBinding>
<telerikChart:BarSeries.CategoryBinding>
<telerikChart:PropertyNameDataPointBinding
PropertyName="Category"/>
</telerikChart:BarSeries.CategoryBinding>
</telerikChart:BarSeries>
</telerikChart:RadCartesianChart.Series>
</telerikChart:RadCartesianChart>

496
Telerik UI for Xamarin

<telerikChart:RadCartesianChart>
<telerikChart:RadCartesianChart.Series>
<telerikChart:BarSeries ItemsSource="{Binding Data}">
<telerikChart:BarSeries.ValueBinding>
<telerikChart:PropertyNameDataPointBinding PropertyName="Value"/>
</telerikChart:BarSeries.ValueBinding>
<telerikChart:BarSeries.CategoryBinding>
<telerikChart:PropertyNameDataPointBinding PropertyName="Category"/>
</telerikChart:BarSeries.CategoryBinding>
</telerikChart:BarSeries>
</telerikChart:RadCartesianChart.Series>
</telerikChart:RadCartesianChart>
 

var series = new BarSeries();


series.SetBinding(BarSeries.ItemsSourceProperty, new Binding("Data"));
series.ValueBinding = new PropertyNameDataPointBinding("Value");
series.CategoryBinding = new PropertyNameDataPointBinding("Category");
chart.Series.Add(series);
 

4. You also have to set a BindingContext of the chart if none of its parents have a context:

XAML" class="hljs"><telerikChart:RadCartesianChart.BindingContext>
<local:CategoricalDataViewModel/>
</telerikChart:RadCartesianChart.BindingContext>
 

<telerikChart:RadCartesianChart.BindingContext>
<local:CategoricalDataViewModel/>
</telerikChart:RadCartesianChart.BindingContext>
 

chart.BindingContext = new ViewModel();


 

Where local is

XAML
xmlns:local="clr-namespace:[The namespace where the ViewModel class is
defined];assembly=[The assembly name]"
 

5. Use the following business model

C#
public class CategoricalData
{
public object Category { get; set; }

497
Telerik UI for Xamarin

public double Value { get; set; }


}
 

6. And ViewModel:

C#
public class CategoricalDataViewModel
{
public ObservableCollection<CategoricalData> Data { get; set; }

public CategoricalDataViewModel()
{
this.Data = GetCategoricalData();
}

private static ObservableCollection<CategoricalData> GetCategoricalData()


{
var data = new ObservableCollection<CategoricalData>
{
new CategoricalData { Category = "A", Value = 101 },
new CategoricalData { Category = "B", Value = 45 },
new CategoricalData { Category = "C", Value = 77 },
new CategoricalData { Category = "D", Value = 15 },
new CategoricalData { Category = "E", Value = 56 },
};
return data;
}
}
 

Example
First, create the needed business object, for example:

C#
public class CategoricalData
{
public object Category { get; set; }

public double Value { get; set; }


}
 

Then create a ViewModel:

C#
public class CategoricalDataViewModel
{
public ObservableCollection<CategoricalData> Data { get; set; }

498
Telerik UI for Xamarin

public CategoricalDataViewModel()
{
this.Data = GetCategoricalData();
}

private static ObservableCollection<CategoricalData> GetCategoricalData()


{
var data = new ObservableCollection<CategoricalData>
{
new CategoricalData { Category = "A", Value = 101 },
new CategoricalData { Category = "B", Value = 45 },
new CategoricalData { Category = "C", Value = 77 },
new CategoricalData { Category = "D", Value = 15 },
new CategoricalData { Category = "E", Value = 56 },
};
return data;
}
}
 

Finally use the following snippet to declare a RadCartesianChart with Bar Series in XAML and in C#:

XAML
<telerikChart:RadCartesianChart>
<telerikChart:RadCartesianChart.BindingContext>
<local:CategoricalDataViewModel />
</telerikChart:RadCartesianChart.BindingContext>
<telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:CategoricalAxis LabelFitMode="MultiLine" />
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:NumericalAxis LabelFitMode="MultiLine" />
</telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:RadCartesianChart.Series>
<telerikChart:BarSeries ValueBinding="Value"
CategoryBinding="Category"
ItemsSource="{Binding Data}" />
</telerikChart:RadCartesianChart.Series>
</telerikChart:RadCartesianChart>
 

C#
var chart = new RadCartesianChart
{
BindingContext = new CategoricalDataViewModel(),
HorizontalAxis = new CategoricalAxis()
{
LabelFitMode = AxisLabelFitMode.MultiLine,
},
VerticalAxis = new NumericalAxis()
{

499
Telerik UI for Xamarin

LabelFitMode = AxisLabelFitMode.MultiLine,
},
Series =
{
new BarSeries
{
ValueBinding = new PropertyNameDataPointBinding("Value"),
CategoryBinding = new PropertyNameDataPointBinding("Category")
}
}
};

chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "Data");
 

Here is the final result:

SDK Browser application contains various examples with RadCartesianChart control.


 

See Also
 Pie Chart
 Chart Legend
 Chart Null Values

500
Telerik UI for Xamarin

RadPieChart
The RadPieChart visualizes its data points using radial coordinate system. Each data point is
represented as a slice from a pie. The ratio between the space consumed by each slice and the
space consumed by the whole chart is the same as the ratio between the value of the data point that
it represents and the total value of all data points in the series.

Properties
 Series: Gets a collection of all series presented by the chart instance.
 Behaviors: Gets a collection of all enabled behaviors.
 Palette: Gets or sets the ChartPalette instance that defines the appearance of the chart.
 PaletteName: Gets or sets the name of the predefined Palette that will be applied to the
chart.
 SelectionPalette: Gets or sets the ChartPalette instance that defines the appearance of the
chart for selected series and/or data points.
 SelectionPaletteName: Gets or sets the name of the predefined SelectionPalette that will be
applied to the chart.

Supported Series
RadPieChart can visualize the following types of series:

 PieSeries: The PieSeries are used to visualize a single series of data in a pie chart. The
sweep of a pie's slices is directly proportional to the magnitude of the data points' values.

Example
1. Define RadPieChart:

XAML
<telerikChart:RadPieChart>
</telerikChart:RadPieChart>
 

C#
var chart = new RadPieChart();
 

1. After that you can add the series to the RadPieChart.Series collection:

XAML
<telerikChart:RadPieChart.Series>
<telerikChart:PieSeries ItemsSource="{Binding Data}">
<telerikChart:PieSeries.ValueBinding>

501
Telerik UI for Xamarin

<telerikChart:PropertyNameDataPointBinding PropertyName="Value"/>
</telerikChart:PieSeries.ValueBinding>
</telerikChart:PieSeries>
</telerikChart:RadPieChart.Series>
 

C#
var series = new PieSeries();
series.SetBinding(PieSeries.ItemsSourceProperty, new Binding("Data"));
series.ValueBinding = new PropertyNameDataPointBinding("Value");
chart.Series.Add(series);
 

1. You also have to set a BindingContext of the chart if none of its parents have a context:

XAML
<telerikChart:RadPieChart.BindingContext>
<local:ViewModel/>
</telerikChart:RadPieChart.BindingContext>
 

C#
chart.BindingContext = new ViewModel();
 

PieChart Example
Here is the full definition of the chart:

First, create the needed business object, for example:

C#
public class CategoricalData
{
public object Category { get; set; }

public double Value { get; set; }


}
 

Then create a ViewModel:

C#
public class ViewModel
{
public ObservableCollection<CategoricalData> Data { get; set; }

public ViewModel()
{
this.Data = GetCategoricalData();

502
Telerik UI for Xamarin

private static ObservableCollection<CategoricalData> GetCategoricalData()


{
var data = new ObservableCollection<CategoricalData>
{
new CategoricalData { Category = "Greenings", Value = 52 },
new CategoricalData { Category = "Perfecto", Value = 19 },
new CategoricalData { Category = "NearBy", Value = 82 },
new CategoricalData { Category = "Family", Value = 23 },
new CategoricalData { Category = "Fresh", Value = 56 },
};
return data;
}
}
 

Finally use the following snippet to declare a RadPieChart with Pie Series in XAML and in C#:

XAML
<telerikChart:RadPieChart>
<telerikChart:RadPieChart.BindingContext>
<local:ViewModel />
</telerikChart:RadPieChart.BindingContext>
<telerikChart:RadPieChart.Series>
<telerikChart:PieSeries ShowLabels="True"
RadiusFactor="0.8"
ValueBinding="Value"
ItemsSource="{Binding Data}" />
</telerikChart:RadPieChart.Series>
</telerikChart:RadPieChart>
 

C#
var chart = new RadPieChart
{
BindingContext = new ViewModel(),
Series =
{
new PieSeries
{
ShowLabels = true,
RadiusFactor = 0.8,
ValueBinding = new PropertyNameDataPointBinding("Value")
}
}
};

chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "Data");
 

Here is the result:

503
Telerik UI for Xamarin

SDK Browser application contains various examples with RadPieChart control.


 

See Also
 Cartesian Chart
 Chart Legend
 Chart Null Values

504
Telerik UI for Xamarin

Overview
RadCartesianChart plots data points in a coordinate system defined by its two axes. Instead of
having one axis type that does hundreds of things, we have a hierarchy of axes where each
concrete axis type expose particular functionality.

The predefined axis types are:

 NumericalAxis
 CategoricalAxis
 DateTimeAxisContinuous

Common Axis Features


The common axis functionality is encapsulated by the abstract Axis class and is responsible for
displaying ticks that simply mark values on the axis at fixed positions. The axis also displays labels
that are used to provide a visualization of the values at some or all of the ticks. The default
visualization of the labels is text and the default visuals created internally are text blocks. Here is a
list with all the properties exposed by the base axis type.

Label Style and Position


You can customize the labels orientation and style with the following properties:

 LabelFitMode: Specifies how labels that exceed axis bounding rectangle should be
positioned. These are the available fit options:
 MultiLine: Arranges axis labels on multiple lines with each label on a different line than its
neighbor labels.
 Rotate: Arranges the axis labels so that they are rotated some degrees around their top
left corner.
 LabelFontSize: Specifies the font size of the labels.
 LabelTextColor: Specifies the color of the labels.

Example

XAML
<telerikChart:CategoricalAxis LabelFitMode="Rotate"
LabelFontSize="25"

505
Telerik UI for Xamarin

LabelTextColor="#FFCC88CC"/>
 

Label Format
You can customize the labels text with the following properties:

 LabelFormat: Provides a format string that will be used when converting the label value to
string. Each axis type requires different format:
 NumericalAxis: any numeric format like "N", "P2"
 DateTimeContinuousAxis: any date format like "dd-MM-yy", "HH:mm"
 CategoricalAxis: "{0} items", "{0:N}"
 LabelFormatter: Specifies a custom formatter that implements the ILabelFormatter interface
to apply a custom rule for setting each label text.

Example

Here is a quick snippet how you can set LabelFormat to a NumericalAxis:

XAML
<telerikChart:NumericalAxis LabelFormat="C"
MajorStep="0.5"
Minimum="-1"
Maximum="1" />
 

Label Formatter
The LabelFormatterBase class is a base implementation of the ILabelFormatter interface that could
be used in the most common scenarios. Below is an example of a label formatter for
DateTimeContinuousAxis.

Example

C#
public class DateLabelFormatter : LabelFormatterBase<DateTime>
{
public override string FormatTypedValue(DateTime value)
{
if (value.Day == 1)
{
return value.Day + "st";
}
else if (value.Day == 2)
{
return value.Day + "nd";
}
else if (value.Day == 3)
{
return value.Day + "rd";

506
Telerik UI for Xamarin

}
else
{
return value.Day + "th";
}
}
}
 

And you could apply it like this:

XAML
<telerikChart:DateTimeContinuousAxis LabelFitMode="Rotate"
MajorStepUnit="Day">
<telerikChart:DateTimeContinuousAxis.LabelFormatter>
<local:DateLabelFormatter />
</telerikChart:DateTimeContinuousAxis.LabelFormatter>
</telerikChart:DateTimeContinuousAxis>
 

Styling the Axis Line and Ticks


You can customize the appearance of the axis line and ticks with the following properties:

 MajorTickBackgroundColor: Specifies the major ticks color.


 MajorTickThickness: Specifies the thickness of the major ticks.
 LineColor: Specifies the color of the axis line.
 LineDashArray: Specifies the array used to create a dash line that will be applied to the axis
line.

Example

XAML
<telerikChart:NumericalAxis MajorTickBackgroundColor="#FFCC88CC"
MajorTickThickness="5"
LineColor="#FFCC88CC"/>
 

Location
You can specify the location of the axis:

 HorizontalLocation: Specifies the horizontal location of the axis. Applicable for vertical axes.
 VerticalLocation: Specifies the vertical location of the axis. Applicable for horizontal axes.

Example

XAML
<telerikChart:CategoricalAxis VerticalLocation="Top"/>

507
Telerik UI for Xamarin

See Also
 Categorical Axis
 Numerical Axis
 DateTimeContinuous Axis

508
Telerik UI for Xamarin

CategoricalAxis
Overview
When RadCartesianChart visualizes CategoricalSeries, it needs an axis that can represent the
different categories. Categories are built depending on the CategoryBinding value of each
categorical data point in the owning CategoricalSeries. The axis is divided into discrete slots and
each data point is visualized in the slot corresponding to its categorical value.

The CategoricalAxis inherits from the base Axis class. You can see the inherited properties here.

Features
 GapLength: Defines the distance (in logical units [0,1]) between two adjacent categories.
Default value is 0.3. For example if you have BarSeries, you can decrease the space
between the bars from the different categories by setting the GapLength to a value lower
than 0.3.
 MajorTickInterval: Defines the step at which major ticks are generated. The default value is
1. This property will also affect axis labels as they are generated on a per major tick basis.
 PlotMode: Defines the strategy used to position data points along the axis category slots.
The possible values are:
 BetweenTicks
 OnTicks
 MajorTickBackgroundColor: Specifies the major ticks color.
 MajorTickThickness: Specifies the thickness of the major ticks

Example
Here is an example how to format axis labes on Categorical Axis:

First, create the needed business objects:

C#
public class CategoricalData
{
public object Category { get; set; }

public double Value { get; set; }


}
 

Then create a ViewModel:

C#
public class CategoricalDataViewModel
{

509
Telerik UI for Xamarin

public ObservableCollection<CategoricalData> Data { get; set; }

public CategoricalDataViewModel()
{
this.Data = GetCategoricalData();
}

private static ObservableCollection<CategoricalData> GetCategoricalData()


{
var data = new ObservableCollection<CategoricalData>
{
new CategoricalData { Category = "A", Value = 101 },
new CategoricalData { Category = "B", Value = 45 },
new CategoricalData { Category = "C", Value = 77 },
new CategoricalData { Category = "D", Value = 15 },
new CategoricalData { Category = "E", Value = 56 },
};
return data;
}
}
 

Finally, use the following snippet to declare the RadChart in XAML or in C#:

XAML
<telerikChart:RadCartesianChart>
<telerikChart:RadCartesianChart.BindingContext>
<local:CategoricalDataViewModel/>
</telerikChart:RadCartesianChart.BindingContext>
<telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:CategoricalAxis PlotMode="OnTicks"
MajorTickInterval="2"
GapLength="0.5"/>
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:NumericalAxis LabelFitMode="MultiLine"/>
</telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:RadCartesianChart.Series>
<telerikChart:BarSeries ItemsSource="{Binding Data}"
ValueBinding="Value"
CategoryBinding="Category"/>
</telerikChart:RadCartesianChart.Series>
</telerikChart:RadCartesianChart>
 

C#
var chart = new RadCartesianChart
{
BindingContext = new ViewModel2(),
HorizontalAxis = new CategoricalAxis()
{
PlotMode = AxisPlotMode.OnTicks,

510
Telerik UI for Xamarin

MajorTickInterval = 2,
GapLength = 0.5
},
VerticalAxis = new NumericalAxis()
{
LabelFitMode = AxisLabelFitMode.MultiLine,
},
Series =
{
new BarSeries
{
ValueBinding = new PropertyNameDataPointBinding("Value"),
CategoryBinding = new PropertyNameDataPointBinding("Category")
}
}
};

chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "Data");
 

Here is how the Categorical Axis Format looks:

See Also
 Axis Overview
 Numerical Axis
 DateTimeContinuous Axis

511
Telerik UI for Xamarin

DateTimeContinuousAxis
Overview
The DateTimeContinuousAxis is a special axis that extends the base CartesianAxis class and may
be considered as a hybrid between a categorical and a numerical axis. DateTimeContinuousAxis
works with categorical data but instead of categories, the axis builds time slots depending on its
Minimum, Maximum and MajorStep values.DateTimeContinuousAxis also expects valid DateTime
values so that the data could be plotted correctly. Think of DateTimeContinuousAxis as a timeline
where each data point has a certain position, depending on its DateTime value. The timeline range
properties are automatically calculated if not set explicitly by the user: the default value of the major
step is the smallest difference between any two DateTime values. There might be empty time slots if
no data falling into them is found, because the axis behaves like a numerical one.

The CategoricalAxis inherits from the base Axis class. You can see the inherited properties here.

Features
 Minimum: Defines the start value of the timeline. Specify DateTime.Minimum to clear the
value and force the axis to determine it automatically, depending on the smallest DateTime
value present.
 Maximum: Defines the end value of the timeline. Specify DateTime.Maximum to clear the
value and force the axis to determine it automatically, depending on the biggest DateTime
value present.
 PlotMode: Defines the strategy used to position data points along the axis time slots. Two
different options are available: { BetweenTicks, OnTicks }.
 MajorStep: Defines the user-defined step between two adjacent time slots. Specify
double.PositiveInfinity to clear the value and make the axis calculate an automatic step,
depending on the smallest difference between any two dates.
 MajorStepUnit: Defines what DateTime component the MajorStep property refers to { Year,
Quarter, Month, Week, Day, Hour, Minute, Second, Millisecond }.
 GapLength: Defines the distance (in logical units [0,1]) between two adjacent time slots. The
default value is 0.3. As an example, if you have two BarSeries combined in Cluster mode,
you can remove the space between the bars by setting the GapLength property to 0.

Example
Here is an example how to format axis labes on DateTimeContinuous Axis:

First, create the needed business objects:

C#
public class TemporalData
{
public DateTime Date { get; set; }

public double Value { get; set; }

512
Telerik UI for Xamarin

}
 

Then create a ViewModel:

C#
public class ViewModel
{
public ObservableCollection<TemporalData> Data { get; set; }

public ViewModel()
{
this.Data = GetDateTimeData(6);
}

private static ObservableCollection<TemporalData> GetDateTimeData(int itemsCount)


{
var startDate = new DateTime(2015, 03, 01);

ObservableCollection<TemporalData> items = new


ObservableCollection<TemporalData>();
for (int i = 0; i < itemsCount; i++)
{
TemporalData data = new TemporalData();
data.Date = startDate.AddDays(i);
data.Value = Math.Sin(i);

items.Add(data);
}

return items;
}
}
 

Create a class, for example DateLabelFormatter that inherits from LabelFormatterBase for
DateTimeContinuous Axis

C#
public class DateLabelFormatter : LabelFormatterBase<DateTime>
{
public override string FormatTypedValue(DateTime value)
{
if (value.Day == 1)
{
return value.Day + "st";
}
else if (value.Day == 2)
{
return value.Day + "nd";
}
else if (value.Day == 3)

513
Telerik UI for Xamarin

{
return value.Day + "rd";
}
else
{
return value.Day + "th";
}
}
}
 

Finally, use the following snippet to declare the RadChart in XAML or in C#:

C#
var chart = new RadCartesianChart
{
BindingContext = new ViewModel(),
VerticalAxis = new NumericalAxis
{
LabelFormat = "C",
MajorStep = 0.5,
Minimum = -1,
Maximum = 1
},
HorizontalAxis = new DateTimeContinuousAxis
{
LabelFormatter = new DateLabelFormatter(),
LabelFitMode = AxisLabelFitMode.Rotate,
MajorStepUnit = TimeInterval.Day,
},
Series =
{
new LineSeries
{
ValueBinding = new PropertyNameDataPointBinding("Value"),
CategoryBinding = new PropertyNameDataPointBinding("Date")
}
}
};

chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "Data");
 

Here is how the DateTimeContinuous Axis Formatter looks:

514
Telerik UI for Xamarin

A sample Format Axis Label example can be found in the Chart/Customization folder of the SDK
Samples Browser application.
 

See Also
 Categorical Axis
 Numerical Axis
 Axis Overview

515
Telerik UI for Xamarin

NumericalAxis
Overview
The NumericalAxis plots the associated data points using each point's numerical value, provided for
the axis. It will build a numerical range (user-defined or automatically calculated) and will determine
each data point X or Y coordinate (depending on whether the axis is specified as Horizontal or as
Vertical).

The axis works with either categorical or scatter data. For categorical data the axis uses the
ValueBinding property of the data points, while for scatter data the axis uses the XValueBinding or
the YValueBinding property depending on whether the axis is horizontal or vertical.

The NumericalAxis inherits from the base Axis class. You can see the inherited properties here.

Features
 LabelFormat: Provides a format string that will be used when converting the label value to
string. For example any numeric format like "N", "P2".
 Minimum: Defines the minimum value of the axis. By default, the axis itself will calculate the
minimum, depending on the minimum value of the plotted data points.
 Maximum: Defines the maximum value of the axis. By default, the axis itself will calculate the
maximum, depending on the maximum value of the plotted data points.
 RangeExtendDirection: Defines a value that specifies how the actual range of the axis (when
auto-calculated) should be extended. By default the axis will calculate its minimum and
maximum in such a way that the data is best visualized. For example, if the maximum data
point value is 50, the axis will make its Maximum 50 + MajorStep, so that the plotted data will
not intersect with the top of the plot area. The available values are:
 None
 Positive
 Negative
 Both
 MajorStep: Specifies the step at which the major ticks are positioned on the axis. If this
property is set to 0, the axis automatically calculate the step so that the data will be
visualized in the best possible way.

Example
XAML
<telerikChart:NumericalAxis LabelFormat="C"
MajorStep="0.5"
Minimum="-1"
Maximum="1" />
 

A sample Format Axis Label example can be found in the Chart/Customization folder of the SDK

516
Telerik UI for Xamarin

Samples Browser application.


 

See Also
 Axis Overview
 Categorical Axis
 DateTimeContinuous Axis

517
Telerik UI for Xamarin

Overview
The data visualization in RadChart is done by a hierarchy of classes that inherit from the ChartSeries
class. Each series has a collection of data points, that is the view model of the data. A series may
have its data populated by data-binding to an arbitrary IEnumerable instance through the
ItemsSource property.

Series Class Hierarchy


Concrete series types are available for specific charts. For example, there is a set of CartesianSeries
applicable in the context of a RadCartesianChart. Here is the hierarchy of all series:

Here are listed all supported series grouped by the chart types that can use them:

CartesianChart

 CategoricalSeries
 Bar Series
 Line Series
 Spline Series
 Area Series
 SplineArea Series
 ScatterSeries
 ScatterPoint Series
 ScatterLine Series
 ScatterSpline Series
 ScatterArea Series

518
Telerik UI for Xamarin

 ScatterSplineArea Series

PieChart

 Pie Series
 Donut Series

Financial Chart

 Ohlc Series
 Candlestick Series
 Financial Series

See Also
 Annotations
 Chart Legend
 Null Values

519
Telerik UI for Xamarin

Common Features
 ItemsSource(IList): Defines the data set that will fill the series data points.
 DisplayName(string): The display name of the series.

Selection
 AllowSelect(bool): Specifies whether the series is selectable. If the property value is true,
the selection is handled by the chart selection behavior.
 IsSelected(bool): Specifies whether the series is selected.

Labels customization
RadChart provides the option to display data point labels in the plot area through the ShowLabels
property of the ChartSeries.

You could customize the series labels text using the properties below:

 ShowLabels(bool): Defines whether the series will display labels for each plotted data point.
 LabelBinding(PropertyNameDataPointBinding): Allows the user to bind the series labels to a
property of the data point item.
 LabelFormat(string): Sets label format string such as "N", "P2".
 LabelFormatter(ILabelFormatter): Allows custom series label formatting.

Example
Here is a quick example how you could apply LabelFormat to a LineSeries:

First, create the needed business objects, for example:

C#
public class TemporalData
{
public DateTime Date { get; set; }

public double Value { get; set; }


}
 

Then create a ViewModel:

C#
public class ViewModel
{
public ObservableCollection<TemporalData> Data { get; set; }

520
Telerik UI for Xamarin

public ViewModel()
{
this.Data = GetDateTimeData(6);
}

private static ObservableCollection<TemporalData> GetDateTimeData(int itemsCount)


{
var startDate = new DateTime(2018, 03, 01);

ObservableCollection<TemporalData> items = new


ObservableCollection<TemporalData>();
for (int i = 0; i < itemsCount; i++)
{
TemporalData data = new TemporalData();
data.Date = startDate.AddDays(i);
data.Value = Math.Sin(i);

items.Add(data);
}

return items;
}
}
 

Finally, use the following snippet to declare a RadCartesianChart with Line Series in XAML and in
C#:

XAML
<telerikChart:RadCartesianChart x:Name="chart">
<telerikChart:RadCartesianChart.BindingContext>
<local:ViewModel />
</telerikChart:RadCartesianChart.BindingContext>
<telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:DateTimeContinuousAxis LabelFitMode="Rotate"
MajorStepUnit="Day" />
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:NumericalAxis Minimum="-1.5"
Maximum="1.5" />
</telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:RadCartesianChart.Series>
<telerikChart:LineSeries ValueBinding="Value"
CategoryBinding="Date"
ItemsSource="{Binding Data}"
ShowLabels="True"
LabelFormat="{}{0:N2}"
/>
</telerikChart:RadCartesianChart.Series>
 

C#
var chart = new RadCartesianChart

521
Telerik UI for Xamarin

{
BindingContext = new ViewModel(),
VerticalAxis = new NumericalAxis
{
Minimum = -1.5,
Maximum = 1.5
},
HorizontalAxis = new DateTimeContinuousAxis
{
LabelFitMode = AxisLabelFitMode.Rotate,
MajorStepUnit = TimeInterval.Day,
},
Series =
{
new LineSeries
{
ValueBinding = new PropertyNameDataPointBinding("Value"),
CategoryBinding = new PropertyNameDataPointBinding("Date"),
ShowLabels = true,
LabelFormat = "{0:N2}"
}
}
};

chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "Data");
 

And the result is:

You can find detailed information about the supported numeric formats here: Standard Numeric

522
Telerik UI for Xamarin

Format Strings.
 

Categorical Series Features


Data Binding
All categorical series have CategoryBinding and ValueBinding properties. These properties are of
PropertyNameDataPointBinding and specify the name of the property from the data model used by
the chart to plot the corresponding visual points.

Combining
The categorical series could be combined. Several combining strategies are supported. You can
take a look at the Grouping example.

Scatter Series Common Features


Data Binding
Scatter series provide XValueBinding and YValueBinding properties for data binding to a view
model. These properties are of PropertyNameDataPointBinding and specify the name of the property
from the data model used by the chart to plot the corresponding visual points.

See Also
 Annotations
 Chart Legend
 Null Values

523
Telerik UI for Xamarin

Area Series
Overview
RadCartesianChart visualizes AreaSeries as an area on the chart that is enclosed by the coordinate
axes and straight line segments that connect the data points represented by these series. The
AreaSeries extend CategoricalStrokedSeries, so they are also CategoricalSeries and require one
CategoricalAxis and one NumricalAxis.

Features
 Fill : Defines the fill of the AreaSeries.
 Stroke : Changes the color used to draw lines.
 StrokeThickness : Changes the width of the lines.

Example
Here is an example how to create RadCartesianChart with Area Series:

First, create the needed business objects, for example:

C#
public class CategoricalData
{
public object Category { get; set; }

public double Value { get; set; }


}
 

Then create a ViewModel:

C#
public class CategoricalViewModel
{
public ObservableCollection<CategoricalData> Data { get; set; }

public CategoricalViewModel()
{
this.Data = GetCategoricalData();
}

private static ObservableCollection<CategoricalData> GetCategoricalData()


{
var data = new ObservableCollection<CategoricalData>
{

524
Telerik UI for Xamarin

new CategoricalData { Category = "Greenings", Value = 52 },


new CategoricalData { Category = "Perfecto", Value = 19 },
new CategoricalData { Category = "NearBy", Value = 82 },
new CategoricalData { Category = "Family", Value = 23 },
new CategoricalData { Category = "Fresh", Value = 56 },
};
return data;
}
}
 

Finally, use the following snippet to declare a RadCartesianChart with Area Series in XAML and in
C#:

XAML
<telerikChart:RadCartesianChart>
<telerikChart:RadCartesianChart.BindingContext>
<local:CategoricalViewModel />
</telerikChart:RadCartesianChart.BindingContext>
<telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:CategoricalAxis LabelFitMode="MultiLine"
PlotMode="OnTicks" />
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:NumericalAxis />
</telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:RadCartesianChart.Series>
<telerikChart:AreaSeries ValueBinding="Value"
CategoryBinding="Category"
ItemsSource="{Binding Data}" />
</telerikChart:RadCartesianChart.Series>
</telerikChart:RadCartesianChart>
 

C#
var chart = new RadCartesianChart
{
BindingContext = new CategoricalViewModel(),
HorizontalAxis = new CategoricalAxis()
{
LabelFitMode = AxisLabelFitMode.MultiLine,
PlotMode = AxisPlotMode.OnTicks
},
VerticalAxis = new NumericalAxis(),
Series =
{
new AreaSeries
{
ValueBinding = new PropertyNameDataPointBinding("Value"),
CategoryBinding = new PropertyNameDataPointBinding("Category")
}
}

525
Telerik UI for Xamarin

};

chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "Data");
 

Where the telerikChart namespace is the following:

XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
 

C#
using Telerik.XamarinForms.Chart;
 

Here is the result:

Customization Example
Here we have some customizations:

C#
var series = new AreaSeries
{
Fill = new Color(0.8, 0.8, 1),
Stroke = new Color(0.6, 0.6, 0.9),

526
Telerik UI for Xamarin

StrokeThickness = 5
};
 

This is the final result:

A sample Ares Series example can be found in the Chart/Series folder of the SDK Samples Browser
application.
 

See Also
 Bar Series
 Line Series
 Spline Series

527
Telerik UI for Xamarin

Bar Series
Overview
RadCartesianChart visualizes each data point from the BarSeries as a rectangle. These rectangles
(or bars) can be displayed either horizontally, or vertically, depending on whether the
CategoricalAxis is the vertical axis or the horizontal. When the horizontal axis is categorical, the
rectangles are displayed vertically. This means that they have equal width while their height
represents the numerical value of each of the data points. On the other hand, when the vertical axis
is categorical, the rectangles have equal height, while their width represents the value of the data
point.

The BarSeries inherits from CategoricalSeries and requires one CategoricalAxis and one
NumericalAxis.

You could check the common CategoricalSeries features that are also applicable to BarSeries at the
following link: Series Features.
 

Example
Here is an example how to create RadCartesianChart with Bar Series:

First, create the needed business objects, for example:

C#
public class CategoricalData
{
public object Category { get; set; }

public double Value { get; set; }


}
 

Then create a ViewModel:

C#
public class CategoricalDataViewModel
{
public ObservableCollection<CategoricalData> Data { get; set; }

public CategoricalDataViewModel()
{
this.Data = GetCategoricalData();
}

private static ObservableCollection<CategoricalData> GetCategoricalData()

528
Telerik UI for Xamarin

{
var data = new ObservableCollection<CategoricalData>
{
new CategoricalData { Category = "A", Value = 101 },
new CategoricalData { Category = "B", Value = 45 },
new CategoricalData { Category = "C", Value = 77 },
new CategoricalData { Category = "D", Value = 15 },
new CategoricalData { Category = "E", Value = 56 },
};
return data;
}
}
 

Finally, use the following snippet to declare a RadCartesianChart with Bar Series in XAML and in
C#:

XAML
<telerikChart:RadCartesianChart>
<telerikChart:RadCartesianChart.BindingContext>
<local:CategoricalDataViewModel />
</telerikChart:RadCartesianChart.BindingContext>
<telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:CategoricalAxis LabelFitMode="MultiLine" />
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:NumericalAxis LabelFitMode="MultiLine" />
</telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:RadCartesianChart.Series>
<telerikChart:BarSeries ValueBinding="Value"
CategoryBinding="Category"
ItemsSource="{Binding Data}" />
</telerikChart:RadCartesianChart.Series>
</telerikChart:RadCartesianChart>
 

C#
var chart = new RadCartesianChart
{
BindingContext = new CategoricalDataViewModel(),
HorizontalAxis = new CategoricalAxis()
{
LabelFitMode = AxisLabelFitMode.MultiLine,
},
VerticalAxis = new NumericalAxis()
{
LabelFitMode = AxisLabelFitMode.MultiLine,
},
Series =
{
new BarSeries
{

529
Telerik UI for Xamarin

ValueBinding = new PropertyNameDataPointBinding("Value"),


CategoryBinding = new PropertyNameDataPointBinding("Category")
}
}
};

chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "Data");
 

Where the telerikChart namespace is the following:

XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
 

C#
using Telerik.XamarinForms.Chart;
 

Here is how it looks:

A sample Bar Series example can be found in the Chart/Series folder of the SDK Samples Browser
application.
 

BarSeries Palette Mode

530
Telerik UI for Xamarin

The Palette Mode property of the BarSeries allows users to change the color of the series using
SeriesPaletteMode enumeration. The changes of the color can be set on:

 Series: The palette is applied to data point depending on the index of the owning ChartSeries
instance.
 DataPoint: You can apply the palette to the data points depending on the index od each data
point.

The fill of the BarSeries can be defined using the FillColor property.

PaletteMode Example
Here is an example that demonstrates how you can set the PaletteMode property on Series and
DataPoint:

XAML
<telerikChart:RadCartesianChart>
<telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:CategoricalAxis />
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:NumericalAxis />
</telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:RadCartesianChart.Series>
<telerikChart:BarSeries CategoryBinding="Category"
ValueBinding="Value"
ItemsSource="{Binding Data}"
PaletteMode="{Binding SelectedMode}" />
</telerikChart:RadCartesianChart.Series>
<telerikChart:RadCartesianChart.Palette>
<telerikChart:ChartPalette>
<telerikChart:ChartPalette.Entries>
<telerikChart:PaletteEntry FillColor="Green" />
<telerikChart:PaletteEntry FillColor="HotPink" />
<telerikChart:PaletteEntry FillColor="Red" />
<telerikChart:PaletteEntry FillColor="Yellow" />
<telerikChart:PaletteEntry FillColor="Orange" />
</telerikChart:ChartPalette.Entries>
</telerikChart:ChartPalette>
</telerikChart:RadCartesianChart.Palette>
</telerikChart:RadCartesianChart>
 

C#
var chart = new RadCartesianChart
{
HorizontalAxis = new CategoricalAxis(),
VerticalAxis = new NumericalAxis(),
Series =
{
new BarSeries

531
Telerik UI for Xamarin

{
ValueBinding = new PropertyNameDataPointBinding("Value"),
CategoryBinding = new PropertyNameDataPointBinding("Category")
}
},
Palette = new ChartPalette
{
Entries =
{
new PaletteEntry(Color.Green),
new PaletteEntry(Color.HotPink),
new PaletteEntry(Color.Red),
new PaletteEntry(Color.Yellow),
new PaletteEntry(Color.Orange)
}
}
};

chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "Data");
chart.Series[0].SetBinding(BarSeries.PaletteModeProperty, "SelectedMode");
 

PaletteMode for Series

PaletteMode for DataPoint

532
Telerik UI for Xamarin

SDK Browser application contains an example that shows Palette Mode feature for BarSeries in
RadChart cotrol. You can find the application in the Examples folder of your local Telerik UI for
Xamarin installation.
 

See Also
 Categorical Series Overview
 Categorical Series Orientation
 Cartegorical Series Combine Mode

533
Telerik UI for Xamarin

Line Series
Overview
RadCartesianChart visualizes each data item from the LineSeries and connects them with straight
line segments. The LineSeries extend CategoricalStrokedSeries, so they are also CategoricalSeries
and require one CategoricalAxis and one NumricalAxis.

Features
 Stroke (Color): changes the color used to draw lines.
 StrokeThickness (double): changes the width of the lines.

Example
Here is an example how to create RadCartesianChartChart with Line Series:

First, create the needed business objects, for example:

C#
public class CategoricalData
{
public object Category { get; set; }

public double Value { get; set; }


}
 

Then create a ViewModel:

C#
public class SeriesCategoricalViewModel
{
public ObservableCollection<CategoricalData> Data1 { get; set; }
public ObservableCollection<CategoricalData> Data2 { get; set; }

public SeriesCategoricalViewModel()
{
this.Data1 = GetCategoricalData1();
this.Data2 = GetCategoricalData2();
}

private static ObservableCollection<CategoricalData> GetCategoricalData1()


{
var data = new ObservableCollection<CategoricalData>
{

534
Telerik UI for Xamarin

new CategoricalData { Category = "Greenings", Value = 52 },


new CategoricalData { Category = "Perfecto", Value = 19 },
new CategoricalData { Category = "NearBy", Value = 82 },
new CategoricalData { Category = "Family", Value = 23 },
new CategoricalData { Category = "Fresh", Value = 56 },
};
return data;
}

private static ObservableCollection<CategoricalData> GetCategoricalData2()


{
var data = new ObservableCollection<CategoricalData>
{
new CategoricalData { Category = "Greenings", Value = 33 },
new CategoricalData { Category = "Perfecto", Value = 51 },
new CategoricalData { Category = "NearBy", Value = 11 },
new CategoricalData { Category = "Family", Value = 94 },
new CategoricalData { Category = "Fresh", Value = 12 },
};
return data;
}
}
 

Finally, use the following snippet to declare a RadCartesianChart with Line Series in XAML and in
C#:

XAML
<telerikChart:RadCartesianChart>
<telerikChart:RadCartesianChart.BindingContext>
<local:SeriesCategoricalViewModel />
</telerikChart:RadCartesianChart.BindingContext>
<telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:CategoricalAxis LabelFitMode="MultiLine"
PlotMode="OnTicks" />
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:NumericalAxis />
</telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:RadCartesianChart.Series>
<telerikChart:LineSeries ValueBinding="Value"
CategoryBinding="Category"
ItemsSource="{Binding Data1}" />
<telerikChart:LineSeries ValueBinding="Value"
CategoryBinding="Category"
ItemsSource="{Binding Data2}" />
</telerikChart:RadCartesianChart.Series>
</telerikChart:RadCartesianChart>
 

C#
var chart = new RadCartesianChart

535
Telerik UI for Xamarin

{
BindingContext = new SeriesCategoricalViewModel(),
HorizontalAxis = new CategoricalAxis()
{
LabelFitMode = AxisLabelFitMode.MultiLine,
PlotMode = AxisPlotMode.OnTicks
},
VerticalAxis = new NumericalAxis(),
Series =
{
new LineSeries
{
ValueBinding = new PropertyNameDataPointBinding("Value"),
CategoryBinding = new PropertyNameDataPointBinding("Category")
},
new LineSeries
{
ValueBinding = new PropertyNameDataPointBinding("Value"),
CategoryBinding = new PropertyNameDataPointBinding("Category")
}
}
};

chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "Data1");
chart.Series[1].SetBinding(ChartSeries.ItemsSourceProperty, "Data2");
 

Where the telerikChart namespace is the following:

XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
 

C#
using Telerik.XamarinForms.Chart;
 

And here is the result:

536
Telerik UI for Xamarin

A sample Line Series example can be found in the Chart/Series folder of the SDK Samples Browser
application.
 

Customization Example
Here we make some customizations:

C#
var series = new LineSeries
{
Stroke = new Color(0.6, 0.6, 0.9),
StrokeThickness = 5
};
 

537
Telerik UI for Xamarin

See Also
 ScatterArea Series
 ScatterLine Series
 ScatterPoint Series

538
Telerik UI for Xamarin

ScatterAreaSeries
Overview
RadCartesianChart visualizes ScatterAreaSeries as the area enclosed by the coordinate axes and
straight line segments that connect the series data points. The ScatterAreaSeries inherit from the
ScatterPointSeries class and also require both axes of the chart to be of type NumericalAxis.

Features
ScatterAreaSeries provides the following properties to change its style:

 Stroke (Color): Changes the color used to draw lines.


 StrokeThickness (double): Changes the width of the lines.
 Fill (Color): Changes the color of the chart area.

Example
Here is an example how to create RadCartesianChart with ScatterArea Series:

First, create the needed business objects, for example:

C#
public class NumericalData
{
public double XData { get; set; }
public double YData { get; set; }
}
 

Then create a ViewModel:

C#
public class NumericalViewModel
{
public ObservableCollection<NumericalData> Data { get; set; }

public NumericalViewModel()
{
this.Data = GetNumericData();
}

public static ObservableCollection<NumericalData> GetNumericData()


{
var data = new ObservableCollection<NumericalData>
{

539
Telerik UI for Xamarin

new NumericalData { XData = 4, YData = 9 },


new NumericalData { XData = 8, YData = 10 },
new NumericalData { XData = 9, YData = 13 },
new NumericalData { XData = 12, YData = 24 },
new NumericalData { XData = 17, YData = 24 },
new NumericalData { XData = 21, YData = 4 },
new NumericalData { XData = 26, YData = 13 },
new NumericalData { XData = 29, YData = 3 },
new NumericalData { XData = 30, YData = 16 },
};
return data;
}
}
 

Finally, use the following snippet to declare a RadCartesianChart with ScatterArea Series in XAML
and in C#:

XAML
<telerikChart:RadCartesianChart>
<telerikChart:RadCartesianChart.BindingContext>
<local:NumericalViewModel />
</telerikChart:RadCartesianChart.BindingContext>
<telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:NumericalAxis LabelFitMode="MultiLine" />
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:NumericalAxis />
</telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:RadCartesianChart.Series>
<telerikChart:ScatterAreaSeries XValueBinding="XData"
YValueBinding="YData"
ItemsSource="{Binding Data}" />
</telerikChart:RadCartesianChart.Series>
</telerikChart:RadCartesianChart>
 

C#
var chart = new RadCartesianChart
{
BindingContext = new NumericalViewModel(),
HorizontalAxis = new NumericalAxis()
{
LabelFitMode = AxisLabelFitMode.MultiLine
},
VerticalAxis = new NumericalAxis(),
Series =
{
new ScatterAreaSeries
{
XValueBinding = new PropertyNameDataPointBinding("XData"),
YValueBinding = new PropertyNameDataPointBinding("YData")

540
Telerik UI for Xamarin

}
}
};

chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "Data");
 

Where the telerikChart namespace is the following:

XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
 

C#
using Telerik.XamarinForms.Chart;
 

And here is the result:

A sample ScatterArea Series example can be found in the Chart/Series folder of the SDK Samples
Browser application.
 

Customization Example
Here we make some customization:

541
Telerik UI for Xamarin

C#
var series = new ScatterAreaSeries
{
Stroke = new Color(0.6, 0.6, 0.9),
StrokeThickness = 5,
Fill = new Color(0.8, 0.8, 1)
};
 

See Also
 Line Series
 ScatterLine Series
 ScatterPoint Series

542
Telerik UI for Xamarin

ScatterLine Series
Overview
The ScatterLineSeries are represented on the chart as data points connected with straight line
segments. The ScatterLineSeries inherit from the ScatterPointSeries class and also require both axes
of the chart to be of type NumericalAxis.

Features
ScatterLineSeries provide the following properties to change their style:

 Stroke (Color): changes the color used to draw lines.


 StrokeThickness (double): changes the width of the lines.

If you want to style the series, on iOS both Stroke and StrokeThickness must be set
 

Example
Here is an example how to create RadCartesianChart with ScatterLine Series:

First, create the needed business objects, for example:

C#
public class NumericalData
{
public double XData { get; set; }
public double YData { get; set; }
}
 

Then create a ViewModel:

C#
public class SeriesNumericalViewModel
{
public ObservableCollection<NumericalData> Data1 { get; set; }
public ObservableCollection<NumericalData> Data2 { get; set; }

public SeriesNumericalViewModel()
{
this.Data1 = GetNumericData1();
this.Data2 = GetNumericData2();
}

543
Telerik UI for Xamarin

public static ObservableCollection<NumericalData> GetNumericData1()


{
var data = new ObservableCollection<NumericalData>
{
new NumericalData { XData = 2, YData = 13 },
new NumericalData { XData = 19, YData = 31 },
new NumericalData { XData = 22, YData = 33 },
new NumericalData { XData = 28, YData = 35 },
new NumericalData { XData = 33, YData = 46 },
new NumericalData { XData = 38, YData = 34 },
new NumericalData { XData = 49, YData = 66 },
new NumericalData { XData = 55, YData = 24 },
new NumericalData { XData = 62, YData = 41 },
};
return data;
}
public static ObservableCollection<NumericalData> GetNumericData2()
{
var data = new ObservableCollection<NumericalData>
{
new NumericalData { XData = 7, YData = 13 },
new NumericalData { XData = 19, YData = 17 },
new NumericalData { XData = 22, YData = 19 },
new NumericalData { XData = 28, YData = 21 },
new NumericalData { XData = 33, YData = 35 },
new NumericalData { XData = 38, YData = 43 },
new NumericalData { XData = 49, YData = 15 },
new NumericalData { XData = 55, YData = 21 },
new NumericalData { XData = 62, YData = 47 },
};
return data;
}
}
 

Finally, use the following snippet to declare a RadCartesianChart with ScatterLine Series in XAML
and in C#:

XAML
<telerikChart:RadCartesianChart>
<telerikChart:RadCartesianChart.BindingContext>
<local:SeriesNumericalViewModel />
</telerikChart:RadCartesianChart.BindingContext>
<telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:NumericalAxis LabelFitMode="MultiLine" />
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:NumericalAxis />
</telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:RadCartesianChart.Series>
<telerikChart:ScatterLineSeries XValueBinding="XData"
YValueBinding="YData"
ItemsSource="{Binding Data1}" />

544
Telerik UI for Xamarin

<telerikChart:ScatterLineSeries XValueBinding="XData"
YValueBinding="YData"
ItemsSource="{Binding Data2}" />
</telerikChart:RadCartesianChart.Series>
</telerikChart:RadCartesianChart>
 

C#
var chart = new RadCartesianChart
{
BindingContext = new SeriesNumericalViewModel(),
HorizontalAxis = new NumericalAxis()
{
LabelFitMode = AxisLabelFitMode.MultiLine
},
VerticalAxis = new NumericalAxis(),
Series =
{
new ScatterLineSeries
{
XValueBinding = new PropertyNameDataPointBinding("XData"),
YValueBinding = new PropertyNameDataPointBinding("YData")
},
new ScatterLineSeries
{
XValueBinding = new PropertyNameDataPointBinding("XData"),
YValueBinding = new PropertyNameDataPointBinding("YData")
}
}
};

chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "Data1");
chart.Series[1].SetBinding(ChartSeries.ItemsSourceProperty, "Data2");
 

Where the telerikChart namespace is the following:

XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
 

C#
using Telerik.XamarinForms.Chart;
 

And here is the result:

545
Telerik UI for Xamarin

A sample ScatterLine Series example can be found in the Chart/Series folder of the SDK Samples
Browser application.
 

Customization Example
Here we make some customizations on the ScatterLine Series applying Stroke and
StrokeThickness to the series. We extended the example above:

XAML
<telerikChart:RadCartesianChart>
<telerikChart:RadCartesianChart.BindingContext>
<local:SeriesNumericalViewModel />
</telerikChart:RadCartesianChart.BindingContext>
<telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:NumericalAxis LabelFitMode="MultiLine" />
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:NumericalAxis />
</telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:RadCartesianChart.Series>
<telerikChart:ScatterLineSeries XValueBinding="XData"
YValueBinding="YData"
Stroke="Red"
StrokeThickness="5"
ItemsSource="{Binding Data1}" />
<telerikChart:ScatterLineSeries XValueBinding="XData"
YValueBinding="YData"

546
Telerik UI for Xamarin

Stroke="Blue"
StrokeThickness="5"
ItemsSource="{Binding Data2}" />
</telerikChart:RadCartesianChart.Series>
</telerikChart:RadCartesianChart>
 

Here is the result:

See Also
 Line Series
 ScatterPoint Series
 Spline Series

547
Telerik UI for Xamarin

ScatterPoint Series
Overview
The ScatterPointSeries are represented on the chart as not connected data points. Each scatter
data point has to provide values for the X and Y coordinate on the RadCartesianChart. The
ScatterPointSeries require both axes of the chart to be of type NumericalAxis.

Features
 XValueBinding : Defines the binding that will be used to fill the XValue of ScatterDataPoint
members of the DataPoints collection.
 YValueBinding : Defines the binding that will be used to fill the YValue of ScatterDataPoint
members of the DataPoints collection.

Example
Here is an example how to create RadCartesianChart with ScatterPoint Series:

First, create the needed business objects, for example:

C#
public class NumericalData
{
public double XData { get; set; }
public double YData { get; set; }
}
 

Then create a ViewModel:

C#
public class SeriesNumericalViewModel
{
public ObservableCollection<NumericalData> Data1 { get; set; }
public ObservableCollection<NumericalData> Data2 { get; set; }

public SeriesNumericalViewModel()
{
this.Data1 = GetNumericData1();
this.Data2 = GetNumericData2();
}

public static ObservableCollection<NumericalData> GetNumericData1()


{
var data = new ObservableCollection<NumericalData>

548
Telerik UI for Xamarin

{
new NumericalData { XData = 2, YData = 13 },
new NumericalData { XData = 19, YData = 31 },
new NumericalData { XData = 22, YData = 33 },
new NumericalData { XData = 28, YData = 35 },
new NumericalData { XData = 33, YData = 46 },
new NumericalData { XData = 38, YData = 34 },
new NumericalData { XData = 49, YData = 66 },
new NumericalData { XData = 55, YData = 24 },
new NumericalData { XData = 62, YData = 41 },
};
return data;
}
public static ObservableCollection<NumericalData> GetNumericData2()
{
var data = new ObservableCollection<NumericalData>
{
new NumericalData { XData = 7, YData = 13 },
new NumericalData { XData = 19, YData = 17 },
new NumericalData { XData = 22, YData = 19 },
new NumericalData { XData = 28, YData = 21 },
new NumericalData { XData = 33, YData = 35 },
new NumericalData { XData = 38, YData = 43 },
new NumericalData { XData = 49, YData = 15 },
new NumericalData { XData = 55, YData = 21 },
new NumericalData { XData = 62, YData = 47 },
};
return data;
}
}
 

Finally, use the following snippet to declare a RadCartesianChart with ScatterPoint Series in XAML
and in C#:

XAML
<telerikChart:RadCartesianChart PaletteName="LightSelected">
<telerikChart:RadCartesianChart.BindingContext>
<local:SeriesNumericalViewModel />
</telerikChart:RadCartesianChart.BindingContext>
<telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:NumericalAxis LabelFitMode="MultiLine" />
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:NumericalAxis />
</telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:RadCartesianChart.Series>
<telerikChart:ScatterPointSeries XValueBinding="XData"
YValueBinding="YData"
ItemsSource="{Binding Data1}" />
<telerikChart:ScatterPointSeries XValueBinding="XData"
YValueBinding="YData"
ItemsSource="{Binding Data2}" />

549
Telerik UI for Xamarin

</telerikChart:RadCartesianChart.Series>
</telerikChart:RadCartesianChart>
 

C#
var chart = new RadCartesianChart
{
BindingContext = new SeriesNumericalViewModel(),
PaletteName = PaletteNames.LightSelected,
HorizontalAxis = new NumericalAxis()
{
LabelFitMode = AxisLabelFitMode.MultiLine
},
VerticalAxis = new NumericalAxis(),
Series =
{
new ScatterPointSeries
{
XValueBinding = new PropertyNameDataPointBinding("XData"),
YValueBinding = new PropertyNameDataPointBinding("YData")
},
new ScatterPointSeries
{
XValueBinding = new PropertyNameDataPointBinding("XData"),
YValueBinding = new PropertyNameDataPointBinding("YData")
}
}
};

chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "Data1");
chart.Series[1].SetBinding(ChartSeries.ItemsSourceProperty, "Data2");
 

Where the telerikChart namespace is the following:

XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
 

C#
using Telerik.XamarinForms.Chart;
 

And here is the result:

550
Telerik UI for Xamarin

A sample ScatterPoint Series example can be found in the Chart/Series folder of the SDK Samples
Browser application.
 

See Also
 Line Series
 ScatterLine Series
 Spline Series

551
Telerik UI for Xamarin

ScatterSplineSeries
Overview
The ScatterSplineSeries are represented on the chart as data points connected with curved line
segments. The ScatterSplineSeries inherit from theScatterPointSeries class and also require both
axes of the chart to be of type NumericalAxis.

Features
 Stroke (Color): changes the color used to draw lines.
 StrokeThickness (double): changes the width of the lines.

Example
Here is an example how to create RadCartesianChart with ScatterSpline Series:

First, create the needed business objects, for example:

C#
public class NumericalData
{
public double XData { get; set; }
public double YData { get; set; }
}
 

Then create a ViewModel:

C#
public class SeriesNumericalViewModel
{
public ObservableCollection<NumericalData> Data1 { get; set; }
public ObservableCollection<NumericalData> Data2 { get; set; }

public SeriesNumericalViewModel()
{
this.Data1 = GetNumericData1();
this.Data2 = GetNumericData2();
}

public static ObservableCollection<NumericalData> GetNumericData1()


{
var data = new ObservableCollection<NumericalData>
{
new NumericalData { XData = 2, YData = 13 },

552
Telerik UI for Xamarin

new NumericalData { XData = 19, YData = 31 },


new NumericalData { XData = 22, YData = 33 },
new NumericalData { XData = 28, YData = 35 },
new NumericalData { XData = 33, YData = 46 },
new NumericalData { XData = 38, YData = 34 },
new NumericalData { XData = 49, YData = 66 },
new NumericalData { XData = 55, YData = 24 },
new NumericalData { XData = 62, YData = 41 },
};
return data;
}
public static ObservableCollection<NumericalData> GetNumericData2()
{
var data = new ObservableCollection<NumericalData>
{
new NumericalData { XData = 7, YData = 13 },
new NumericalData { XData = 19, YData = 17 },
new NumericalData { XData = 22, YData = 19 },
new NumericalData { XData = 28, YData = 21 },
new NumericalData { XData = 33, YData = 35 },
new NumericalData { XData = 38, YData = 43 },
new NumericalData { XData = 49, YData = 15 },
new NumericalData { XData = 55, YData = 21 },
new NumericalData { XData = 62, YData = 47 },
};
return data;
}
}
 

Finally, use the following snippet to declare a RadCartesianChart with ScatterSpline Series in XAML
and in C#:

XAML
<telerikChart:RadCartesianChart>
<telerikChart:RadCartesianChart.BindingContext>
<local:SeriesNumericalViewModel />
</telerikChart:RadCartesianChart.BindingContext>
<telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:NumericalAxis LabelFitMode="MultiLine" />
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:NumericalAxis />
</telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:RadCartesianChart.Series>
<telerikChart:ScatterSplineSeries XValueBinding="XData"
YValueBinding="YData"
ItemsSource="{Binding Data1}" />
<telerikChart:ScatterSplineSeries XValueBinding="XData"
YValueBinding="YData"
ItemsSource="{Binding Data2}" />
</telerikChart:RadCartesianChart.Series>
</telerikChart:RadCartesianChart>

553
Telerik UI for Xamarin

C#
var chart = new RadCartesianChart
{
BindingContext = new SeriesNumericalViewModel(),
HorizontalAxis = new NumericalAxis()
{
LabelFitMode = AxisLabelFitMode.MultiLine
},
VerticalAxis = new NumericalAxis(),
Series =
{
new ScatterSplineSeries
{
XValueBinding = new PropertyNameDataPointBinding("XData"),
YValueBinding = new PropertyNameDataPointBinding("YData")
},
new ScatterSplineSeries
{
XValueBinding = new PropertyNameDataPointBinding("XData"),
YValueBinding = new PropertyNameDataPointBinding("YData")
}
}
};

chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "Data1");
chart.Series[1].SetBinding(ChartSeries.ItemsSourceProperty, "Data2");
 

Where the telerikChart namespace is the following:

XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
 

C#
using Telerik.XamarinForms.Chart;
 

And here is the result:

554
Telerik UI for Xamarin

A sample ScatterSpline Series example can be found in the Chart/Series folder of the SDK Samples
Browser application.
 

Customization Example
C#
var series = new ScatterSplineSeries
{
Stroke = new Color(0.6, 0.6, 0.9),
StrokeThickness = 5
};
 

## See Also

 Line Series
 ScatterLine Series
 Spline Series

555
Telerik UI for Xamarin

ScatterSplineArea Series
Overview
RadCartesianChart visualizes ScatterSplineAreaSeries as the area enclosed by the coordinate axes
and curved line segments that connect the series data points. The ScatterSplineAreaSeries inherit
from the ScatterPointSeries class and also require both axes of the chart to be of type NumericalAxis.

Features
 XValueBinding : Defines the binding that will be used to fill the XValue of ScatterDataPoint
members of the DataPoints collection.
 YValueBinding : Defines the binding that will be used to fill the YValue of ScatterDataPoint
members of the DataPoints collection.
 Stroke (Color): Changes the color used to draw lines.
 StrokeThickness (double): Changes the width of the lines.
 Fill (Color): Changes the color used to fill the area shapes.

Example
Here is an example how to create RadCartesianChart with ScatterSplineArea Series:

First, create the needed business objects, for example:

C#
public class NumericalData
{
public double XData { get; set; }
public double YData { get; set; }
}
 

Then create a ViewModel:

Finally, use the following snippet to declare a RadCartesianChart with ScatterSplineArea Series in
XAML and in C#:

XAML
<telerikChart:RadCartesianChart>
<telerikChart:RadCartesianChart.BindingContext>
<local:NumericalViewModel />
</telerikChart:RadCartesianChart.BindingContext>
<telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:NumericalAxis LabelFitMode="MultiLine" />
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.VerticalAxis>

556
Telerik UI for Xamarin

<telerikChart:NumericalAxis />
</telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:RadCartesianChart.Series>
<telerikChart:ScatterSplineAreaSeries XValueBinding="XData"
YValueBinding="YData"
ItemsSource="{Binding Data}" />
</telerikChart:RadCartesianChart.Series>
</telerikChart:RadCartesianChart>
 

C#
var chart = new RadCartesianChart
{
BindingContext = new NumericalViewModel(),
HorizontalAxis = new NumericalAxis()
{
LabelFitMode = AxisLabelFitMode.MultiLine
},
VerticalAxis = new NumericalAxis(),
Series =
{
new ScatterSplineAreaSeries
{
XValueBinding = new PropertyNameDataPointBinding("XData"),
YValueBinding = new PropertyNameDataPointBinding("YData")
}
}
};

chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "Data");
 

Where the telerikChart namespace is the following:

XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
 

C#
using Telerik.XamarinForms.Chart;
 

And here is the result:

557
Telerik UI for Xamarin

A sample ScatterSplineArea Series example can be found in the Chart/Series folder of the SDK
Samples Browser application.
 

Customization Example
Here we make some customization:

C#
var series = new ScatterSplineAreaSeries
{
Stroke = new Color(0.6, 0.6, 0.9),
StrokeThickness = 5,
Fill = new Color(0.8, 0.8, 1)
};
 

See Also
 Line Series
 ScatterLine Series
 Spline Series

558
Telerik UI for Xamarin

Spline Series
Overview
RadCartesianChart visualizes each data item from the LineSeries and connects them with curved
line segments. The SplineSeries extend LineSeries, so they are also CategoricalSeries and require
one CategoricalAxis and one NumricalAxis.

Features
SplineSeries extend LineSeries so they provide the same properties to change their style:

 Stroke (Color): changes the color used to draw lines.


 StrokeThickness (double): changes the width of the lines.

Example
Here is an example how to create RadCartesianChart with Spline Series:

First, create the needed business objects, for example:

C#
public class CategoricalData
{
public object Category { get; set; }

public double Value { get; set; }


}
 

Then create a ViewModel:

C#
public class CategoricalDataViewModel
{
public ObservableCollection<CategoricalData> Data { get; set; }

public CategoricalDataViewModel()
{
this.Data = GetCategoricalData();
}

private static ObservableCollection<CategoricalData> GetCategoricalData()


{
var data = new ObservableCollection<CategoricalData>
{

559
Telerik UI for Xamarin

new CategoricalData { Category = "A", Value = 101 },


new CategoricalData { Category = "B", Value = 45 },
new CategoricalData { Category = "C", Value = 77 },
new CategoricalData { Category = "D", Value = 15 },
new CategoricalData { Category = "E", Value = 56 },
};
return data;
}
}
 

Finally, use the following snippet to declare a RadCartesianChart with Spline Series in XAML and in
C#:

XAML
<telerikChart:RadCartesianChart>
<telerikChart:RadCartesianChart.BindingContext>
<local:CategoricalDataViewModel />
</telerikChart:RadCartesianChart.BindingContext>
<telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:CategoricalAxis LabelFitMode="MultiLine"
PlotMode="OnTicks" />
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:NumericalAxis />
</telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:RadCartesianChart.Series>
<telerikChart:SplineSeries ValueBinding="Value"
CategoryBinding="Category"
ItemsSource="{Binding Data}" />
</telerikChart:RadCartesianChart.Series>
</telerikChart:RadCartesianChart>
 

C#
var chart = new RadCartesianChart
{
BindingContext = new CategoricalDataViewModel(),
HorizontalAxis = new CategoricalAxis()
{
LabelFitMode = AxisLabelFitMode.MultiLine,
PlotMode = AxisPlotMode.OnTicks
},
VerticalAxis = new NumericalAxis(),
Series =
{
new SplineSeries
{
ValueBinding = new PropertyNameDataPointBinding("Value"),
CategoryBinding = new PropertyNameDataPointBinding("Category")
}
}

560
Telerik UI for Xamarin

};

chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "Data");
 

Where the telerikChart namespace is the following:

XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
 

C#
using Telerik.XamarinForms.Chart;
 

And here is the result:

A sample Spline Series example can be found in the Chart/Series folder of the SDK Samples Browser
application.
 

Customization Example
Here we make some customization:

C#

561
Telerik UI for Xamarin

var series = new SplineSeries


{
Stroke = new Color(0.6, 0.6, 0.9),
StrokeThickness = 5
};
 

See Also
 ScatterArea Series
 ScatterLine Series
 ScatterPoint Series

562
Telerik UI for Xamarin

SplineArea Series
Overview
RadCartesianChart visualizes SplineAreaSeries as an area on the chart that is enclosed by the
coordinate axes and straight line segments that connect the data points represented by these series.
The SplineAreaSeries extend CategoricalStrokedSeries, so they are also CategoricalSeries and
require one CategoricalAxis and one NumricalAxis.

Features
 Stroke (Color): changes the color used to draw lines.
 StrokeThickness (double): changes the width of the lines.
 Fill (Color): changes the color used to fill the area shapes.

Example
Here is an example how to create RadCartesianChart with SplineArea Series:

First, create the needed business objects, for example:

C#
public class CategoricalData
{
public object Category { get; set; }

public double Value { get; set; }


}
 

Then create a ViewModel:

C#
public class CategoricalViewModel
{
public ObservableCollection<CategoricalData> Data { get; set; }

public CategoricalViewModel()
{
this.Data = GetCategoricalData();
}

private static ObservableCollection<CategoricalData> GetCategoricalData()


{
var data = new ObservableCollection<CategoricalData>
{

563
Telerik UI for Xamarin

new CategoricalData { Category = "Greenings", Value = 52 },


new CategoricalData { Category = "Perfecto", Value = 19 },
new CategoricalData { Category = "NearBy", Value = 82 },
new CategoricalData { Category = "Family", Value = 23 },
new CategoricalData { Category = "Fresh", Value = 56 },
};
return data;
}
}
 

Finally, use the following snippet to declare a RadCartesianChart with SplineArea Series in XAML
and in C#:

XAML
<telerikChart:RadCartesianChart>
<telerikChart:RadCartesianChart.BindingContext>
<local:CategoricalViewModel />
</telerikChart:RadCartesianChart.BindingContext>
<telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:CategoricalAxis LabelFitMode="MultiLine"
PlotMode="OnTicks" />
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:NumericalAxis />
</telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:RadCartesianChart.Series>
<telerikChart:SplineAreaSeries ValueBinding="Value"
CategoryBinding="Category"
ItemsSource="{Binding Data}" />
</telerikChart:RadCartesianChart.Series>
</telerikChart:RadCartesianChart>
 

C#
var chart = new RadCartesianChart
{
BindingContext = new SeriesNumericalViewModel(),
HorizontalAxis = new NumericalAxis()
{
LabelFitMode = AxisLabelFitMode.MultiLine
},
VerticalAxis = new NumericalAxis(),
Series =
{
new ScatterSplineSeries
{
XValueBinding = new PropertyNameDataPointBinding("XData"),
YValueBinding = new PropertyNameDataPointBinding("YData")
},
new ScatterSplineSeries
{

564
Telerik UI for Xamarin

XValueBinding = new PropertyNameDataPointBinding("XData"),


YValueBinding = new PropertyNameDataPointBinding("YData")
}
}
};

chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "Data1");
chart.Series[1].SetBinding(ChartSeries.ItemsSourceProperty, "Data2");
 

Where the telerikChart namespace is the following:

XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
 

C#
using Telerik.XamarinForms.Chart;
 

And here is the result:

Customization Example
C#
var series = new SplineAreaSeries
{

565
Telerik UI for Xamarin

Stroke = new Color(0.6, 0.6, 0.9),


StrokeThickness = 5,
Fill = new Color(0.8, 0.8, 1)
};
 

See Also
 Line Series
 ScatterLine Series
 Spline Series

566
Telerik UI for Xamarin

Combine Mode
When the series in a RadCartesianChart are more than one, a few different drawing strategies can
be used. The possible strategies are:

 None: The series are not combined - each series is plotted independently.
 Cluster: Series are combined next to each other (applicable for BarSeries).
 Stack: Series form stacks.
 Stack100: Series form stacks that occupy 100% of the plot area and the characterictic size of
each series is proportional to its relative value.

The default combine mode is None. You can define the current combine mode with the series
CombineMode property.

CombineMode could be applied only to Categorical Series, such as Bar, Line and Area.
 

Stack Bar Series Example


Here is an example how to create Stack CartesianChart with Bar Series :

First, create the needed business objects, for example:

C#
public class CategoricalData
{
public object Category { get; set; }

public double Value { get; set; }


}
 

Then create a ViewModel:

C#
public class SeriesCategoricalViewModel
{
public ObservableCollection<CategoricalData> Data1 { get; set; }
public ObservableCollection<CategoricalData> Data2 { get; set; }

public SeriesCategoricalViewModel()
{
this.Data1 = GetCategoricalData1();
this.Data2 = GetCategoricalData2();
}

private static ObservableCollection<CategoricalData> GetCategoricalData1()


{

567
Telerik UI for Xamarin

var data = new ObservableCollection<CategoricalData>


{
new CategoricalData { Category = "Greenings", Value = 52 },
new CategoricalData { Category = "Perfecto", Value = 19 },
new CategoricalData { Category = "NearBy", Value = 82 },
new CategoricalData { Category = "Family", Value = 23 },
new CategoricalData { Category = "Fresh", Value = 56 },
};
return data;
}

private static ObservableCollection<CategoricalData> GetCategoricalData2()


{
var data = new ObservableCollection<CategoricalData>
{
new CategoricalData { Category = "Greenings", Value = 33 },
new CategoricalData { Category = "Perfecto", Value = 51 },
new CategoricalData { Category = "NearBy", Value = 11 },
new CategoricalData { Category = "Family", Value = 94 },
new CategoricalData { Category = "Fresh", Value = 12 },
};
return data;
}
}
 

Finally, use the following snippet to declare a CombineMode property to the Bar Series in XAML and
in C#:

XAML
<telerikChart:RadCartesianChart>
<telerikChart:RadCartesianChart.BindingContext>
<local:SeriesCategoricalViewModel />
</telerikChart:RadCartesianChart.BindingContext>
<telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:CategoricalAxis LabelFitMode="MultiLine" />
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:NumericalAxis LabelFitMode="MultiLine" />
</telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:RadCartesianChart.Series>
<telerikChart:BarSeries ValueBinding="Value"
CategoryBinding="Category"
CombineMode="Stack"
ItemsSource="{Binding Data1}" />
<telerikChart:BarSeries ValueBinding="Value"
CategoryBinding="Category"
CombineMode="Stack"
ItemsSource="{Binding Data2}" />
</telerikChart:RadCartesianChart.Series>
</telerikChart:RadCartesianChart>
 

568
Telerik UI for Xamarin

C#
var chart = new RadCartesianChart
{
BindingContext = new SeriesCategoricalViewModel(),
HorizontalAxis = new CategoricalAxis()
{
LabelFitMode = AxisLabelFitMode.MultiLine,
},
VerticalAxis = new NumericalAxis()
{
LabelFitMode = AxisLabelFitMode.MultiLine,
},
Series =
{
new BarSeries
{
ValueBinding = new PropertyNameDataPointBinding("Value"),
CategoryBinding = new PropertyNameDataPointBinding("Category"),
CombineMode = ChartSeriesCombineMode.Stack
},
new BarSeries
{
ValueBinding = new PropertyNameDataPointBinding("Value"),
CategoryBinding = new PropertyNameDataPointBinding("Category"),
CombineMode = ChartSeriesCombineMode.Stack
}
}
};

chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "Data1");
chart.Series[1].SetBinding(ChartSeries.ItemsSourceProperty, "Data2");
 

Where the telerikChart namespace is the following:

XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
 

C#
using Telerik.XamarinForms.Chart;
 

Here is how Stack Bar Series looks:

569
Telerik UI for Xamarin

A sample StackBarSeries example can be found in the Chart/Series folder of the SDK Samples
Browser application.
 

Stack Area Series Example


Here is how Stack Area Series looks:

570
Telerik UI for Xamarin

A sample StackAreaSeries example can be found in the Chart/Series folder of the SDK Samples
Browser application.
 

Stack Spline Area Series Example


Here is how Stack Spline Area Series looks:

571
Telerik UI for Xamarin

A sample StackSplineSeries example can be found in the Chart/Series folder of the SDK Samples
Browser application.
 

See Also
 CartesianChart Orientation

572
Telerik UI for Xamarin

Orientation
The orientation of the series depends on which chart axis is horizontal and which one is vertical.

Orientation property could be applied only to CategoricalSeries, such as Bar, Line and Area.
 

Horizontal BarSeries Example


Here is an example how to create RadCartesianChart with vertical CategoricalAxis and Horizontal
Bar Series:

First, create the needed business objects, for example:

C#
public class CategoricalData
{
public object Category { get; set; }

public double Value { get; set; }


}
 

Then create a ViewModel:

C#
public class CategoricalDataViewModel
{
public ObservableCollection<CategoricalData> Data { get; set; }

public CategoricalDataViewModel()
{
this.Data = GetCategoricalData();
}

private static ObservableCollection<CategoricalData> GetCategoricalData()


{
var data = new ObservableCollection<CategoricalData>
{
new CategoricalData { Category = "A", Value = 101 },
new CategoricalData { Category = "B", Value = 45 },
new CategoricalData { Category = "C", Value = 77 },
new CategoricalData { Category = "D", Value = 15 },
new CategoricalData { Category = "E", Value = 56 },
};
return data;
}
}

573
Telerik UI for Xamarin

Finally, use the following snippet to declare a RadCartesianChart with Bar Series in XAML and in
C#:

XAML
<telerikChart:RadCartesianChart>
<telerikChart:RadCartesianChart.BindingContext>
<local:CategoricalDataViewModel />
</telerikChart:RadCartesianChart.BindingContext>
<telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:CategoricalAxis />
</telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:NumericalAxis />
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.Series>
<telerikChart:BarSeries ValueBinding="Value"
CategoryBinding="Category"
ItemsSource="{Binding Data}" />
</telerikChart:RadCartesianChart.Series>
</telerikChart:RadCartesianChart>
 

C#
var chart = new RadCartesianChart
{
BindingContext = new CategoricalDataViewModel(),
VerticalAxis = new CategoricalAxis()
{
LabelFitMode = AxisLabelFitMode.MultiLine,
},
HorizontalAxis = new NumericalAxis()
{
LabelFitMode = AxisLabelFitMode.MultiLine,
},
Series =
{
new BarSeries
{
ValueBinding = new PropertyNameDataPointBinding("Value"),
CategoryBinding = new PropertyNameDataPointBinding("Category")
}
}
};

chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "Data");
 

Where the telerikChart namespace is the following:

XAML

574
Telerik UI for Xamarin

xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
 

C#
using Telerik.XamarinForms.Chart;
 

Here is the result:

A sample Horizontal Bar Series example can be found in the Chart/Series folder of the SDK Samples
Browser application.
 

Horizontal Stack BarSeries Example


Here is an example how to create RadCartesianChart with vertical CategoricalAxis and Stack
Horizontal Bar Series:

First, create the needed business objects, for example:

C#
public class CategoricalData
{
public object Category { get; set; }

public double Value { get; set; }

575
Telerik UI for Xamarin

}
 

Then create a ViewModel:

C#
public class SeriesCategoricalViewModel
{
public ObservableCollection<CategoricalData> Data1 { get; set; }
public ObservableCollection<CategoricalData> Data2 { get; set; }

public SeriesCategoricalViewModel()
{
this.Data1 = GetCategoricalData1();
this.Data2 = GetCategoricalData2();
}

private static ObservableCollection<CategoricalData> GetCategoricalData1()


{
var data = new ObservableCollection<CategoricalData>
{
new CategoricalData { Category = "Greenings", Value = 52 },
new CategoricalData { Category = "Perfecto", Value = 19 },
new CategoricalData { Category = "NearBy", Value = 82 },
new CategoricalData { Category = "Family", Value = 23 },
new CategoricalData { Category = "Fresh", Value = 56 },
};
return data;
}

private static ObservableCollection<CategoricalData> GetCategoricalData2()


{
var data = new ObservableCollection<CategoricalData>
{
new CategoricalData { Category = "Greenings", Value = 33 },
new CategoricalData { Category = "Perfecto", Value = 51 },
new CategoricalData { Category = "NearBy", Value = 11 },
new CategoricalData { Category = "Family", Value = 94 },
new CategoricalData { Category = "Fresh", Value = 12 },
};
return data;
}
}
 

Finally, use the following snippet to declare a RadCartesianChart with Bar Series in XAML and in
C#:

XAML
<telerikChart:RadCartesianChart>
<telerikChart:RadCartesianChart.BindingContext>
<local:SeriesCategoricalViewModel />

576
Telerik UI for Xamarin

</telerikChart:RadCartesianChart.BindingContext>
<telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:CategoricalAxis />
</telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:NumericalAxis />
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.Series>
<telerikChart:BarSeries ValueBinding="Value"
CategoryBinding="Category"
CombineMode="Stack"
ItemsSource="{Binding Data1}" />
<telerikChart:BarSeries ValueBinding="Value"
CategoryBinding="Category"
CombineMode="Stack"
ItemsSource="{Binding Data2}" />
</telerikChart:RadCartesianChart.Series>
</telerikChart:RadCartesianChart>
 

C#
var chart = new RadCartesianChart
{
BindingContext = new SeriesCategoricalViewModel(),
VerticalAxis = new CategoricalAxis()
{
LabelFitMode = AxisLabelFitMode.MultiLine,
},
HorizontalAxis = new NumericalAxis()
{
LabelFitMode = AxisLabelFitMode.MultiLine,
},
Series =
{
new BarSeries
{
ValueBinding = new PropertyNameDataPointBinding("Value"),
CategoryBinding = new PropertyNameDataPointBinding("Category"),
CombineMode = ChartSeriesCombineMode.Stack
},
new BarSeries
{
ValueBinding = new PropertyNameDataPointBinding("Value"),
CategoryBinding = new PropertyNameDataPointBinding("Category"),
CombineMode = ChartSeriesCombineMode.Stack
}
}
};

chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "Data1");
chart.Series[1].SetBinding(ChartSeries.ItemsSourceProperty, "Data2");
 

577
Telerik UI for Xamarin

Where the telerikChart namespace is the following:

XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
 

C#
using Telerik.XamarinForms.Chart;
 

Here is the result:

A sample Stack Horizontal Bar Series example can be found in the Chart/Series folder of the SDK
Samples Browser application.
 

See Also
 CartesianChart Combine Mode

578
Telerik UI for Xamarin

DonutSeries
Overview
RadPieChart visualizes the DonutSeries in the shape of a donut. The inner empty space is set
according to the InnerRadiusFactor property. Each data item is visually represented by a donut slice.
The ratio between the space consumed by each slice and the space consumed by the whole chart is
the same as the ratio between the value of the data point that it represents and the total value of all
data points in the series.

Features
 ValueBinding: Defines the binding to a property of the data model that will be used to fill the
pie slices.
 RadiusFactor: Specifies the radius factor used to calculate the radius of the visual series.
This value is usually within the [0,1] range but it is possible to oversize the series by setting a
value greater than 1.
 InnerRadiusFactor: Specifies the radius factor used to calculate the radius of the inner empty
space within the Donut visual element.
 SelectedPointOffset: Sets the offset applied to the currently selected point.

Example
Here is an example that shows how to create a basic RadPieChart with DonutSeries in XAML:

XAML
<telerikChart:RadPieChart>
<telerikChart:RadPieChart.BindingContext>
<local:ViewModel />
</telerikChart:RadPieChart.BindingContext>
<telerikChart:RadPieChart.Series>
<telerikChart:DonutSeries ShowLabels="True"
InnerRadiusFactor="0.4"
ValueBinding="Value"
ItemsSource="{Binding Data}" />
</telerikChart:RadPieChart.Series>
</telerikChart:RadPieChart>
 

Where:

XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
 

579
Telerik UI for Xamarin

And the business object exposes the following properties:

C#
public class CategoricalData
{
public object Category { get; set; }

public double Value { get; set; }


}
 

You'd also need to add a ViewModel class and add some data:

C#
public class ViewModel
{
public ObservableCollection<CategoricalData> Data { get; set; }

public ViewModel()
{
this.Data = GetCategoricalData();
}

private static ObservableCollection<CategoricalData> GetCategoricalData()


{
var data = new ObservableCollection<CategoricalData>
{
new CategoricalData { Category = "Greenings", Value = 52 },
new CategoricalData { Category = "Perfecto", Value = 19 },
new CategoricalData { Category = "NearBy", Value = 82 },
new CategoricalData { Category = "Family", Value = 23 },
new CategoricalData { Category = "Fresh", Value = 56 },
};
return data;
}
}
 

Here is the result:

580
Telerik UI for Xamarin

A sample Donut Series example can be found in the Chart/PieChart folder of the SDK Samples
Browser application.
 

See Also
 Pie Series Overview
 Categorical Series Overview

581
Telerik UI for Xamarin

PieSeries
Overview
RadPieChart visualizes the PieSeries in the shape of a pie. Each data item is visually represented by
a pie slice. The ratio between the space consumed by each slice and the space consumed by the
whole chart is the same as the ratio between the value of the data point that it represents and the
total value of all data points in the series.

Features
 ValueBinding: Defines the binding to a property of the data model that will be used to fill the
pie slices.
 RadiusFactor: Defines the radius factor used to calculate the radius of the visual series. This
value is usually within the [0,1] range but it is possible to oversize the series by setting a
value greater than 1.
 SelectedPointOffset: Defines the offset applied to the currently selected point.

Example
Here is an example how to create RadPieChart with Pie Series:

First, create the needed business objects, for example:

C#
public class CategoricalData
{
public object Category { get; set; }

public double Value { get; set; }


}
 

Then create a ViewModel:

C#
public class ViewModel
{
public ObservableCollection<CategoricalData> Data { get; set; }

public ViewModel()
{
this.Data = GetCategoricalData();
}

private static ObservableCollection<CategoricalData> GetCategoricalData()

582
Telerik UI for Xamarin

{
var data = new ObservableCollection<CategoricalData>
{
new CategoricalData { Category = "Greenings", Value = 52 },
new CategoricalData { Category = "Perfecto", Value = 19 },
new CategoricalData { Category = "NearBy", Value = 82 },
new CategoricalData { Category = "Family", Value = 23 },
new CategoricalData { Category = "Fresh", Value = 56 },
};
return data;
}
}
 

Finally, use the following snippet to declare a RadPieChart with Pie Series in XAML and in C#:

XAML
<telerikChart:RadPieChart>
<telerikChart:RadPieChart.BindingContext>
<local:ViewModel />
</telerikChart:RadPieChart.BindingContext>
<telerikChart:RadPieChart.Series>
<telerikChart:PieSeries ShowLabels="True"
RadiusFactor="0.8"
ValueBinding="Value"
ItemsSource="{Binding Data}" />
</telerikChart:RadPieChart.Series>
</telerikChart:RadPieChart>
 

C#
var chart = new RadPieChart
{
BindingContext = new ViewModel(),
Series =
{
new PieSeries
{
ShowLabels = true,
RadiusFactor = 0.8,
ValueBinding = new PropertyNameDataPointBinding("Value")
}
}
};

chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "Data");
 

In addition to this you need to add the following namespace:

XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF

583
Telerik UI for Xamarin

orms.Chart"
 

C#
using Telerik.XamarinForms.Chart;
 

Here is the result:

A sample Pie Series example can be found in the Chart/PieChart folder of the SDK Samples Browser
application.
 

See Also
 Donut Series
 Bar Series
 Categorical Series Overview

584
Telerik UI for Xamarin

Ohlc Series
Overview
RadCartesianChart visualizes each data point from the OhlcSeries as a line with open and close
value indicators on its side. This is a typical financial series that can be used to visualize the state of
a market for a period of time. The series operates with a special kind of data in the form of four
parameters defining the stock market - open, high, low, and close. The high and low values show the
price range (the highest and lowest prices) over one unit of time. The open and close values indicate
the opening and closing price of the stock for the corresponding period

Example
Here is an example of how to create a basic RadCartesianChart with OhlcSeries in XAML and C#:

XAML
<telerikChart:RadCartesianChart PaletteName="Light"
SelectionPaletteName="LightSelected"
BackgroundColor="White" >
<telerikChart:RadCartesianChart.BindingContext>
<local:ViewModel />
</telerikChart:RadCartesianChart.BindingContext>
<telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:DateTimeContinuousAxis LineColor="#A9A9A9"
LabelFitMode="Rotate"
LabelFormat="MMM"
PlotMode="BetweenTicks"
MajorStepUnit="Month"/>
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:NumericalAxis LineColor="#A9A9A9"
MajorTickBackgroundColor="#A9A9A9" />
</telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:RadCartesianChart.Series>
<telerikChart:OhlcSeries CategoryBinding="Category"
OpenBinding="Open"
HighBinding="High"
LowBinding="Low"
CloseBinding="Close"
ItemsSource="{Binding SeriesData}" />
</telerikChart:RadCartesianChart.Series>
</telerikChart:RadCartesianChart>
 

C#
var chart = new RadCartesianChart
{
BackgroundColor = Color.White,

585
Telerik UI for Xamarin

BindingContext = new ViewModel(),


HorizontalAxis = new DateTimeContinuousAxis()
{
LabelFitMode = AxisLabelFitMode.Rotate,
PlotMode = AxisPlotMode.BetweenTicks,
MajorStepUnit = TimeInterval.Month,
LabelFormat = "MMM"
},
VerticalAxis = new NumericalAxis()
{
LineColor = Color.FromHex("#A9A9A9"),
MajorTickBackgroundColor = Color.FromHex("#A9A9A9")
},
Series =
{
new OhlcSeries
{
CategoryBinding = new PropertyNameDataPointBinding("Category"),
OpenBinding = new PropertyNameDataPointBinding("Open"),
HighBinding = new PropertyNameDataPointBinding("High"),
LowBinding = new PropertyNameDataPointBinding("Low"),
CloseBinding = new PropertyNameDataPointBinding("Close")
}
},
};

chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "SeriesData");
 

Add the following namespace:

XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
 

Here is how the business model is defined:

C#
public class OhlcDataPoint : NotifyPropertyChangedBase
{
private DateTime category;
private double open;
private double high;
private double low;
private double close;

public DateTime Category


{
get { return this.category; }
set
{

586
Telerik UI for Xamarin

if (value != this.category)
{
this.category = value;
this.OnPropertyChanged();
}
}
}

public double Open


{
get { return this.open; }
set
{
if (value != this.open)
{
this.open = value;
this.OnPropertyChanged();
}
}
}

public double High


{
get { return this.high; }
set
{
if (value != this.high)
{
this.high = value;
this.OnPropertyChanged();
}
}
}

public double Low


{
get { return this.low; }
set
{
if (value != this.low)
{
this.low = value;
this.OnPropertyChanged();
}
}
}

public double Close


{
get { return this.close; }
set
{
if (value != this.close)

587
Telerik UI for Xamarin

{
this.close = value;
this.OnPropertyChanged();
}
}
}
}
 

And here is the result:

SDK Browser application contains an example that shows how to use the OhlcSeries. You can find
the application in the Examples folder of your local Telerik UI for Xamarin installation.
 

See Also
 Candlestick Series Overview
 Financial Indicators

588
Telerik UI for Xamarin

Candlestick Series
Overview
RadCartesianChart visualizes each data point from the CandlestickSeries as a visual that resembles
a candlestick. This is a typical financial series that can be used to visualize the state of a market for
a period of time. The series operates with a special kind of data in the form of four parameters
defining the stock market - open, high, low, and close. The high and low values show the price range
(the highest and lowest prices) over one unit of time. The open and close values indicate the
opening and closing price of the stock for the corresponding period

Example
Here is an example of how to create a basic RadCartesianChart with CandlestickSeries in XAML
and C#:

XAML
<telerikChart:RadCartesianChart PaletteName="Light"
SelectionPaletteName="LightSelected"
BackgroundColor="White" >
<telerikChart:RadCartesianChart.BindingContext>
<local:ViewModel />
</telerikChart:RadCartesianChart.BindingContext>
<telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:DateTimeContinuousAxis LineColor="#A9A9A9"
LabelFitMode="Rotate"
LabelFormat="MMM"
PlotMode="BetweenTicks"
MajorStepUnit="Month"/>
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:NumericalAxis LineColor="#A9A9A9"
MajorTickBackgroundColor="#A9A9A9" />
</telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:RadCartesianChart.Series>
<telerikChart:CandlestickSeries CategoryBinding="Category"
OpenBinding="Open"
HighBinding="High"
LowBinding="Low"
CloseBinding="Close"
ItemsSource="{Binding SeriesData}" />
</telerikChart:RadCartesianChart.Series>
</telerikChart:RadCartesianChart>
 

C#
var chart = new RadCartesianChart
{

589
Telerik UI for Xamarin

BackgroundColor = Color.White,
BindingContext = new ViewModel(),
HorizontalAxis = new DateTimeContinuousAxis()
{
LabelFitMode = AxisLabelFitMode.Rotate,
PlotMode = AxisPlotMode.BetweenTicks,
MajorStepUnit = TimeInterval.Month,
LabelFormat = "MMM"
},
VerticalAxis = new NumericalAxis()
{
LineColor = Color.FromHex("#A9A9A9"),
MajorTickBackgroundColor = Color.FromHex("#A9A9A9")
},
Series =
{
new CandlestickSeries
{
CategoryBinding = new PropertyNameDataPointBinding("Category"),
OpenBinding = new PropertyNameDataPointBinding("Open"),
HighBinding = new PropertyNameDataPointBinding("High"),
LowBinding = new PropertyNameDataPointBinding("Low"),
CloseBinding = new PropertyNameDataPointBinding("Close")
}
},
};

chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "SeriesData");
 

Add the following namespace:

XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
 

Here is how the business model is defined:

C#
public class OhlcDataPoint : NotifyPropertyChangedBase
{
private DateTime category;
private double open;
private double high;
private double low;
private double close;

public DateTime Category


{
get { return this.category; }
set

590
Telerik UI for Xamarin

{
if (value != this.category)
{
this.category = value;
this.OnPropertyChanged();
}
}
}

public double Open


{
get { return this.open; }
set
{
if (value != this.open)
{
this.open = value;
this.OnPropertyChanged();
}
}
}

public double High


{
get { return this.high; }
set
{
if (value != this.high)
{
this.high = value;
this.OnPropertyChanged();
}
}
}

public double Low


{
get { return this.low; }
set
{
if (value != this.low)
{
this.low = value;
this.OnPropertyChanged();
}
}
}

public double Close


{
get { return this.close; }
set
{

591
Telerik UI for Xamarin

if (value != this.close)
{
this.close = value;
this.OnPropertyChanged();
}
}
}
}
 

And here is the result:

SDK Browser application contains an example that shows how to use the CandlestickSeries. You
can find the application in the Examples folder of your local Telerik UI for Xamarin installation.
 

See Also
 Ohlc Series Overview
 Financial Indicators

592
Telerik UI for Xamarin

Financial Indicators
Overview
The financial, or also called stock indicators, are mainly used for keeping track of stock prices and
patterns of price changes over time. You can find further information about what indicators are and
what they are being used for by following this link: Short information about financial indicators.

In terms of using the indicators in the RadCartesianChart, you will need to add them as you would
add any other Cartesian series. Every indicator has a related formula by which it calculates the
expected result. All you need to do is provide the needed data.

There are two types of indicators in terms of setting their properties and getting them ready for
displaying your stock data:

Indicators that have a category and a value(usually the close) bindings as well as one or more
periods. Here are the available indicators:

 OscillatorIndicator
 RateOfChangeIndicator
 RelativeStrengthIndexIndicator
 TrixIndicator
 WeightedMovingAverageIndicator
 ExponentialMovingAverageIndicator
 AdaptiveMovingAverageKaufmanIndicator
 BollingerBandsIndicator
 RelativeMomentumIndexIndicator
 MacdIndicator

Indicators that have a category and high/low/close value bindings as well as none, one, or more
periods:

 AverageTrueRangeIndicator
 CommodityChannelIndexIndicator
 StochasticFastIndicator
 StochasticSlowIndicator
 TrueRangeIndicator
 UltimateOscillatorIndicator

Example
Here is an example of how to create a basic RadCartesianChart with OhlcSeries and a couple of
ExponentialMovingAverageIndicator instances with different period set:

XAML
<telerikChart:RadCartesianChart PaletteName="Light"

593
Telerik UI for Xamarin

SelectionPaletteName="LightSelected"
BackgroundColor="White" >
<telerikChart:RadCartesianChart.BindingContext>
<local:ViewModel />
</telerikChart:RadCartesianChart.BindingContext>
<telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:DateTimeContinuousAxis LineColor="#A9A9A9"
LabelFitMode="Rotate"
LabelFormat="dd/MM"
PlotMode="BetweenTicks"
MajorStep="2"
MajorStepUnit="Day"/>
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:NumericalAxis LineColor="#A9A9A9"
Minimum="320"
Maximum="350"
MajorTickBackgroundColor="#A9A9A9" />
</telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:RadCartesianChart.Series>
<telerikChart:OhlcSeries CategoryBinding="Category"
DisplayName="AppleStocks-OHLC"
OpenBinding="Open"
HighBinding="High"
LowBinding="Low"
CloseBinding="Close"
ItemsSource="{Binding SeriesData}"/>

<telerikChart:ExponentialMovingAverageIndicator CategoryBinding="Category"
DisplayName="EMA 7days"
ValueBinding="Close"
Period="7"
StrokeThickness="1"
Stroke="DarkGreen"
ItemsSource="{Binding SeriesData}"/>

<telerikChart:ExponentialMovingAverageIndicator CategoryBinding="Category"
DisplayName="EMA 14days"
ValueBinding="Close"
Period="14"
StrokeThickness="1"
Stroke="DarkOrange"
ItemsSource="{Binding SeriesData}"/>
</telerikChart:RadCartesianChart.Series>
</telerikChart:RadCartesianChart>
 

C#
var chart = new RadCartesianChart
{
BackgroundColor = Color.White,
BindingContext = new ViewModel(),
HorizontalAxis = new DateTimeContinuousAxis()

594
Telerik UI for Xamarin

{
LabelFitMode = AxisLabelFitMode.Rotate,
PlotMode = AxisPlotMode.BetweenTicks,
MajorStepUnit = TimeInterval.Day,
MajorStep = 2,
LabelFormat = "dd/MM",
LineColor = Color.FromHex("#A9A9A9")
},
VerticalAxis = new NumericalAxis()
{
LineColor = Color.FromHex("#A9A9A9"),
Maximum = 350,
Minimum = 320,
MajorTickBackgroundColor = Color.FromHex("#A9A9A9")
},
Series =
{
new OhlcSeries
{
CategoryBinding = new PropertyNameDataPointBinding("Category"),
OpenBinding = new PropertyNameDataPointBinding("Open"),
HighBinding = new PropertyNameDataPointBinding("High"),
LowBinding = new PropertyNameDataPointBinding("Low"),
CloseBinding = new PropertyNameDataPointBinding("Close")
},
new ExponentialMovingAverageIndicator
{
CategoryBinding = new PropertyNameDataPointBinding("Category"),
ValueBinding = new PropertyNameDataPointBinding("Close"),
Period = 7,
Stroke = Color.DarkGreen,
StrokeThickness = 1,
DisplayName = "EMA 7days"
},
new ExponentialMovingAverageIndicator
{
CategoryBinding = new PropertyNameDataPointBinding("Category"),
ValueBinding = new PropertyNameDataPointBinding("Close"),
Period = 14,
Stroke = Color.DarkOrange,
StrokeThickness = 1,
DisplayName = "EMA 14days"
}
}
};

chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "SeriesData");
chart.Series[1].SetBinding(ChartSeries.ItemsSourceProperty, "SeriesData");
chart.Series[2].SetBinding(ChartSeries.ItemsSourceProperty, "SeriesData");
 

Add the following namespace:

595
Telerik UI for Xamarin

XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
 

Here is how the business model is defined:

C#
public class OhlcDataPoint : NotifyPropertyChangedBase
{
private DateTime category;
private double open;
private double high;
private double low;
private double close;

public DateTime Category


{
get { return this.category; }
set
{
if (value != this.category)
{
this.category = value;
this.OnPropertyChanged();
}
}
}

public double Open


{
get { return this.open; }
set
{
if (value != this.open)
{
this.open = value;
this.OnPropertyChanged();
}
}
}

public double High


{
get { return this.high; }
set
{
if (value != this.high)
{
this.high = value;
this.OnPropertyChanged();
}
}

596
Telerik UI for Xamarin

public double Low


{
get { return this.low; }
set
{
if (value != this.low)
{
this.low = value;
this.OnPropertyChanged();
}
}
}

public double Close


{
get { return this.close; }
set
{
if (value != this.close)
{
this.close = value;
this.OnPropertyChanged();
}
}
}
}
 

And here is the result:

597
Telerik UI for Xamarin

SDK Browser application contains an example that shows how to use the Financial Indicators. You
can find the application in the Examples folder of your local Telerik UI for Xamarin installation.
 

See Also
 Ohlc Series Overview
 Candlestick Series Overview

598
Telerik UI for Xamarin

ChartSelectionBehavior
Overview
ChartSelectionBehavior is responsible for selecting, deselecting and reporting the selection of either
data points or series. In other words, the selection behavior can target data points, series or both if
required.

With R2 2018 SP release Behaviors property of RadChart was replaced with ChartBehaviors.
Behaviors property is marked as obsolete, so please use ChartBehaviors instead.
 

Features
Properties

 DataPointSelectionMode: Gets or sets the ChartSelectionMode that controls the selection


behavior of the data points within the chart series. The available values are:
 None
 Single
 Multiple
 SeriesSelectionMode: Gets or sets the ChartSelectionMode that controls the selection
behavior of the series within the plot area. The available values are:
 None
 Single
 Multiple
 SelectedPoints: Retrieves all the points from all series within the chart plot area that are
currently selected.
 SelectedSeries: Retrieves all the series instances within the plot area that are currently
selected.

Methods

 ClearSelecton() method : Removes the current selection within the chart.

Events

 SelectionChanged event: Occurs when a selection has been made.

Commands
ChartSelectionBehavior exposes support for Commands.

Example

599
Telerik UI for Xamarin

Here is an example of how the Chart Selection Behavior works with Command:

First, create the needed business objects, for example:

C#
public class CategoricalData
{
public object Category { get; set; }

public double Value { get; set; }


}
 

Then create a ViewModel:

C#
public class ViewModel : NotifyPropertyChangedBase
{
private int counter = 0;
private string displayCount;
public ObservableCollection<CategoricalData> Data1 { get; set; }
public ObservableCollection<CategoricalData> Data2 { get; set; }
public ICommand IsSelectionChangedCommand { get; }

public ViewModel()
{
this.Data1 = GetCategoricalData1();
this.Data2 = GetCategoricalData2();
this.IsSelectionChangedCommand = new Command(this.IncreaseCount);
}
public int Counter
{
get
{
return this.counter;
}
set
{
this.counter = value;
this.DisplayCount = $"Command executed {counter} times.";
}
}
public string DisplayCount
{
get
{
return this.displayCount;
}
set
{
if (this.displayCount != value)
{

600
Telerik UI for Xamarin

this.displayCount = value;
this.OnPropertyChanged();
}
}
}

private static ObservableCollection<CategoricalData> GetCategoricalData1()


{
var data = new ObservableCollection<CategoricalData>
{
new CategoricalData { Category = "Greenings", Value = 52 },
new CategoricalData { Category = "Perfecto", Value = 60 },
new CategoricalData { Category = "NearBy", Value = 77 },
new CategoricalData { Category = "Family", Value = 50 },
new CategoricalData { Category = "Fresh", Value = 56 },
};
return data;
}

private static ObservableCollection<CategoricalData> GetCategoricalData2()


{
var data = new ObservableCollection<CategoricalData>
{
new CategoricalData { Category = "Greenings", Value = 33 },
new CategoricalData { Category = "Perfecto", Value = 88 },
new CategoricalData { Category = "NearBy", Value = 61 },
new CategoricalData { Category = "Family", Value = 94 },
new CategoricalData { Category = "Fresh", Value = 72 },
};
return data;
}
private void IncreaseCount()
{
this.Counter++;
}
}
 

Finally, use the following snippet to declare a RadCartesianChart in XAML and in C#:

XAML
<ContentView.BindingContext>
<local:ViewModel/>
</ContentView.BindingContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto" />
<RowDefinition Height="0.3*"/>
</Grid.RowDefinitions>

<telerikChart:RadCartesianChart Grid.Row="0">
<telerikChart:RadCartesianChart.HorizontalAxis>

601
Telerik UI for Xamarin

<telerikChart:CategoricalAxis LabelFitMode="MultiLine" />


</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:NumericalAxis />
</telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:RadCartesianChart.Series>
<telerikChart:BarSeries ValueBinding="Value"
CategoryBinding="Category"
CombineMode="Stack"
StackGroupKey="1"
AllowSelect="True"
ItemsSource="{Binding Data1}" />
<telerikChart:BarSeries ValueBinding="Value"
CategoryBinding="Category"
CombineMode="Stack"
StackGroupKey="1"
AllowSelect="True"
ItemsSource="{Binding Data2}" />
</telerikChart:RadCartesianChart.Series>
<telerikChart:RadCartesianChart.ChartBehaviors>
<telerikChart:ChartSelectionBehavior DataPointSelectionMode="Single"
Command="{Binding IsSelectionChangedCommand}"
SeriesSelectionMode="None" />
</telerikChart:RadCartesianChart.ChartBehaviors>
</telerikChart:RadCartesianChart>

<Label Grid.Row="2" Text="{Binding DisplayCount}"/>


</Grid>
 

C#
var chart = new RadCartesianChart
{
BindingContext = new ViewModel(),
PaletteName = PaletteNames.Light,
SelectionPaletteName = PaletteNames.LightSelected,
HorizontalAxis = new CategoricalAxis()
{
LabelFitMode = AxisLabelFitMode.MultiLine,
},
VerticalAxis = new NumericalAxis(),
Series =
{
new BarSeries
{
ValueBinding = new PropertyNameDataPointBinding("Value"),
CategoryBinding = new PropertyNameDataPointBinding("Category"),
CombineMode = ChartSeriesCombineMode.Stack,
StackGroupKey = 1,
AllowSelect = true
},
new BarSeries
{

602
Telerik UI for Xamarin

ValueBinding = new PropertyNameDataPointBinding("Value"),


CategoryBinding = new PropertyNameDataPointBinding("Category"),
CombineMode = ChartSeriesCombineMode.Stack,
StackGroupKey = 1,
AllowSelect = true
}
},
ChartBehaviors =
{
new ChartSelectionBehavior
{
DataPointSelectionMode = ChartSelectionMode.Single,
SeriesSelectionMode = ChartSelectionMode.None
}
}
};

chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "Data1");
chart.Series[1].SetBinding(ChartSeries.ItemsSourceProperty, "Data2");
 

Where the telerikChart namespace is the following:

XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
 

C#
using Telerik.XamarinForms.Chart;
 

Here is how the selection looks:

603
Telerik UI for Xamarin

A sample Selection example can be found in the Chart/Interactivity folder of the SDK Samples
Browser application.
 

See Also
 Chart Track Ball Behavior
 Chart Tool Tip Behavior
 Chart Pan And Zoom Behavior

604
Telerik UI for Xamarin

ChartTrackBallBehavior
Overview
ChartTrackBallBehavior is responsible for rendering concise information about several data points in
a small popup which displays over its relevant data points. A vertical line is also drawn through the
data points for maximum clarity.

With R2 2018 SP release Behaviors property of RadChart was replaced with ChartBehaviors.
Behaviors property is marked as obsolete, so please use ChartBehaviors instead.
 

Features
 ShowTrackInfo(bool): Determines whether the visual information for all the closest data
points will be displayed.
 ShowIntersectionPoints(bool): Defines a value indicating whether a visual information for all
the closest data points will be displayed.

Example
Here is an example of how the Chart TrackBall Behavior works:

First, create the needed business objects, for example:

C#
public class CategoricalData
{
public object Category { get; set; }

public double Value { get; set; }


}
 

Then create a ViewModel:

C#
public class ViewModel
{
public ObservableCollection<CategoricalData> Data1 { get; set; }
public ObservableCollection<CategoricalData> Data2 { get; set; }

public ViewModel()
{
this.Data1 = GetCategoricalData1();
this.Data2 = GetCategoricalData2();

605
Telerik UI for Xamarin

private static ObservableCollection<CategoricalData> GetCategoricalData1()


{
var data = new ObservableCollection<CategoricalData> {
new CategoricalData { Category = "Greenings", Value = 52 },
new CategoricalData { Category = "Perfecto", Value = 60 },
new CategoricalData { Category = "NearBy", Value = 77 },
new CategoricalData { Category = "Family", Value = 50 },
new CategoricalData { Category = "Fresh", Value = 56 },
};
return data;
}

private static ObservableCollection<CategoricalData> GetCategoricalData2()


{
var data = new ObservableCollection<CategoricalData> {
new CategoricalData { Category = "Greenings", Value = 33 },
new CategoricalData { Category = "Perfecto", Value = 88 },
new CategoricalData { Category = "NearBy", Value = 61 },
new CategoricalData { Category = "Family", Value = 94 },
new CategoricalData { Category = "Fresh", Value = 72 },
};
return data;
}
}
 

Finally, use the following snippet to declare a RadCartesianChart in XAML and in C#:

XAML
<telerikChart:RadCartesianChart>
<telerikChart:RadCartesianChart.BindingContext>
<local:ViewModel />
</telerikChart:RadCartesianChart.BindingContext>
<telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:CategoricalAxis LabelFitMode="MultiLine"
PlotMode="OnTicks" />
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:NumericalAxis />
</telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:RadCartesianChart.Series>
<telerikChart:LineSeries ValueBinding="Value"
CategoryBinding="Category"
DisplayName="Sales 1"
ItemsSource="{Binding Data1}" />
<telerikChart:LineSeries ValueBinding="Value"
CategoryBinding="Category"
DisplayName="Sales 2"
ItemsSource="{Binding Data2}" />
</telerikChart:RadCartesianChart.Series>
<telerikChart:RadCartesianChart.ChartBehaviors>

606
Telerik UI for Xamarin

<telerikChart:ChartTrackBallBehavior ShowIntersectionPoints="True"
ShowTrackInfo="True" />
</telerikChart:RadCartesianChart.ChartBehaviors>
</telerikChart:RadCartesianChart>
 

C#
var chart = new RadCartesianChart
{
BindingContext = new ViewModel(),
HorizontalAxis = new CategoricalAxis()
{
LabelFitMode = AxisLabelFitMode.MultiLine,
PlotMode = AxisPlotMode.OnTicks
},
VerticalAxis = new NumericalAxis(),
Series =
{
new LineSeries
{
ValueBinding = new PropertyNameDataPointBinding("Value"),
CategoryBinding = new PropertyNameDataPointBinding("Category"),
DisplayName = "Sales 1"
},
new LineSeries
{
ValueBinding = new PropertyNameDataPointBinding("Value"),
CategoryBinding = new PropertyNameDataPointBinding("Category"),
DisplayName = "Sales 2"
}
},
ChartBehaviors =
{
new ChartTrackBallBehavior
{
ShowIntersectionPoints = true,
ShowTrackInfo = true
}
}
};

chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "Data1");
chart.Series[1].SetBinding(ChartSeries.ItemsSourceProperty, "Data2");
 

Where the telerikChart namespace is the following:

XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
 

607
Telerik UI for Xamarin

C#
using Telerik.XamarinForms.Chart;
 

Here is how the trackball looks:

A sample TrackBall example can be found in the Chart/Interactivity folder of the SDK Samples
Browser application.
 

See Also
 Chart Selection Behavior
 Chart Tool Tip Behavior
 Chart Pan And Zoom Behavior

608
Telerik UI for Xamarin

ChartToolTipBehavior
Overview
ChartTooltipBehavior is responsible for rendering concise information about a data point in a small
popup which is displayed close to its relevant data point.

With R2 2018 SP release Behaviors property of RadChart was replaced with ChartBehaviors.
Behaviors property is marked as obsolete, so please use ChartBehaviors instead.
 

Features
 TriggerMode: Determines the gestures on which the ChartToolTipBehavior should show a
tool tip. The available values are:
 Tap
 Hold

Example
Here is an example of how the Chart ToolTip Behavior works:

First, create the needed business objects, for example:

C#
public class CategoricalData
{
public object Category { get; set; }

public double Value { get; set; }


}
 

Then create a ViewModel:

C#
public class ViewModel
{
public ObservableCollection<CategoricalData> Data { get; set; }

public ViewModel()
{
this.Data = GetCategoricalData();
}

private static ObservableCollection<CategoricalData> GetCategoricalData()

609
Telerik UI for Xamarin

{
var data = new ObservableCollection<CategoricalData> {
new CategoricalData { Category = "Greenings", Value = 52 },
new CategoricalData { Category = "Perfecto", Value = 60 },
new CategoricalData { Category = "NearBy", Value = 77 },
new CategoricalData { Category = "Family", Value = 50 },
new CategoricalData { Category = "Fresh", Value = 56 },
};
return data;
}
}
 

Finally, use the following snippet to declare a RadCartesianChart in XAML and in C#:

XAML
<telerikChart:RadCartesianChart>
<telerikChart:RadCartesianChart.BindingContext>
<local:ViewModel />
</telerikChart:RadCartesianChart.BindingContext>
<telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:CategoricalAxis LabelFitMode="MultiLine"
PlotMode="OnTicks" />
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:NumericalAxis />
</telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:RadCartesianChart.Series>
<telerikChart:LineSeries ValueBinding="Value"
CategoryBinding="Category"
DisplayName="Sales 1"
ItemsSource="{Binding Data}" />
</telerikChart:RadCartesianChart.Series>
<telerikChart:RadCartesianChart.ChartBehaviors>
<telerikChart:ChartTooltipBehavior TriggerMode="Tap" />
</telerikChart:RadCartesianChart.ChartBehaviors>
</telerikChart:RadCartesianChart>
 

C#
var chart = new RadCartesianChart
{
BindingContext = new ViewModel(),
HorizontalAxis = new CategoricalAxis()
{
LabelFitMode = AxisLabelFitMode.MultiLine,
PlotMode = AxisPlotMode.OnTicks
},
VerticalAxis = new NumericalAxis(),
Series =
{
new LineSeries

610
Telerik UI for Xamarin

{
ValueBinding = new PropertyNameDataPointBinding("Value"),
CategoryBinding = new PropertyNameDataPointBinding("Category"),
DisplayName = "Sales 1"
},
},
ChartBehaviors =
{
new ChartTooltipBehavior
{
TriggerMode = ToolTipTriggerMode.Tap
}
}
};

chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "Data");
 

Where the telerikChart namespace is the following:

XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
 

C#
using Telerik.XamarinForms.Chart;
 

Here is how the tool-tip looks:

611
Telerik UI for Xamarin

A sample ToolTip example can be found in the Chart/Interactivity folder of the SDK Samples Browser
application.
 

See Also
 Chart Selection Behavior
 Chart Track Ball Behavior
 Chart Pan And Zoom Behavior

612
Telerik UI for Xamarin

ChartPanAndZoomBehavior
Overview
With ChartPanAndZoomBehavior, RadChart handles the gestures drag, pinch open and pinch close
which respectively cause panning, zooming in and zooming out of the associated chart plot area.

Features
 ZoomMode: Gets or sets value that specifies how the chart will respond to a zoom gesture.
The available values are:
 None
 Horizontal
 Vertical
 Both
 PanMode: Gets or sets value that specifies how the chart will respond to a pan gesture. The
available values are:
 None
 Horizontal
 Vertical
 Both
 HandleDoubleTap: Determines whether a double-tap gesture will be handled by the behavior
to reset the values of the Zoom and ScrollOffset (Pan) properties of the chart.

With R2 2018 SP release Behaviors property of RadChart was replaced with ChartBehaviors.
Behaviors property is marked as obsolete, so please use ChartBehaviors instead.
 

Example
Here is an example of how the Chart PanAndZoom Behavior works:

First, create the needed business objects, for example:

C#
public class TemporalData
{
public DateTime Date { get; set; }

public double Value { get; set; }


}
 

Then create a ViewModel:

C#

613
Telerik UI for Xamarin

public class ViewModel


{
public ObservableCollection<TemporalData> Data { get; set; }

public ViewModel()
{
this.Data = new ObservableCollection<TemporalData>(GetDateTimeData(200));
}

private static List<TemporalData> GetDateTimeData(int itemsCount)


{
var startDate = new DateTime(2015, 03, 01);

List<TemporalData> items = new List<TemporalData>();


for (int i = 0; i < itemsCount; i++)
{
TemporalData data = new TemporalData();
data.Date = startDate.AddDays(i);

if (i % 2 == 0)
{
data.Value = i + 5;
}
else
{
if (i % 5 == 0)
{
data.Value = i - 15;
}
}

items.Add(data);
}

return items;
}
}
 

Finally, use the following snippet to declare a RadCartesianChart in XAML and in C#:

XAML
<telerikChart:RadCartesianChart PaletteName="Light"
Zoom="2, 1">
<telerikChart:RadCartesianChart.BindingContext>
<local:ViewModel/>
</telerikChart:RadCartesianChart.BindingContext>
<telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:DateTimeContinuousAxis LabelFitMode="Rotate"
MajorStepUnit="Day"
PlotMode="OnTicks"
LabelFormat="dd MMM"
MajorStep="20"

614
Telerik UI for Xamarin

ShowLabels="True"/>
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:NumericalAxis />
</telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:RadCartesianChart.Series>
<telerikChart:LineSeries ValueBinding="Value"
CategoryBinding="Date"
DisplayName="Sales"
ItemsSource="{Binding Data}"/>
</telerikChart:RadCartesianChart.Series>
<telerikChart:RadCartesianChart.ChartBehaviors>
<telerikChart:ChartPanAndZoomBehavior ZoomMode="Horizontal"
PanMode="Horizontal"
HandleDoubleTap="True"/>
</telerikChart:RadCartesianChart.ChartBehaviors>
</telerikChart:RadCartesianChart>
 

C#
var chart = new RadCartesianChart
{
BindingContext = new ViewModel(),
PaletteName = PaletteNames.Light,
HorizontalAxis = new DateTimeContinuousAxis
{
LabelFitMode = AxisLabelFitMode.Rotate,
MajorStepUnit = TimeInterval.Day,
PlotMode = AxisPlotMode.OnTicks,
LabelFormat = "dd MMM",
MajorStep = 20,
ShowLabels = true
},
VerticalAxis = new NumericalAxis(),
Series =
{
new LineSeries
{
ValueBinding = new PropertyNameDataPointBinding("Value"),
CategoryBinding = new PropertyNameDataPointBinding("Date"),
DisplayName = "Sales"
}
},
ChartBehaviors =
{
new ChartPanAndZoomBehavior
{
ZoomMode = ChartPanZoomMode.Horizontal,
PanMode = ChartPanZoomMode.Horizontal,
HandleDoubleTap = true
}
}
};

615
Telerik UI for Xamarin

chart.Zoom = new Size(2, 1);


chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "Data");
 

Where the telerikChart namespace is the following:

XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
 

C#
using Telerik.XamarinForms.Chart;
 

Here is the result:

A sample Pan And Zoom example can be found in the Chart/Interactivity folder of the SDK Samples
Browser application.
 

See Also
 Chart Selection Behavior
 Chart Track Ball Behavior
 Chart Tool Tip Behavior

616
Telerik UI for Xamarin

Annotations
Overview
Annotations are visual elements used to highlight certain areas on the plot. They can be used as
comments or as markers for specific values on the plot. You can practically use any visual element
as a template for the annotation.

RadChart provides support for the following types of annotations:

 Cartesian GridLineAnnotations: this annotation is visually represented by straight lines


across the chart that marks a specific value on the associated Cartesian axis.
 Cartesian PlotBandAnnotations: this annotation is visually represented by a band across the
chart that marks a specific range on the associated Cartesian axis.

CartesianGridLineAnnotation
The CartesianGridLineAnnotation represents a vertical or horizontal line that crosses the entire plot
area.

Features

 Axis : the CartesianGridLineAnnotation should be associated with horizontal or vertical


cartesian axis explicitly.
 Value : the place on the associated axis where a line crosses it.

Note: When the associated axis is numerical - a numeric value is expected, and when it is a
CategoricalAxis - a category is expected.
 

Example
Here is an example of how the CartesianGridLineAnnotation works:

First, create the needed business objects:

C#
public class CategoricalData
{
public object Category { get; set; }

public double Value { get; set; }


}
 

Then create a ViewModel:

617
Telerik UI for Xamarin

C#
public class ViewModel
{
public ObservableCollection<CategoricalData> Data { get; set; }
public double Threshold { get; set; }

public ViewModel()
{
this.Data = GetCategoricalData();
this.Threshold = this.Data.Average(data => data.Value);
}

private static ObservableCollection<CategoricalData> GetCategoricalData()


{
var data = new ObservableCollection<CategoricalData>
{
new CategoricalData { Category = "Greenings", Value = 21 },
new CategoricalData { Category = "Perfecto", Value = 18 },
new CategoricalData { Category = "NearBy", Value = 44 },
new CategoricalData { Category = "Family", Value = 77 },
new CategoricalData { Category = "Fresh", Value = 34 },
};
return data;
}
}
 

Finally, use the following snippet to declare the RadChart in XAML or in C#:

XAML
<telerikChart:RadCartesianChart>
<telerikChart:RadCartesianChart.BindingContext>
<local:ViewModel />
</telerikChart:RadCartesianChart.BindingContext>
<telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:CategoricalAxis LabelFitMode="MultiLine" />
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:NumericalAxis x:Name="verticalAxis" />
</telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:RadCartesianChart.Series>
<telerikChart:BarSeries ValueBinding="Value"
CategoryBinding="Category"
ItemsSource="{Binding Data}" />
</telerikChart:RadCartesianChart.Series>
<telerikChart:RadCartesianChart.Annotations>
<telerikChart:CartesianGridLineAnnotation Stroke="#0E72F6"
StrokeThickness="2"
Axis="{x:Reference verticalAxis}"
Value="{Binding Threshold}">
<telerikChart:CartesianGridLineAnnotation.DashArray>
<x:Array Type="{x:Type x:Double}">

618
Telerik UI for Xamarin

<x:Double>4.0</x:Double>
<x:Double>2.0</x:Double>
</x:Array>
</telerikChart:CartesianGridLineAnnotation.DashArray>
</telerikChart:CartesianGridLineAnnotation>
</telerikChart:RadCartesianChart.Annotations>
</telerikChart:RadCartesianChart>
 

C#
var verticalAxis = new NumericalAxis();
var chart = new RadCartesianChart
{
BindingContext = new ViewModel(),
HorizontalAxis = new CategoricalAxis
{
LabelFitMode = AxisLabelFitMode.MultiLine,
},
VerticalAxis = verticalAxis,
Series =
{
new BarSeries
{
ValueBinding = new PropertyNameDataPointBinding("Value"),
CategoryBinding = new PropertyNameDataPointBinding("Category")
}
},
Annotations =
{
new CartesianGridLineAnnotation
{
Axis = verticalAxis,
StrokeThickness = 2,
Stroke = Color.FromHex("0E72F6"),
DashArray = new[] { 4.0, 2.0 }
}
}
};

chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "Data");
chart.Annotations[0].SetBinding(CartesianGridLineAnnotation.ValueProperty,
"Threshold");
 

Here is how the CartesianGridLineAnnotation looks:

619
Telerik UI for Xamarin

A sample CartesianGridLineAnnotation example can be found in the Chart/Annotations folder of the


SDK Samples Browser application.
 

CartesianPlotBandAnnotation
The CartesianPlotBandAnnotation represents a vertical or horizontal area that crosses the entire plot
area.

Features

 Axis : the cartesian plotband annotation needs to be associated with horizontal or vertical
axis explicitly.
 From : the starting value for the plotband.
 To : the ending value for the plotband.
 Fill : Gets or sets the Fill.

Example
Here is an example of how the CartesianPlotBandAnnotation works:

First, create the needed business objects:

C#
public class CategoricalData
{

620
Telerik UI for Xamarin

public object Category { get; set; }

public double Value { get; set; }


}
 

Then create a ViewModel:

C#
public class ViewModel
{
public ObservableCollection<CategoricalData> Data { get; set; }
public double StartThreshold { get; private set; }
public double EndThreshold { get; private set; }

public ViewModel()
{
this.Data = GetCategoricalData();
var threshold = this.Data.Average(data => data.Value);
this.StartThreshold = threshold * 0.9;
this.EndThreshold = threshold * 1.1;
}

private static ObservableCollection<CategoricalData> GetCategoricalData()


{
var data = new ObservableCollection<CategoricalData>
{
new CategoricalData { Category = "Greenings", Value = 66 },
new CategoricalData { Category = "Perfecto", Value = 19 },
new CategoricalData { Category = "NearBy", Value = 92 },
new CategoricalData { Category = "Family", Value = 23 },
new CategoricalData { Category = "Fresh", Value = 56 },
};
return data;
}
}
 

Finally, use the following snippet to declare the RadChart control in XAML or in C#:

XAML
<telerikChart:RadCartesianChart>
<telerikChart:RadCartesianChart.BindingContext>
<local:ViewModel />
</telerikChart:RadCartesianChart.BindingContext>
<telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:CategoricalAxis LabelFitMode="MultiLine"
PlotMode="OnTicks" />
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:NumericalAxis x:Name="verticalAxis" />
</telerikChart:RadCartesianChart.VerticalAxis>

621
Telerik UI for Xamarin

<telerikChart:RadCartesianChart.Series>
<telerikChart:LineSeries ValueBinding="Value"
CategoryBinding="Category"
ItemsSource="{Binding Data}" />
</telerikChart:RadCartesianChart.Series>
<telerikChart:RadCartesianChart.Annotations>
<telerikChart:CartesianPlotBandAnnotation StrokeThickness="2"
Stroke="Green"
Fill="#2F66FF33"
Axis="{x:Reference verticalAxis}"
From="{Binding StartThreshold}"
To="{Binding EndThreshold}" />
</telerikChart:RadCartesianChart.Annotations>
</telerikChart:RadCartesianChart>
 

C#
var verticalAxis = new NumericalAxis();
var chart = new RadCartesianChart
{
BindingContext = new ViewModel(),
HorizontalAxis = new CategoricalAxis
{
LabelFitMode = AxisLabelFitMode.MultiLine,
PlotMode = AxisPlotMode.OnTicks
},
VerticalAxis = verticalAxis,
Series =
{
new LineSeries
{
ValueBinding = new PropertyNameDataPointBinding("Value"),
CategoryBinding = new PropertyNameDataPointBinding("Category")
}
},
Annotations =
{
new CartesianPlotBandAnnotation()
{
Axis = verticalAxis,
StrokeThickness = 2,
Stroke = Color.Green,
Fill = Color.FromHex("2F66FF33")
}
}
};

chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "Data");
chart.Annotations[0].SetBinding(CartesianPlotBandAnnotation.FromProperty,
"StartThreshold");
chart.Annotations[0].SetBinding(CartesianPlotBandAnnotation.ToProperty,
"EndThreshold");
 

622
Telerik UI for Xamarin

Here is how the CartesianPlotBandAnnotation looks:

A sample CartesianPlotBandAnnotation example can be found in the Chart/Annotations folder of the


SDK Samples Browser application.
 

See Also
 CartesianChart Grid
 Chart Legend
 Chart Null Values

623
Telerik UI for Xamarin

CartesianChartGrid
Overview
The CartesianChartGrid represents a decoration over the plot area of RadCartesianChart. It adds
major lines connected to each Major tick of each axis. You can set a new grid through the
RadCartesianChart.Grid property.

Features
 MajorLinesVisibility : Gets or sets the visibility of major grid lines. In other means : a line that
extends the major ticks throughout the plot area.
 MajorLineThickness: Gets or sets the thickness of the Major Grid Lines.
 MajorLineColor: Gets or sets the color the of Major Grid Lines.
 MajorXLineDashArray : Gets or sets a collection of Double values that indicates the pattern
of dashes and gaps that is used to outline Major X Grid Line.
 MajorYLineDashArray: Gets or sets a collection of Double values that indicates the pattern of
dashes and gaps that is used to outline Major Y Grid Line.
 StripeLinesVisibility: Gets or sets the visibility of the grid stripes. In other means : the area
between two grid lines.
 YStripeColor : Gets or sets the color of the area between two major ticks of the Vertical Axis.
This color alternates with the YStripeAlternativeColor starting from the first area.
 YStripeAlternativeColor : Gets or sets the color of the area between two major ticks of the
Vertical Axis. This color alternates with the YStripeColor starting from the second area.
 XStripeColor: Gets or sets the color of the area between two major ticks of the Horizontal
Axis. This color alternates with the XStripeAlternativeColor starting from the first area.
 XStripeAlternativeColor: Gets or sets the color of the area between two major ticks of the
Horizontal Axis. This color alternates with the XStripeAlternativeColor starting from the
second area.

Example
Here is an example how the CartesianChartGrid works:

First, create the needed business objects:

C#
public class CategoricalData
{
public object Category { get; set; }

public double Value { get; set; }


}
 

Then create a ViewModel:

624
Telerik UI for Xamarin

C#
public class ViewModel
{
public ObservableCollection<CategoricalData> Data { get; set; }

public ViewModel()
{
this.Data = GetCategoricalData();
}

private static ObservableCollection<CategoricalData> GetCategoricalData()


{
var data = new ObservableCollection<CategoricalData>
{
new CategoricalData { Category = "Greenings", Value = 21 },
new CategoricalData { Category = "Perfecto", Value = 44 },
new CategoricalData { Category = "NearBy", Value = 39 },
new CategoricalData { Category = "Family", Value = 11 },
new CategoricalData { Category = "Fresh", Value = 83 },
};
return data;
}
}
 

Finally, use the following snippet to declare the RadChart in XAML or in C#:

XAML
<telerikChart:RadCartesianChart>
<telerikChart:RadCartesianChart.BindingContext>
<local:ViewModel />
</telerikChart:RadCartesianChart.BindingContext>
<telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:NumericalAxis />
</telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:CategoricalAxis LabelFitMode="MultiLine" />
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.Series>
<telerikChart:BarSeries ValueBinding="Value"
CategoryBinding="Category"
ItemsSource="{Binding Data}" />
</telerikChart:RadCartesianChart.Series>
<telerikChart:RadCartesianChart.Grid>
<telerikChart:CartesianChartGrid StripLinesVisibility="Y"
MajorLinesVisibility="XY"
MajorLineColor="LightGreen"
MajorLineThickness="3" />
</telerikChart:RadCartesianChart.Grid>
</telerikChart:RadCartesianChart>
 

625
Telerik UI for Xamarin

C#
var chart = new RadCartesianChart
{
BindingContext = new ViewModel(),
VerticalAxis = new NumericalAxis(),
HorizontalAxis = new CategoricalAxis()
{
LabelFitMode = AxisLabelFitMode.MultiLine
},
Series =
{
new BarSeries
{
ValueBinding = new PropertyNameDataPointBinding("Value"),
CategoryBinding = new PropertyNameDataPointBinding("Category")
}
},
Grid = new CartesianChartGrid
{
StripLinesVisibility = GridLineVisibility.Y,
MajorLinesVisibility = GridLineVisibility.XY,
MajorLineColor = Color.LightGreen,
MajorLineThickness = 3
}
};

chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "Data");
 

Here is how the CartesianGridLineAnnotation looks:

626
Telerik UI for Xamarin

A sample Glid Lines example can be found in the Chart/Customization folder of the SDK Samples
Browser application.
 

See Also
 Chart Annotations
 Chart Legend
 Chart Null Values

627
Telerik UI for Xamarin

Chart Legend
The Legend feature of the RadChart makes it easy for you to provide description regarding the
series which are visualized within the control. In order to add the legend feature in your application,
you need to initialize a new object of type RadLegend.

Chart Legend definition:

XAML
<telerikChart:RadPieChart x:Name="pieChart" HeightRequest="300">
<telerikChart:RadCartesianChart.BindingContext>
<local:ViewModel />
</telerikChart:RadCartesianChart.BindingContext>
<telerikChart:RadPieChart.Series>
<telerikChart:PieSeries DisplayName="Value" LegendTitleBinding="Category"
ItemsSource="{Binding Data1}" ValueBinding="Value"/>
</telerikChart:RadPieChart.Series>
</telerikChart:RadPieChart>
<telerikChart:RadLegend HeightRequest="200"
LegendItemFontColor="DarkGreen"
LegendItemFontSize="20"
LegendProvider="{x:Reference Name=pieChart}"/>
 

C#
var chart = new RadPieChart
{
BindingContext = new ViewModel(),
HeightRequest = 300
};
var series = new PieSeries
{
ValueBinding = new PropertyNameDataPointBinding("Value"),
DisplayName = "Value",
LegendTitleBinding = new PropertyNameDataPointBinding("Category")
};
series.SetBinding(ChartSeries.ItemsSourceProperty, new Binding("Data1"));
chart.Series.Add(series);

var legend = new RadLegend


{
LegendProvider = chart,
HeightRequest = 200,
LegendItemFontColor = Color.DarkGreen,
LegendItemFontSize = 20
};
 

Figure 1: RadLegend in combination with PieChart

628
Telerik UI for Xamarin

As shown in Figure 1, each item within the RadLegend represents particular series. The most
important property which you need to set is the LegendProvider. It should point to the chart object
whose series will be included in the legend.

Here are the most important properties of the RadLegend control. In brackets is commented the type
of the property:

 LegendProvider(RadChartBase): The Chart control whose series will be described in the


legend.
 LegendItemFontSize(double): The size of the item's title text.
 LegendItemFontColor(Color): The color of the item's title text.
 LegendItemIconSize(Size): The size of the title icons.
 Orientation(LegendOrientation): Sets the orientation of the legend. Can be Horizontal or
Vertical.

The control can be used in combination with RadCartesianChart as well.

XAML
<telerikChart:RadCartesianChart x:Name="chart" HeightRequest="300">
<telerikChart:RadCartesianChart.BindingContext>
<local:ViewModel />
</telerikChart:RadCartesianChart.BindingContext>
<telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:CategoricalAxis />
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:NumericalAxis />
</telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:RadCartesianChart.Series>

629
Telerik UI for Xamarin

<telerikChart:LineSeries CategoryBinding="Category"
ValueBinding="Value"
DisplayName=" Data1"
ItemsSource="{Binding Data1}" />
<telerikChart:LineSeries CategoryBinding="Category"
ValueBinding="Value"
DisplayName=" Data2"
ItemsSource="{Binding Data2}" />
<telerikChart:LineSeries CategoryBinding="Category"
ValueBinding="Value"
DisplayName=" Data3"
ItemsSource="{Binding Data3}" />
</telerikChart:RadCartesianChart.Series>
</telerikChart:RadCartesianChart>
<telerikChart:RadLegend LegendProvider="{x:Reference Name=chart}"
LegendItemFontColor="DarkGreen"
HeightRequest="200"/>
 

C#
var chart = new RadCartesianChart
{
HorizontalAxis = new CategoricalAxis(),
VerticalAxis = new NumericalAxis(),
BindingContext = new ViewModel(),
HeightRequest = 300
};

var seriesData1 = new LineSeries


{
CategoryBinding = new PropertyNameDataPointBinding("Category"),
ValueBinding = new PropertyNameDataPointBinding("Value"),
DisplayName = "Data1"
};

seriesData1.SetBinding(ChartSeries.ItemsSourceProperty, new Binding("Data1"));


chart.Series.Add(seriesData1);

var seriesData2 = new LineSeries


{
CategoryBinding = new PropertyNameDataPointBinding("Category"),
ValueBinding = new PropertyNameDataPointBinding("Value"),
DisplayName = "Data2"
};

seriesData2.SetBinding(ChartSeries.ItemsSourceProperty, new Binding("Data2"));


chart.Series.Add(seriesData2);

var seriesData3 = new LineSeries


{
CategoryBinding = new PropertyNameDataPointBinding("Category"),
ValueBinding = new PropertyNameDataPointBinding("Value"),
DisplayName = "Data3"

630
Telerik UI for Xamarin

};

seriesData3.SetBinding(ChartSeries.ItemsSourceProperty, new Binding("Data3"));


chart.Series.Add(seriesData3);

var legend = new RadLegend


{
LegendProvider = chart,
HeightRequest = 200,
LegendItemFontColor = Color.DarkGreen,
Orientation = LegendOrientation.Vertical
};
 

Figure 2: RadLegend in combination with CartesianChart

LegendTitleBinding
The LegendTitleBinding is a property which can be set specifically for the PieSeries. It points to the
property of the data item which will be used as a title in the legend. For all other series, the
DisplayName property will be used instead.

XAML
<telerikChart:RadPieChart.Series>
<telerikChart:PieSeries DisplayName="Value" LegendTitleBinding="Category"
ItemsSource="{Binding Data1}" ValueBinding="Value"/>
</telerikChart:RadPieChart.Series>
 

631
Telerik UI for Xamarin

C#
var series = new PieSeries
{
ValueBinding = new PropertyNameDataPointBinding("Value"),
DisplayName = "Value",
LegendTitleBinding = new PropertyNameDataPointBinding("Category")
};
 

See Also
 CartesianChartGrid
 Annotations

632
Telerik UI for Xamarin

Null Values
There are many scenarios, in which some of the data points visualized in RadChart contain
empty/null values. These are the cases when data is not available for some records from the used
dataset.In cases of CartesianSeries that require X and Y axes (line, area, bar, etc), RadChart
represents null data points with an empty space or gap. In case of other chart types (pie, donut)
these data points are not visualized.

The following example demonstrates a databound scenario where nullable double type is used.

First, create a ViewModel with a collection of CategoryItems objects, where a few of the items have
null values:

C#
public class ViewModel
{
public ViewModel()
{
this.Data = new ObservableCollection<CategoryItem>()
{
new CategoryItem { Category = "A" },
new CategoryItem { Category = "B", Value = 70 },
new CategoryItem { Category = "C", Value = 80 },
new CategoryItem { Category = "D", Value = 50 },
new CategoryItem { Category = "E", Value = 40 },
new CategoryItem { Category = "F" },
new CategoryItem { Category = "G" },
new CategoryItem { Category = "H", Value = 30 },
new CategoryItem { Category = "I", Value = 60 },
new CategoryItem { Category = "J", Value = 80 },
new CategoryItem { Category = "K", Value = 85 },
new CategoryItem { Category = "L", Value = 90 }
};
}

public ObservableCollection<CategoryItem> Data { get; private set; }


}

public class CategoryItem


{
public string Category { get; set; }
public double? Value { get; set; }
}
 

Then, add RadCartesianChart with SplineAreaSeries, for example:

XAML
<telerikChart:RadCartesianChart>

633
Telerik UI for Xamarin

<telerikChart:RadCartesianChart.BindingContext>
<local:ViewModel />
</telerikChart:RadCartesianChart.BindingContext>
<telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:CategoricalAxis />
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:NumericalAxis Minimum="0" Maximum="100" />
</telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:RadCartesianChart.Series>
<telerikChart:SplineAreaSeries ValueBinding="Value"
CategoryBinding="Category"
ItemsSource="{Binding Data}" />
</telerikChart:RadCartesianChart.Series>
</telerikChart:RadCartesianChart>
 

The image below shows how the null data points are visualized as gaps.

See Also
 Series Overview

634
Telerik UI for Xamarin

Custom Chart Palette


When you need to define custom sets of colors for the Chart series, you can take advantage of
custom palettes. RadChart exposes the following properties for setting custom ChartPalettes:

 Palette (of type ChartPalette): Defines the default appearance of the Chart series/data
points.
 SelectionPalette (of type ChartPalette): Defines the appearance of the Chart series/data
points when selected.

Both properties should be set to a ChartPalette instance. The ChartPalette holds a collection of
PaletteEntry objects where each PaletteEntry has FillColor and StrokeColor properties, thus defining
the visual appearance of each series/data points of the Chart.

For SelectionPalette you'd need to add the SelectionBehavior to the ChartBehaviors collection of the
Chart instance. For more details on this refer to Chart SelectionBehavior topic.
 

Example
Here is an example how to create a CartesianChart with custom palettes:

First, create the needed business model:

C#
public class CategoricalData
{
public object Category { get; set; }

public double Value { get; set; }


}
 

And here is the sample data used as binding context:

C#
public class ViewModel
{
public ViewModel()
{
this.Data1 = GetCategoricalData1();
this.Data2 = GetCategoricalData2();
this.Data3 = GetCategoricalData3();
}

public ObservableCollection<CategoricalData> Data1 { get; set; }

public ObservableCollection<CategoricalData> Data2 { get; set; }

635
Telerik UI for Xamarin

public ObservableCollection<CategoricalData> Data3 { get; set; }

private static ObservableCollection<CategoricalData> GetCategoricalData1()


{
var data = new ObservableCollection<CategoricalData> {
new CategoricalData { Category = "A", Value = 0.63 },
new CategoricalData { Category = "B", Value = 0.85 },
new CategoricalData { Category = "C", Value = 1.05 },
new CategoricalData { Category = "D", Value = 0.96 },
new CategoricalData { Category = "E", Value = 1.1 },
};
return data;
}

private static ObservableCollection<CategoricalData> GetCategoricalData2()


{
var data = new ObservableCollection<CategoricalData> {
new CategoricalData { Category = "A", Value = 0.23 },
new CategoricalData { Category = "B", Value = 0.35 },
new CategoricalData { Category = "C", Value = 0.55 },
new CategoricalData { Category = "D", Value = 0.66 },
new CategoricalData { Category = "E", Value = 0.77 },
};
return data;
}

private static ObservableCollection<CategoricalData> GetCategoricalData3()


{
var data = new ObservableCollection<CategoricalData> {
new CategoricalData { Category = "A", Value = 1.63 },
new CategoricalData { Category = "B", Value = 1.85 },
new CategoricalData { Category = "C", Value = 2.05 },
new CategoricalData { Category = "D", Value = 1.96 },
new CategoricalData { Category = "E", Value = 1.78 },
};
return data;
}
}
 

Finally, declare the RadCartesianChart in XAML or C#:

XAML
<telerikChart:RadCartesianChart>
<telerikChart:RadCartesianChart.BindingContext>
<local:ViewModel />
</telerikChart:RadCartesianChart.BindingContext>
<telerikChart:RadCartesianChart.ChartBehaviors>
<telerikChart:ChartSelectionBehavior DataPointSelectionMode="None"
SeriesSelectionMode="Single" />
</telerikChart:RadCartesianChart.ChartBehaviors>
<telerikChart:RadCartesianChart.VerticalAxis>

636
Telerik UI for Xamarin

<telerikChart:NumericalAxis />
</telerikChart:RadCartesianChart.VerticalAxis>
<telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:CategoricalAxis LabelFitMode="MultiLine" />
</telerikChart:RadCartesianChart.HorizontalAxis>
<telerikChart:RadCartesianChart.Series>
<telerikChart:BarSeries ValueBinding="Value"
CategoryBinding="Category"
CombineMode="Cluster"
ItemsSource="{Binding Data1}" />
<telerikChart:BarSeries ValueBinding="Value"
CategoryBinding="Category"
CombineMode="Cluster"
ItemsSource="{Binding Data2}" />
<telerikChart:BarSeries ValueBinding="Value"
CategoryBinding="Category"
CombineMode="Cluster"
ItemsSource="{Binding Data3}" />
</telerikChart:RadCartesianChart.Series>
<telerikChart:RadCartesianChart.Palette>
<telerikChart:ChartPalette>
<telerikChart:ChartPalette.Entries>
<telerikChart:PaletteEntry FillColor="#4FB6E7" StrokeColor="#4FB6E7" />
<telerikChart:PaletteEntry FillColor="#A666CE" StrokeColor="#A666CE" />
<telerikChart:PaletteEntry FillColor="#9DCC00" StrokeColor="#9DCC00" />
</telerikChart:ChartPalette.Entries>
</telerikChart:ChartPalette>
</telerikChart:RadCartesianChart.Palette>
<telerikChart:RadCartesianChart.SelectionPalette>
<telerikChart:ChartPalette>
<telerikChart:ChartPalette.Entries>
<telerikChart:PaletteEntry FillColor="#4FB6E7" StrokeColor="#4D4D4D" />
<telerikChart:PaletteEntry FillColor="#A666CE" StrokeColor="#4D4D4D" />
<telerikChart:PaletteEntry FillColor="#9DCC00" StrokeColor="#4D4D4D" />
</telerikChart:ChartPalette.Entries>
</telerikChart:ChartPalette>
</telerikChart:RadCartesianChart.SelectionPalette>
</telerikChart:RadCartesianChart>
 

C#
var chart = new RadCartesianChart
{
BindingContext = new ViewModel(),
VerticalAxis = new NumericalAxis(),
HorizontalAxis = new CategoricalAxis
{
LabelFitMode = AxisLabelFitMode.MultiLine
},
Series =
{
new BarSeries
{

637
Telerik UI for Xamarin

CombineMode = ChartSeriesCombineMode.Cluster,
ValueBinding = new PropertyNameDataPointBinding("Value"),
CategoryBinding = new PropertyNameDataPointBinding("Category")
},
new BarSeries
{
CombineMode = ChartSeriesCombineMode.Cluster,
ValueBinding = new PropertyNameDataPointBinding("Value"),
CategoryBinding = new PropertyNameDataPointBinding("Category")
},
new BarSeries
{
CombineMode = ChartSeriesCombineMode.Cluster,
ValueBinding = new PropertyNameDataPointBinding("Value"),
CategoryBinding = new PropertyNameDataPointBinding("Category")
},
},
Palette = new ChartPalette
{
Entries =
{
new PaletteEntry(Color.FromHex("#4FB6E7"), Color.FromHex("#4FB6E7")),
new PaletteEntry(Color.FromHex("#A666CE"), Color.FromHex("#A666CE")),
new PaletteEntry(Color.FromHex("#9DCC00"), Color.FromHex("#9DCC00"))
}
},
SelectionPalette = new ChartPalette
{
Entries =
{
new PaletteEntry(Color.FromHex("#4FB6E7"), Color.FromHex("#4D4D4D")),
new PaletteEntry(Color.FromHex("#A666CE"), Color.FromHex("#4D4D4D")),
new PaletteEntry(Color.FromHex("#9DCC00"), Color.FromHex("#4D4D4D"))
}
}
};

chart.ChartBehaviors.Add(new ChartSelectionBehavior { DataPointSelectionMode =


ChartSelectionMode.None, SeriesSelectionMode = ChartSelectionMode.Single});
chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "Data1");
chart.Series[1].SetBinding(ChartSeries.ItemsSourceProperty, "Data2");
chart.Series[2].SetBinding(ChartSeries.ItemsSourceProperty, "Data3");
 

Here is the result:

638
Telerik UI for Xamarin

See Also
 Chart SelectionBehavior
 Categorical Series Combine Mode
 Chart Legend

639
Telerik UI for Xamarin

Register the RadChart renderer


When certain features are available in the native control on a given platform, but not exposed in
Xamarin.Forms you would need to create a custom renderer. This will allow you to access the native
control and configure it as per your needs.

This article will guide you how to register custom renderer for RadChart control.

You will need to create a class for each platform and register your custom renderer using the
ExportRenderer assembly level attribute.

GradientBars example demonstrates how to create custom renderer for each platform and it can be
found in the Chart/Customization folder of the SDK Samples Browser application.
 

Android Project
Register custom renderer for CartesianChart.

C#
[assembly: ExportRenderer(typeof(Telerik.XamarinForms.Chart.RadCartesianChart),
typeof(Telerik.XamarinForms.ChartRenderer.Android.CartesianChartRenderer))]
 

Register custom renderer for PieChart

C#
[assembly: ExportRenderer(typeof(Telerik.XamarinForms.Chart.RadPieChart),
typeof(Telerik.XamarinForms.ChartRenderer.Android.PieChartRenderer))]
 

See the native Android RadChartView documentation for more information.


 

iOS Project
Register custom renderer for CartesianChart

C#
[assembly: ExportRenderer(typeof(Telerik.XamarinForms.Chart.RadCartesianChart),
typeof(Telerik.XamarinForms.ChartRenderer.iOS.CartesianChartRenderer))]
 

Register custom renderer for PieChart

C#

640
Telerik UI for Xamarin

[assembly: ExportRenderer(typeof(Telerik.XamarinForms.Chart.RadPieChart),
typeof(Telerik.XamarinForms.ChartRenderer.iOS.PieChartRenderer))]
 

See the native iOS TKChart documentation for more information.


 

UWP Projects
Register custom renderer for CartesianChart

C#
[assembly:
Xamarin.Forms.Platform.UWP.ExportRenderer(typeof(Telerik.XamarinForms.Chart.RadCartesi
anChart), typeof(Telerik.XamarinForms.ChartRenderer.UWP.CartesianChartRenderer))]
 

Register custom renderer for PieChart

C#
[assembly:
Xamarin.Forms.Platform.UWP.ExportRenderer(typeof(Telerik.XamarinForms.Chart.RadPieChar
t), typeof(Telerik.XamarinForms.ChartRenderer.UWP.PieChartRenderer))]
 

See the native UWP RadChart documentation for more information.


 

See Also
 How To Create Custom Renderer
 Categorical Series Combine Mode
 Chart Legend

641
Telerik UI for Xamarin

Example
Let us consider the following example: we need to apply animation to LineSeries in iOS. Create a
class which inherits from Telerik.XamarinForms.ChartRenderer.iOS.CartesianChartRenderer and
override the UpdateNativeWidget and CreateChartDelegate methods:

C#
public class LineWithAnimationRenderer : CartesianChartRenderer
{
public LineWithAnimationRenderer()
{
}

protected override void UpdateNativeWidget()


{
base.UpdateNativeWidget();
this.Control.AllowAnimations = true;
}

protected override TKChartDelegate CreateChartDelegate(RadCartesianChart chart)


{
return new ChartWithAnimationDelegate(chart);
}
}
 

UpdateNativeWidget method takes care of allowing animations for the chart. CreateChartDelegate
supplies an instance of a class that inherits from TKChartDelegate, configured with animations as
per the iOS chart help. ChartWithAnimationDelegate inherits from
Telerik.XamarinForms.ChartRenderer.iOS.CartesianChartDelegate, which in turn inherits from
TKChartdelegate. This way you only need to extend it with the desired features:

C#
public class ChartWithAnimationDelegate : CartesianChartDelegate
{
public ChartWithAnimationDelegate()
{
}

public override CAAnimation AnimationForSeries(TKChart chart, TKChartSeries


series, TKChartSeriesRenderState state, CGRect rect)
{
var duration = 0.0;
var animations = new List<CAAnimation>();
for (int i = 0; i < (int)state.Points.Count; i++)
{
var pointKeyPath = state.AnimationKeyPathForPointAtIndex((uint)i);
var keyPath = pointKeyPath + ".y";
var point = state.Points.ObjectAtIndex((uint)i) as TKChartVisualPoint;
var oldY = rect.Size.Height;

642
Telerik UI for Xamarin

if (i > 0)
{
var animation = new CAKeyFrameAnimation();
animation.KeyPath = keyPath;
animation.Duration = (double)(0.1 * i );
animation.Values = new NSNumber[] { new NSNumber(oldY), new NSNumber(oldY), new
NSNumber(point.Y) };
animation.KeyTimes = new NSNumber[] { new NSNumber(0), new NSNumber(i / (i +
1.0)), new NSNumber(1.0) };
animations.Add(animation);
duration = animation.Duration;
}
else
{
var animation = new CABasicAnimation();
animation.KeyPath = keyPath;
animation.From = new NSNumber(oldY);
animation.To = new NSNumber(point.Y);
animation.Duration = 0.1;
animations.Add(animation);
}
}

var group = new CAAnimationGroup();


group.Duration = duration;
group.Animations = animations.ToArray();
return group;
}
}
chart.Palette = CustomPalettes.CustomDark;
 

Now you only need to register your custom renderer using the ExportRenderer assembly level
attribute:

C#
[assembly:
Xamarin.Forms.ExportRenderer(typeof(Telerik.XamarinForms.Chart.RadCartesianChart),
typeof(LineWithAnimationRenderer))]
 

See Also
 Categorical Series Combine Mode
 Chart Legend
 How To Create Custom Renderer

643
Telerik UI for Xamarin

Overview
Telerik RadCheckBox for Xamarin is a checkbox control which enables users to make a choice
between two mutually exclusive options. The user’s selection is indicated by a check mark, and
when a user clicks the checkbox its appearance and state change.

Figure 1: RadCheckBox Overview

Key features
 Indeterminate state support: RadCheckBox provides an additional indeterminate state which
indicates the control is neither checked nor unchecked, for more details go here.
 Color customization: You will be able to set various Color properties to make changes to the
look of different parts of the CheckBox control, check here for more details.
 Stroke Width customization: You will have the option to customize the layout of the
CheckBox, including the borders and the check mark, read more here.
 Different sizes: You will be able to set the dimension of the CheckBox by adjusting only one
property - the Length property, check the details here.
 Commands support: CheckBox exposes a Commands collection that allows you to register
custom commands with each control’s instance, read more here.
 Theming Support: RadCheckBox comes with built-in theming support that allows you to
easily build slick interfaces with the look-and-feel of a predefined theme. See the Theme
color keys here

See Also
 Getting Started
 CheckBox Styling

644
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadCheckBox control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadCheckBox control

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadCheckBox control you have to install the
Telerik.UI.for.Xamarin.Primitives nuget package. This nuget will automatically refer the
Telerik.UI.for.Xamarin.Common and Telerik.UI.for.Xamarin.SkiaSharp nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadCheckBox component:

Platform Assemblies
Portable Telerik.XamarinForms.Primitives.dll
Android Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Primitives.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Primitives.dll
UWP Telerik.Core.dll
Telerik.UI.Xaml.Primitives.UWP.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll

3. Adding RadCheckBox control

645
Telerik UI for Xamarin

You could use one of the following approaches:

Drag the control from the Toolbox.

Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML or C#.

The snippet below shows a simple RadCheckBox definition:

XAML
<StackLayout Orientation="Horizontal">
<telerikPrimitives:RadCheckBox x:Name="checkbox" />
<Label Text="Agree to the Terms &amp; Conditions" />
</StackLayout>
 

C#
var mainLayout = new StackLayout() { Orientation = StackOrientation.Horizontal };
mainLayout.Children.Add(new RadCheckBox());
mainLayout.Children.Add(new Label() { Text = "Agree to the Terms & Conditions"});
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
 

C#
using Telerik.XamarinForms.Primitives;
 

Here is the result:

646
Telerik UI for Xamarin

SDK Browser and QSF applications contain different examples that show RadCheckBox's main
features. You can find the applications in the Examples and QSF folders of your local Telerik UI for
Xamarin installation.
 

See Also
 Key Features

647
Telerik UI for Xamarin

Key Features
The purpose of this help article is to show you the key features of the RadCheckBox control.

CheckBox States
RadCheckBox provides three states – Checked, Unchecked and Indeterminate. The state is
controlled through the IsChecked property which is of type bool?. All the states could be set either
through the UI or programmatically ( Indeterminate could be applied through UI only for three-state
checkboxes).

 Checked/Unchecked state - when IsChecked is true/false respectively;


 Indeterminate state - when IsChecked is null;
 IsThreeState (bool) - Defines whether the Indeterminate state could be applied through the
UI. When IsThreeState is true it allows the end user to go to Indeterminate state along with
the Checked and Unchecked states. The default value is false.

The default value of IsChecked is false.

Here is an example how you can set the Indeterminate state through the UI when IsThreeState is
true:

XAML
<telerikPrimitives:RadCheckBox x:Name="checkboxIsChecked" IsChecked="{Binding
IsChecked}" IsThreeState="True" />
 

and the ViewModel:

C#
public class ViewModel : NotifyPropertyChangedBase
{
private bool? isChecked;

public bool? IsChecked


{
get { return this.isChecked; }
set
{
if (this.isChecked != value)
{
this.isChecked = value;
OnPropertyChanged();
}
}
}
}
 

648
Telerik UI for Xamarin

CheckBox Length
The width and height of the checkbox is controlled through the Length property and maintains a 1:1
aspect ratio.

Here is an example of setting the Length value:

XAML
<telerikPrimitives:RadCheckBox x:Name="checkboxLength" Length="40" StrokeWidth="5"/>
 

Stroke Thickness
The RadCheckBox control exposes a StrokeWidth property that specifies the width of the lines with
which the Checkbox element is drawn. It affects the border of the control as well as the check mark.

Here is an example how you can apply a StrokeWidth value:

XAML
<telerikPrimitives:RadCheckBox x:Name="checkboxStrokeWidth" StrokeWidth="5"/>
 

Example
Here is the result at runtime showing the above Indeterminate state as well as StrokeWidth and
Length examples:

649
Telerik UI for Xamarin

RadCheckBox follows the guidelines of the operating system, meaning that on iOS it is visualized as
circle and on Android and UWP - as square.
 

See Also
 CheckBox Getting Started
 CheckBox Styling

650
Telerik UI for Xamarin

Commands
RadCheckBox exposes a Commands collection that allows you to register custom commands with
each control’s instance through the Commands property:

 Commands: Gets the collection with all the custom commands registered with the
CommandService.

Command Type
There are two types of commands:

 CheckBoxCommand: All the default commands within RadCheckBox derive from the base
RadCheckBoxCommand. Think of this command as a UI-related command as it operates
over the RadCheckBox instance that owns the command.
 CheckBoxUserCommand: This type of command should be used when you would like to
modify the behavior of the control on any of the available actions. It exposes the following
properties:
 Id: The key that relates a command instance to a particular action/routine.
 Command: Gets or sets the generic ICommand implementation.
 SuppressDefaultCommand: Gets or sets a value indicating whether the default(built-in)
UI command associated with the specified Id will be executed.

Example
Here is an example how to create a sample CheckBoxUserCommand.

Add the RadCheckBox control and bound the IsCheckedChangedCommand through the
CheckBoxUserCommand predefined command. Use the Id property to map the command to the
corresponding action with the control. In the following example we set the Id property to the
IsCheckedChanged CommandId Enumeration.

XAML
<telerikPrimitives:RadCheckBox x:Name="checkbox"
VerticalOptions="Start"
HorizontalOptions="Center">
<telerikPrimitives:RadCheckBox.Commands>
<checkBoxComamnds:CheckBoxUserCommand Id="IsCheckedChanged"
Command="{Binding IsCheckedChangedCommand}"
SuppressDefaultCommand="True"/>
</telerikPrimitives:RadCheckBox.Commands>
</telerikPrimitives:RadCheckBox>
<Label Text="Select that option" />
 

use the following namespace:

651
Telerik UI for Xamarin

XAML
xmlns:checkBoxComamnds="clr-namespace:Telerik.XamarinForms.Primitives.CheckBox.Command
s;assembly=Telerik.XamarinForms.Primitives"
 

And lets handle the needed command in a sample ViewModel class - define the
IsCheckedChangedCommand and create methods for CanExecute and Execute:

C#
public class ViewModel
{
public ViewModel()
{
this.IsCheckedChangedCommand = new Command((p) =>
IsCheckedChangedCommandExecute(p), (p) => IsCheckedChangedCommandCanExecute(p));
}

public ICommand IsCheckedChangedCommand { get; set; }

private bool IsCheckedChangedCommandCanExecute(object p)


{
return true;
}

private void IsCheckedChangedCommandExecute(object p)


{
var context = p as CheckBoxIsCheckChangedCommandContext;
if (context.NewState == true)
{
Application.Current.MainPage.DisplayAlert("Message", "Option selected", "OK");
}
else
{
Application.Current.MainPage.DisplayAlert("Message", "You've unselected that
option", "OK");
}
}
}
 

The last step is to set the ViewModel class as a BindingContext of the page:

C#
this.BindingContext = new ViewModel();
 

See Also
 Key Features

652
Telerik UI for Xamarin

Styling
The purpose of this help article is to show you the styling options of the RadCheckBox control.

Colors
RadCheckBox exposes a few useful Color properties for customizing its visual appearance. You
could set the color of the check mark as well as the control itself in each of the available states.

 Background/Border Colors
 CheckedColor: Defines the Color applied to the control when it is checked. This is both
the border and background color.
 UncheckedColor: Defines the Color applied to the control when it is unchecked. This is
the border color only, the background is transparent when unchecked.
 IndeterminateColor: Defines the Color applied to the control when it is in Indeterminate
state. This is both the border and background color.
 Symbol Colors
 CheckedSymbolColor: Defines the Color applied to the check symbol of the control when
it is in Checked state.
 IndeterminateSymbolColor: Defines the Color applied to the Indeterminate symbol of the
control.

Example
Here is an example how to apply indeterminate color and indeterminate symbol color:

Checked Color

XAML
<telerikPrimitives:RadCheckBox CheckedColor="Aqua" />
 

UncheckedColor

XAML
<telerikPrimitives:RadCheckBox UncheckedColor="DarkBlue" />
 

CheckedSymbol

XAML
<telerikPrimitives:RadCheckBox CheckedSymbolColor="Black" />
 

Indeterminate and IndeterminateSymbol Color

653
Telerik UI for Xamarin

XAML
<telerikPrimitives:RadCheckBox x:Name="checkbox" IsChecked="{x:Null}"
IndeterminateColor="Brown" IndeterminateSymbolColor="Coral" />
 

Here is the result at runtime with all of the above examples:

RadCheckBox follows the guidelines of the operating system, meaning that on iOS it is visualized as
circle and on Android and UWP - as square.
 

Theme
Telerik UI for Xamarin allows you to override the default theme and provide an entire set of colors
across all the controls in a custom theme. Visit the Modifying the Default Theme article for more
instructions.

The colors you can set in the custom theme are as follows

xml
<!-- CheckBox -->
<Color x:Key="TelerikCheckBoxCheckedColor">#3148CA</Color>
<Color x:Key="TelerikCheckBoxCheckedSymbolColor">White</Color>
<Color x:Key="TelerikCheckBoxIndeterminateColor">#3148CA</Color>
<Color x:Key="TelerikCheckBoxIndeterminateSymbolColor">White</Color>
<Color x:Key="TelerikCheckBoxUncheckedColor">#919191</Color>
 

654
Telerik UI for Xamarin

To use the custom theme on any RadCheckBox instance, set the StyleClass="Telerik", here's
an example:

xml
<primitives:RadCheckBox StyleClass="Telerik" />
 

See Also
 CheckBox Getting Started
 CheckBox Key Features

655
Telerik UI for Xamarin

ComboBox for Xamarin Overview


Telerik ComboBox for Xamarin allows users to select item/items from a drop down list of items. The
control has a number of features such as editing, searching, single and multiple selection, flexible
styling API, dropdown customizations and more.

Figure 1: ComboBox for Xamarin Overview

Key features
 Editable and NonEditable mode – ComboBox supports both editable and noneditable state.
When the control is in edit mode searching can be performed. For more details please check
the Editing article.
 Searching Support – ComboBox provides both case-sensitive and case-insensitive
searching modes. The available options are: Contains, StartsWith, ContainsCaseSensitive
and StartsWithCaseSensitive. View the Searching article for more details.
 Single and Multiple Selection Support – ComboBox control has a support for single and

656
Telerik UI for Xamarin

multiple selection. You can easily specify the required selection using the SelectionMode
property. To learn more about the Selection please check the Single and Multiple Selection topic.
 Complex Object Support – ComboBox control provides you a way to specify which property
of your complex business object to be displayed in the control by setting
DisplayMemberPath. Check here for more details how Data Binding works.
 Search Highlighting Text – ComboBox control highlights the matching text inside the
dropdown list based on the given input after searching is performed. For more details check
here.
 Placeholder – The text which is used to give guidance to the end user on what should be
entered/searched in the input. The watermark text is displayed when the input field is empty,
or the selected item/s is/are cleared. Review the Key Features article.
 Header and Footer – ComBoBox for Xamarin gives you the ability to add header and footer
inside the dropdown list. For this purpose, you will need to define the HeaderTemplate
property and the FooterTemplate property. Go to Header and Footer article.
 UI Virtualization Support - ComboBox supports UI Virtualization which enables you to display
large list of items. When the list (positioned inside the drop down part) is scrolled, the
ComboBox reuses the existing items to display the relevant data instead of creating new
ones.
 Templates – You can easily change the default ItemTemplate and SelectedItemTemplate. In
addition, if the ComboBox is in multiple selection mode, the selected item is displayed inside
a token. You can customize the token using the TokenTemplate property. Also, you can
customize the ShowMoreTemplate which is visualized inside the ComboBox when the
control is not focused and when there is not enough space for all tokens to be displayed.
Check here for more detail.
 Flexible Styling API – Allows you to change the ComboBox background color, Style the
control’s dropdown box, change the clear and dropdown buttons. In addition, you can
change the Placeholder text color and the Highlighted text color. Check here how you can
work with the Styling API.
 Theming Support - RadComboBox comes with built-in theming support that helps you
achieve consistent look with the rest controls from Telerik UI for Xamarin suite. To learn
more about this go to Theme Overview topic.
 Commands Support – ComboBox for Xamarin exposes ClearSelectionCommand that allows
you clear the selected item(s) from external UI and SelectAllCommand that allows you to
select all items from the source. For more details check here.

SDK Browser and QSF applications contain different examples that show RadComboBox's main
features. You can find the applications in the Examples and QSF folders of your local Telerik UI for
Xamarin installation.
 

See Also
 Visual Structure
 Getting Started
 Key Features
 Data Binding
 Editing
 Searching
 Single and Multiple Selection
 Header and Footer
 Templates
 Theming and Style

657
Telerik UI for Xamarin

Visual Structure of ComboBox for Xamarin


Here are described all visual elements used in the ComboBox for Xamarin.

ComboBox Visual Structure

Single Selection

Multiple Selection

DropDown Visual Structure


Single Selection

Multiple Selection

658
Telerik UI for Xamarin

Legend
 Placeholder - The text which is used to give guidance to the end user on what should be
entered/searched in the input.
 ClearButton - Clears the selection of the control both multiple and single.
 Tokens - When multiple items are selected from the dropdown list, these items appear as
tokens. They can easily be deselected using their close button.
 SelectedItem - The currently selected item.
 SelectedItems - The selected items, when mulptiple selection is used.
 DropDownButton - A button used for opening and closing the DropDown part of the control –
the arrow icon of the button indicates whether it is currently opened or closed.

SDK Browser and QSF applications contain different examples that show RadComboBox's main
features. You can find the applications in the Examples and QSF folders of your local Telerik UI for
Xamarin installation.
 

659
Telerik UI for Xamarin

Getting Started with ComboBox for Xamarin


This article will guide you through the steps needed to add a basic RadComboBox control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadComboBox control
 Populating RadComboBox control with data

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadComboBox control you have to install the
Telerik.UI.for.Xamarin.Input nuget package. This nuget will automatically refer the
Telerik.UI.for.Xamarin.DataControls and Telerik.UI.for.Xamarin.Primitives nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadComboBox component:

Platform Assemblies
Portable Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.Primitives.dll
Android Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataControls.dll
Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Primitives.dll
iOS Telerik.Xamarin.iOS.dllTelerik.XamarinForms.I
nput.dll
Telerik.XamarinForms.Common.dll

660
Telerik UI for Xamarin

Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.Primitives.dll
UWP Telerik.Core.dll
Telerik.UI.Xaml.Primitives.UWP.dll
Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.Primitives.dll

3. Adding RadComboBox control


You could use one of the following approaches:

Drag the control from the Toolbox.

Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML or C#.

The snippet below shows a simple RadCheckBox definition:

XAML
<telerikInput:RadComboBox />
 

C#
var combobox = new RadComboBox();
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

C#
using Telerik.XamarinForms.Input;
 

4. Populating RadComboBox control with data


Using static data

661
Telerik UI for Xamarin

XAML
<telerikInput:RadComboBox>
<telerikInput:RadComboBox.ItemsSource>
<x:Array Type="{x:Type x:String}">
<x:String>USA</x:String>
<x:String>Uganda</x:String>
<x:String>Ukraine</x:String>
<x:String>Canada</x:String>
<x:String>France</x:String>
<x:String>Italy</x:String>
<x:String>United Kingdom</x:String>
<x:String>China</x:String>
<x:String>Japan</x:String>
</x:Array>
</telerikInput:RadComboBox.ItemsSource>
</telerikInput:RadComboBox>
 

C#
var combobox = new RadComboBox();

combobox.ItemsSource = new string[]


{
"USA",
"Uganda",
"Ukraine",
"Canada",
"France",
"Italy",
"United Kingdom",
"China",
"Japan",
};
 

Here is the result:

662
Telerik UI for Xamarin

Binding to a complex object


Here is the ComboBox definition in XAML and in code behind:

XAML
<telerikInput:RadComboBox ItemsSource="{Binding Items}"
DisplayMemberPath="Population"/>
 

C#
var comboBox = new RadComboBox();
comboBox.ItemsSource = this.vm.Items;
comboBox.DisplayMemberPath = "Population";
 

When binding to a complex objects, ComboBox DisplayMemberPath property should be set.


 
the sample business model

C#
public class City
{
public string Name { get; set; }
public int Population { get; set; }
}
 

663
Telerik UI for Xamarin

and the ViewModel used:

C#
public class ViewModel
{
public ViewModel()
{
this.Items = new ObservableCollection<City>
{
new City { Name = "Tokyo", Population = 13929286 },
new City { Name = "New York", Population = 8623000 },
new City { Name = "London", Population = 8908081 },
new City { Name = "Madrid", Population = 3223334 },
new City { Name = "Los Angeles", Population = 4000000},
new City { Name = "Paris", Population = 2141000 },
new City { Name = "Beijing", Population = 21540000 },
new City { Name = "Singapore", Population = 5612000 },
new City { Name = "New Delhi", Population = 18980000 },
new City { Name = "Bangkok", Population = 8305218 },
new City { Name = "Berlin", Population = 3748000 },
};
}

public ObservableCollection<City> Items { get; set; }


}
 

Here is the result:

664
Telerik UI for Xamarin

The Getting Started example can be found in our SDK Browser Application. You can find the
applications in the Examples folder of your local Telerik UI for Xamarin installation or in the following
GitHub repo.
 

See Also
 Key Features
 Data Binding
 Editing
 Searching
 Single and Multiple Selection

665
Telerik UI for Xamarin

Key Features
The purpose of this help article is to show you the key features of the RadComboBox control.

Data Binding
You could set static items to the control's ItemsSource or binding it to a complex object using the
DisplayMemberPath property. For more information please check the ComboBox Data Binding
article.

Placeholder
 Placeholder(string): The text which is used to give guidance to the end user on what should
be entered/searched in the input. The watermark text is displayed when the input field is
empty, or the selected item/s is/are cleared.
 PlaceholderColor(Color): Defines the color for the watermark text.

Here is an example of setting the Placeholder property:

XAML
<telerikInput:RadComboBox Placeholder="Select City!"
ItemsSource="{Binding Items}"
DisplayMemberPath="Name"/>
 

and the result:

Text
 Text(string): Specifies the Text of the control. This is the Text that gets visualized when the
control is editable or when it is non-editable and the selection mode is single.

ClearButton Visibility
The visibility state of the Clear X button can be changed using the IsClearButtonVisible(bool)
property. By default its value is true.

Here is an example with IsClearButtonVisible property set:

XAML
<telerikInput:RadComboBox IsClearButtonVisible="False"

666
Telerik UI for Xamarin

ItemsSource="{Binding Items}"
DisplayMemberPath="Population"
IsEditable="True"
SearchTextPath="Population"
Keyboard="Numeric"/>
 

and the result:

DropDown Behavior
ComboBox provides the following properties for managing the drop down visbility:

 IsDropDownOpen(bool): Defines whether the drop down part of the control is opened.
Default value is true.
 IsDropdownClosedOnSelection(bool): Defines whether the drop down should be closed
when item is selected/deselected. The default value is true.

Here is an example with IsDropdownClosedOnSelection property set:

XAML
<telerikInput:RadComboBox IsDropDownClosedOnSelection="False"
ItemsSource="{Binding Items}"
DisplayMemberPath="Name"/>
 

 OpenOnFocus(bool):Defines whether the drop down should be opened when the control is
focused. The default value is true. It is only applicable for Editable ComboBox.

Here is an example with OpenOnFocus property set:

667
Telerik UI for Xamarin

XAML
<telerikInput:RadComboBox OpenOnFocus="False"
ItemsSource="{Binding Items}"
IsEditable="True"
SearchTextPath="Name"
DisplayMemberPath="Name"/>
 

Keyboard
The Keyboard property of type Xamarin.Forms.Keyboard allows you to define the type of the
keyboard that will be visualized by the device. The default value is Text.

Editing
ComboBox supports both editable and noneditable state. When the control is in edit mode searching
can be performed. For more details please check the Editing article.

Searching
ComboBox provides both case-sensitive and case-insensitive searching modes. The available
options are: Contains, StartsWith, ContainsCaseSensitive and StartsWithCaseSensitive. Please
check the Searching article for more details and a sample demo.

Selection
ComboBox control has a support for single and multiple selection. You can easily specify the
required selection using the SelectionMode property. You can check all properties, event and
commands provided for the selection feature in the Combobox Selection article.

The Key Features example can be found in our SDK Browser Application. You can find the
applications in the Examples folder of your local Telerik UI for Xamarin installation or in the following
GitHub repo.
 

See Also
 ComboBox
 Editing
 Searching
 Selection

668
Telerik UI for Xamarin

ComboBox Data Binding


 ItemsSource (IEnumerable): Defines the collection of the items that will populate the control
with data.
 DisplayMemberPath (string): Defines the name of the property which will be visualized inside
the drop-down list.

If DisplayMemberPath is not set the “ToString” implementation of the business object will be
visualized. The DisplayMemberPath is a property that helps the developers to visualize an exact
property from the business object they are bound to.
 

Binding to a complex object


Here is the ComboBox definition in XAML:

XAML
<telerikInput:RadComboBox ItemsSource="{Binding Items}"
DisplayMemberPath="Population"/>
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

the sample business model

C#
public class City
{
public string Name { get; set; }
public int Population { get; set; }
}
 

and the ViewModel used:

C#
public class ViewModel
{
public ViewModel()
{
this.Items = new ObservableCollection<City>
{

669
Telerik UI for Xamarin

new City { Name = "Tokyo", Population = 13929286 },


new City { Name = "New York", Population = 8623000 },
new City { Name = "London", Population = 8908081 },
new City { Name = "Madrid", Population = 3223334 },
new City { Name = "Los Angeles", Population = 4000000},
new City { Name = "Paris", Population = 2141000 },
new City { Name = "Beijing", Population = 21540000 },
new City { Name = "Singapore", Population = 5612000 },
new City { Name = "New Delhi", Population = 18980000 },
new City { Name = "Bangkok", Population = 8305218 },
new City { Name = "Berlin", Population = 3748000 },
};
}

public ObservableCollection<City> Items { get; set; }


}
 

See Also
 Editing
 Searching
 Single and Multiple Selection

670
Telerik UI for Xamarin

Editing
ComboBox supports both editable and noneditable state. When the control is in edit mode searching
can be performed.

 IsEditable(bool): Defines whether editing can be performed. The default value is false.
 SearchTextPath (string): Defines the name of the property against which the searching will
be performed. The property is usable when editing is performed.

In addition, when IsEditable is set to true, the drop-down list is opening when the control is focused.
That behavior could be changed using the OpenOnFocus property (bool) that is true by default. If the
property is set to false when the control is focused the drop-down will no longer open.

 Text(string): Specifies the Text of the control. This is the Text that gets visualized when the
control is editable or when it is non-editable and the selection mode is single.

Example
Here is the ComboBox definition in XAML:

XAML
<telerikInputnput:RadComboBox ItemsSource="{Binding Items}"
SearchTextPath="Name"
DisplayMemberPath="Name"
IsEditable="True">
<telerikInputnput:RadComboBox.BindingContext>
<local:ViewModel/>
</telerikInputnput:RadComboBox.BindingContext>
</telerikInputnput:RadComboBox>
 

When binding to a complex objects, ComboBox DisplayMemberPath property should be set. Also
when IsEditable is true SearchTextPath property should be set.
 
In addition to this, you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

the sample business model

C#
public class City
{
public string Name { get; set; }

671
Telerik UI for Xamarin

public int Population { get; set; }


}
 

and the ViewModel used:

C#
public class ViewModel : NotifyPropertyChangedBase
{
public ViewModel()
{
this.Items = new ObservableCollection<City>
{
new City { Name = "Tokyo", Population = 13929286 },
new City { Name = "New York", Population = 8623000 },
new City { Name = "London", Population = 8908081 },
new City { Name = "Madrid", Population = 3223334 },
new City { Name = "Los Angeles", Population = 4000000},
new City { Name = "Paris", Population = 2141000 },
new City { Name = "Beijing", Population = 21540000 },
new City { Name = "Singapore", Population = 5612000 },
new City { Name = "New Delhi", Population = 18980000 },
new City { Name = "Bangkok", Population = 8305218 },
new City { Name = "Berlin", Population = 3748000 },
};
}

public ObservableCollection<City> Items { get; set; }


}
 

Herre is how the control looks in edit mode:

672
Telerik UI for Xamarin

See Also
 Key Features
 Searching
 Single and Multiple Selection
 Templates

673
Telerik UI for Xamarin

Searching
ComboBox provides both case-sensitive and case-insensitive searching modes. The following
properties are exposed:

 SearchMode (enumeration of type Telerik.XamarinForms.Input.SearchMode): Defines the


value that sets search sets some search criteria for the control. The available options are:
Contains, StartsWith, ContainsCaseSensitive and StartsWithCaseSensitive. The
default SearchMode is StartsWith.
 SearchTexhPath(string): Specifies the name of the property against which the searching will
be performed.
 HighlightTextColor (Xamarin.Forms.Color): Defines the color of the text that will be
highlighted when searching is performed.

Searching can be performed when IsEditable is set to true.


 

Example
Here is the ComboBox definition in XAML:

XAML
<telerikInput:RadComboBox ItemsSource="{Binding Stores}"
DisplayMemberPath="City"
SearchTextPath="City"
SearchMode="{Binding SearchMode}"
HighlightTextColor="Red"
IsEditable="True"/>
 

When binding to a complex objects, ComboBox DisplayMemberPath property should be set. When
you want to achieve Searching set IsEditable to true and SearchTextPath.
 
In addition to this, you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

the sample business model

C#
public class StoreAddress
{
public string City { get; set; }
public string Street { get; set; }

674
Telerik UI for Xamarin

public string Code { get; set; }


public string WorkHours { get; set; }
}
 

and the ViewModel used:

C#
public class ViewModel : NotifyPropertyChangedBase
{
private SearchMode searchMode;

public ViewModel()
{
this.Stores = new ObservableCollection<StoreAddress>();
this.Stores.Add(new StoreAddress() { City = "New York", Street = "536 Halifax
Road", Code = "Woodside, NY 11377", WorkHours = "Open 11am to 6pm" });
this.Stores.Add(new StoreAddress() { City = "New Jersey", Street = "4759 Cherry
Camp Road", Code = "NJ 07097", WorkHours = "Open 10am to 7pm" });
this.Stores.Add(new StoreAddress() { City = "San Francisco", Street = "3082
Rardin Drive", Code = "CA 94107", WorkHours = "Open 10am to 7pm" });
this.Stores.Add(new StoreAddress() { City = "San Diego", Street = "1593 Hood
Avenue", Code = "CA 92123", WorkHours = "Open 11am to 6pm" });
this.Stores.Add(new StoreAddress() { City = "Los Angeles", Street = "28
Woodstock Drive", Code = "CA 90017", WorkHours = "Open 6am to 9pm" });
this.Stores.Add(new StoreAddress() { City = "Dallas", Street = "2586 Sardis
Sta", Code = "X 75201", WorkHours = "Open 10am to 9pm" });
this.Stores.Add(new StoreAddress() { City = "Austin", Street = "3684 Sundown
Lane", Code = "TX 78741", WorkHours = "Open 10am to 67pm" });
}

public ObservableCollection<StoreAddress> Stores { get; set; }

public SearchMode SearchMode


{
get
{
return this.searchMode;
}
set
{
if (this.searchMode != value)
{
this.searchMode = value;
this.OnPropertyChanged();
}
}
}
}
 

Here is how the control looks when searching is performed:

675
Telerik UI for Xamarin

The SearchingMode example can be found in our SDK Browser Application. You can find the
applications in the Examples folder of your local Telerik UI for Xamarin installation or in the following
GitHub repo.
 

See Also
 Key Features
 Single and Multiple Selection
 Templates
 Styling

676
Telerik UI for Xamarin

Selection
ComboBox for Xamarin enables the app users to quickly and easily select item/items fro a
drop-down list. This topic will go through the provided by the ComboBox API related to item/items
selection.

ComboBox control has a support for single and multiple selection. You can easily specify the
required selection using the SelectionMode property.

Main Properties
 SelectionMode (enumeration of type Telerik.XamarinForms.Input.ComboBoxSelectionMode):
Defines whether the selection is single or multiple.
 SelectedIndex (int): Specifies the index of the first item in the current selection or -1 if the
selection is empty.
 SelectedItem (object): Defines the first item in the current selection, or null if the selection is
empty.
 SelectedItems (*readonly ObservableCollection <object > *): Gets the collection of currently
Selected Items.

SelectedItems collection can be changed only when SelectionMode is Multiple. For Single
SelectionMode use SelectedItem.
 

Single Selection
The default SelectinMode (enumeration of type
Telerik.XamarinForms.Input.ComboBoxSelectionMode) of the ComboBox control is Single.

Example with Single Selection and SelectedIndex set


Here is the ComboBox definition in XAML:

XAML
<telerikInput:RadComboBox ItemsSource="{Binding Items}"
DisplayMemberPath="Name"
SelectedIndex="{Binding SelectedIndex, Mode=TwoWay}"
SelectionMode="Single">
<telerikInput:RadComboBox.BindingContext>
<local:ViewModel/>
</telerikInput:RadComboBox.BindingContext>
</telerikInput:RadComboBox>
 

you need to add the following namespace:

677
Telerik UI for Xamarin

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

the sample business model

C#
public class City
{
public string Name { get; set; }
public int Population { get; set; }
}
 

and the ViewModel used:

C#
public class ViewModel : NotifyPropertyChangedBase
{
private int selectedIndex;
private City selectedItem;
private ObservableCollection<object> selectedItems;
public ViewModel()
{
this.Items = new ObservableCollection<City>
{
new City { Name = "Tokyo", Population = 13929286 },
new City { Name = "New York", Population = 8623000 },
new City { Name = "London", Population = 8908081 },
new City { Name = "Madrid", Population = 3223334 },
new City { Name = "Los Angeles", Population = 4000000},
new City { Name = "Paris", Population = 2141000 },
new City { Name = "Beijing", Population = 21540000 },
new City { Name = "Singapore", Population = 5612000 },
new City { Name = "New Delhi", Population = 18980000 },
new City { Name = "Bangkok", Population = 8305218 },
new City { Name = "Berlin", Population = 3748000 },
};

this.SelectedIndex = 1;
this.SelectedItem = this.Items[2];
}

public ObservableCollection<City> Items { get; set; }

public ObservableCollection<object> SelectedItems


{
get
{
return this.selectedItems;
}

678
Telerik UI for Xamarin

set
{
if (this.selectedItems != value)
{
this.selectedItems = value;

this.selectedItems.Add(this.Items[0]);
this.selectedItems.Add(this.Items[1]);

this.OnPropertyChanged();
}
}
}

public int SelectedIndex


{
get
{
return this.selectedIndex;
}
set
{
if (this.selectedIndex != value)
{
this.selectedIndex = value;
OnPropertyChanged();
}
}
}

public City SelectedItem


{
get
{
return this.selectedItem;
}
set
{
if (this.selectedItem != value)
{
this.selectedItem = value;
OnPropertyChanged();
}
}
}
}
 

This is how single selection looks:

679
Telerik UI for Xamarin

Example with Single Selection and SelectedItem set


Here is the ComboBox definition in XAML:

XAML
<telerikInput:RadComboBox ItemsSource="{Binding Items}"
DisplayMemberPath="Name"
SelectedItem="{Binding SelectedItem, Mode=TwoWay}"
SelectionMode="Single">
<telerikInput:RadComboBox.BindingContext>
<local:ViewModel/>
</telerikInput:RadComboBox.BindingContext>
</telerikInput:RadComboBox>
 

you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

the sample business model

C#
public class City
{
public string Name { get; set; }
public int Population { get; set; }
}
 

and the ViewModel used:

C#

680
Telerik UI for Xamarin

public class ViewModel : NotifyPropertyChangedBase


{
private int selectedIndex;
private City selectedItem;
private ObservableCollection<object> selectedItems;
public ViewModel()
{
this.Items = new ObservableCollection<City>
{
new City { Name = "Tokyo", Population = 13929286 },
new City { Name = "New York", Population = 8623000 },
new City { Name = "London", Population = 8908081 },
new City { Name = "Madrid", Population = 3223334 },
new City { Name = "Los Angeles", Population = 4000000},
new City { Name = "Paris", Population = 2141000 },
new City { Name = "Beijing", Population = 21540000 },
new City { Name = "Singapore", Population = 5612000 },
new City { Name = "New Delhi", Population = 18980000 },
new City { Name = "Bangkok", Population = 8305218 },
new City { Name = "Berlin", Population = 3748000 },
};

this.SelectedIndex = 1;
this.SelectedItem = this.Items[2];
}

public ObservableCollection<City> Items { get; set; }

public ObservableCollection<object> SelectedItems


{
get
{
return this.selectedItems;
}
set
{
if (this.selectedItems != value)
{
this.selectedItems = value;

this.selectedItems.Add(this.Items[0]);
this.selectedItems.Add(this.Items[1]);

this.OnPropertyChanged();
}
}
}

public int SelectedIndex


{
get
{
return this.selectedIndex;

681
Telerik UI for Xamarin

}
set
{
if (this.selectedIndex != value)
{
this.selectedIndex = value;
OnPropertyChanged();
}
}
}

public City SelectedItem


{
get
{
return this.selectedItem;
}
set
{
if (this.selectedItem != value)
{
this.selectedItem = value;
OnPropertyChanged();
}
}
}
}
 

Multiple Selection
If you want to achieve multiple selection you will need to set the SelectionMode to Multiple. The
multiple selected items are visualized inside tokens.

As the SelectedItems collection is read-only, in order to be notified when the collection is changed,
you should listen to the CollectionChanged event of the SelectedItems. Example with
SelectedItems CollectionChanged can be found here: SDK Browser App -
ComboBo/HowTo/Selection with Checkboxes and QSF app -> ComboBox Customization example.
 

Example with Multiple Selection and SelectedItems set


Here is the ComboBox definition in XAML:

XAML
<telerikInput:RadComboBox ItemsSource="{Binding Items}"
SelectionMode="Multiple"
DisplayMemberPath="Name"
SelectedItems="{Binding SelectedItems}"
SelectionChanged="RadComboBox_SelectionChanged">
<telerikInput:RadComboBox.BindingContext>

682
Telerik UI for Xamarin

<local:ViewModel/>
</telerikInput:RadComboBox.BindingContext>
</telerikInput:RadComboBox>
 

the sample business model

C#
public class City
{
public string Name { get; set; }
public int Population { get; set; }
}
 

and the ViewModel used:

C#
public class ViewModel : NotifyPropertyChangedBase
{
private int selectedIndex;
private City selectedItem;
private ObservableCollection<object> selectedItems;
public ViewModel()
{
this.Items = new ObservableCollection<City>
{
new City { Name = "Tokyo", Population = 13929286 },
new City { Name = "New York", Population = 8623000 },
new City { Name = "London", Population = 8908081 },
new City { Name = "Madrid", Population = 3223334 },
new City { Name = "Los Angeles", Population = 4000000},
new City { Name = "Paris", Population = 2141000 },
new City { Name = "Beijing", Population = 21540000 },
new City { Name = "Singapore", Population = 5612000 },
new City { Name = "New Delhi", Population = 18980000 },
new City { Name = "Bangkok", Population = 8305218 },
new City { Name = "Berlin", Population = 3748000 },
};

this.SelectedIndex = 1;
this.SelectedItem = this.Items[2];
}

public ObservableCollection<City> Items { get; set; }

public ObservableCollection<object> SelectedItems


{
get
{
return this.selectedItems;
}

683
Telerik UI for Xamarin

set
{
if (this.selectedItems != value)
{
this.selectedItems = value;

this.selectedItems.Add(this.Items[0]);
this.selectedItems.Add(this.Items[1]);

this.OnPropertyChanged();
}
}
}

public int SelectedIndex


{
get
{
return this.selectedIndex;
}
set
{
if (this.selectedIndex != value)
{
this.selectedIndex = value;
OnPropertyChanged();
}
}
}

public City SelectedItem


{
get
{
return this.selectedItem;
}
set
{
if (this.selectedItem != value)
{
this.selectedItem = value;
OnPropertyChanged();
}
}
}
}
 

This is how multiple selection looks:

684
Telerik UI for Xamarin

The Selection example can be found in our SDK Browser Application. You can find the applications in
the Examples folder of your local Telerik UI for Xamarin installation or in the following GitHub repo.
 

Events
ComboBox exposes a SelectionChanged event which is raised when item is selected.

The SelectionChanged event handler receives two parameters:

 The sender which is the RadComboBox control.


 ComboBoxSelectionChangedEventArgs provides the following properties:
 AddedItems: the items added to the SelectedItemsCollection
 RemovedItems: the items removed from the SelectedItmesCollection

Commands
ComboBox has two commands related to the Selection feature:

 SelectAllCommand (ICommand): Selects all items from the source.


 ClearSelectionCommand (ICommand): Sets the selection to null. If Multiple SelectionMode is
used, this command will clear all selected items.

ComboBox with CheckBox


If you want to add checkbox inside the drop down and select/desect items using CheckBox, we have
a how-to article how this scenario can be achieved. In addition you can select all/deselect all items
using CheckBox inside the drop down header. For more details please check the ComboBox with
CheckBox Selection how to article.

See Also
 Key Features
 Data Binding
 Editing
 Searching
 Templates

685
Telerik UI for Xamarin

Events
ComboBox for Xamarin exposes the following events:

 SelectionChanged event is raised when item is selected. The SelectionChanged event


handler receives two parameters:
 The sender which is the RadComboBox control.
 ComboBoxSelectionChangedEventArgs provides the following properties:
 AddedItems: the items added to the SelectedItemsCollection
 RemovedItems: the items removed from the SelectedItemsCollection
 Completed: Invoked when the completed button of the keyboard gets pressed. In UWP it is
invoked when entered gets pressed.

See Also
 Key Features
 Header and Footer
 Searching
 Single and Multiple Selection
 Styling
 Commands

686
Telerik UI for Xamarin

Commands
ComboBox has the following commands:

 SelectAllCommand (ICommand): Selects all items from the source.

SelectAll command can be used only when SelectionMode is Multiple. An exception will be
thrown, if the command is invoked in Single SelectionMode.
 

 ClearSelectionCommand (ICommand): Sets the selection to null. If Multiple SelectionMode is


used, this command will clear all selected items.

Example
Sample example where SelectAll command is used can be found in the ComboBox How-To section
ComboBox with CheckBox article.
 

See Also
 Key Features
 Data Binding
 Editing
 Searching
 Templates

687
Telerik UI for Xamarin

ComboBox Header and Footer


You can easily add Header and Footer to the Drop Down list of the ComboBox control through the
following propertes:

 HeaderTemplate(DataTemplate): Defines the template of the header that will be visualized in


the drop down list.
 FooterTemplate(DataTemplate): Defines the template of the footer that will be visualized in
the drop down list.

It is not recommended to add controls in the Header and Footer which steal the focus (like Entry,
editor, etc.) from the ComboBox control, as unexpected behavior may occur.
 

Example
Here is the ComboBox definition in XAML:

XAML
<telerikInput:RadComboBox ItemsSource="{Binding Items}"
DisplayMemberPath="Name"
IsEditable="True"
SearchMode="Contains"
SearchTextPath="Name"
Placeholder="Select which city you want to visit"
SelectionMode="Multiple"
DropDownHeight="300"
x:Name="comboBox">
<telerikInput:RadComboBox.HeaderTemplate>
<DataTemplate>
<StackLayout BackgroundColor="LightBlue">
<Label Text="To Visit List!"
FontSize="20"
TextColor="Black"
BackgroundColor="LightBlue"
VerticalOptions="Center"
HorizontalOptions="Center"/>
</StackLayout>
</DataTemplate>
</telerikInput:RadComboBox.HeaderTemplate>
<telerikInput:RadComboBox.FooterTemplate>
<DataTemplate>
<StackLayout>
<Button Text="Add Items" Clicked="Button_Clicked" BackgroundColor="LightBlue"/>
</StackLayout>
</DataTemplate>
</telerikInput:RadComboBox.FooterTemplate>
</telerikInput:RadComboBox>
 

688
Telerik UI for Xamarin

the sample business model

C#
public class City
{
public string Name { get; set; }
public int Population { get; set; }
}
 

and the ViewModel used:

C#
public class ViewModel : NotifyPropertyChangedBase
{
public ViewModel()
{
this.Items = new ObservableCollection<City>
{
new City { Name = "Tokyo", Population = 13929286 },
new City { Name = "New York", Population = 8623000 },
new City { Name = "London", Population = 8908081 },
new City { Name = "Madrid", Population = 3223334 },
new City { Name = "Los Angeles", Population = 4000000},
new City { Name = "Paris", Population = 2141000 },
new City { Name = "Beijing", Population = 21540000 },
new City { Name = "Singapore", Population = 5612000 },
new City { Name = "New Delhi", Population = 18980000 },
new City { Name = "Bangkok", Population = 8305218 },
new City { Name = "Berlin", Population = 3748000 },
};
}

public ObservableCollection<City> Items { get; set; }


}
 

This is how the Header and Footer Templates look:

689
Telerik UI for Xamarin

Header and Footer Template example can be found in our SDK Browser Application. You can find the
applications in the Examples folder of your local Telerik UI for Xamarin installation or in the following
GitHub repo.
 

See Also
 Key Features
 Header and Footer
 Searching
 Single and Multiple Selection
 Styling

690
Telerik UI for Xamarin

Templates
If the default templates of the control do not suit your needs, you can easily define custom ones. The
available templates for customizing are:

 ItemTemplate(DataTemplate): Defines the template of the items that are visualized in the
drop-down list.

When the selection mode is single and the control is not editable if there is ItemTemplate set the
same template will be visualized in the box part of the control when item is selected.
 

 SelectedItemTemplate(DataTemplate): Defines the template of the selected items that are


visualized in the drop-down list.
 TokenTemplate(DataTemplate): Defines the template of the tokens that are visualized when
multiple selection is performed.
 ShowMoreTemplate(DataTemplate): Defines the Template of the show more UI that gets
visualized when the control is not focused and there is not enough space for all Tokens to be
visualized when the selection mode is multiple.

Example with ItemTemplate and SelectedItemTemplate


Here is the ComboBox definition in XAML:

XAML
<telerikInput:RadComboBox ItemsSource="{Binding Stores}"
DisplayMemberPath="City"
Placeholder="Select Store">
<telerikInput:RadComboBox.ItemTemplate>
<DataTemplate>
<StackLayout BackgroundColor="LightYellow" VerticalOptions="Center">
<Label Text="{Binding City}"
Style="{StaticResource labelStyle}"/>
</StackLayout>
</DataTemplate>
</telerikInput:RadComboBox.ItemTemplate>
<telerikInput:RadComboBox.SelectedItemTemplate>
<DataTemplate>
<StackLayout BackgroundColor="LightBlue">
<Label Text="{Binding Street}" Style="{StaticResource labelStyle}"/>
<Label Text="{Binding Code}" FontSize="12" Margin="10,0,0,5"/>
</StackLayout>
</DataTemplate>
</telerikInput:RadComboBox.SelectedItemTemplate>
</telerikInput:RadComboBox>
 

you need to add the following namespace:

691
Telerik UI for Xamarin

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

the sample business model

C#
public class StoreAddress
{
public string City { get; set; }
public string Street { get; set; }
public string Code { get; set; }
public string WorkHours { get; set; }
}
 

and the ViewModel used:

C#
public class ViewModel : NotifyPropertyChangedBase
{
private SearchMode searchMode;

public ViewModel()
{
this.Stores = new ObservableCollection<StoreAddress>();
this.Stores.Add(new StoreAddress() { City = "New York", Street = "536 Halifax
Road", Code = "Woodside, NY 11377", WorkHours = "Open 11am to 6pm" });
this.Stores.Add(new StoreAddress() { City = "New Jersey", Street = "4759 Cherry
Camp Road", Code = "NJ 07097", WorkHours = "Open 10am to 7pm" });
this.Stores.Add(new StoreAddress() { City = "San Francisco", Street = "3082
Rardin Drive", Code = "CA 94107", WorkHours = "Open 10am to 7pm" });
this.Stores.Add(new StoreAddress() { City = "San Diego", Street = "1593 Hood
Avenue", Code = "CA 92123", WorkHours = "Open 11am to 6pm" });
this.Stores.Add(new StoreAddress() { City = "Los Angeles", Street = "28
Woodstock Drive", Code = "CA 90017", WorkHours = "Open 6am to 9pm" });
this.Stores.Add(new StoreAddress() { City = "Dallas", Street = "2586 Sardis
Sta", Code = "X 75201", WorkHours = "Open 10am to 9pm" });
this.Stores.Add(new StoreAddress() { City = "Austin", Street = "3684 Sundown
Lane", Code = "TX 78741", WorkHours = "Open 10am to 67pm" });
}

public ObservableCollection<StoreAddress> Stores { get; set; }

public SearchMode SearchMode


{
get
{
return this.searchMode;
}
set
{

692
Telerik UI for Xamarin

if (this.searchMode != value)
{
this.searchMode = value;
this.OnPropertyChanged();
}
}
}
}
 

The final result:

The Item and SelectedItem Template example can be found in our SDK Browser Application. You can
find the applications in the Examples folder of your local Telerik UI for Xamarin installation or in the
following GitHub repo.
 

Example with TokenTemplate and ShowMoreTemplate


Here is the ComboBox definition in XAML:

XAML
<telerikInput:RadComboBox ItemsSource="{Binding Items}"
Placeholder="Select City!"
SelectionMode="Multiple"
DisplayMemberPath="Name"
x:Name="comboBox">
<telerikInput:RadComboBox.TokenTemplate>
<DataTemplate>
<telerikPrimitives:RadBorder BackgroundColor="LightBlue"
CornerRadius="10"

693
Telerik UI for Xamarin

Margin="2">
<StackLayout Orientation="Horizontal"
Margin="3">
<Label Text="{Binding Name}"
TextColor="Black"
VerticalTextAlignment="Center"
Margin="2" />
<Label FontFamily="{StaticResource IconsFontFamily}"
Text="&#xE80A;" FontSize="10"
VerticalTextAlignment="Center"
TextColor="Black"
Margin="2">
<Label.GestureRecognizers>
<TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped"/>
</Label.GestureRecognizers>
</Label>
</StackLayout>
</telerikPrimitives:RadBorder>
</DataTemplate>
</telerikInput:RadComboBox.TokenTemplate>
<telerikInput:RadComboBox.ShowMoreTemplate>
<DataTemplate>
<Label Text="{Binding Path=., StringFormat='+{0} more items'}"
VerticalTextAlignment="Center"/>
</DataTemplate>
</telerikInput:RadComboBox.ShowMoreTemplate>
</telerikInput:RadComboBox>
 

add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

the sample business model

C#
public class City
{
public string Name { get; set; }
public int Population { get; set; }
}
 

and the ViewModel used:

C#
public class ViewModel : NotifyPropertyChangedBase
{

694
Telerik UI for Xamarin

public ViewModel()
{
this.Items = new ObservableCollection<City>
{
new City { Name = "Tokyo", Population = 13929286 },
new City { Name = "New York", Population = 8623000 },
new City { Name = "London", Population = 8908081 },
new City { Name = "Madrid", Population = 3223334 },
new City { Name = "Los Angeles", Population = 4000000},
new City { Name = "Paris", Population = 2141000 },
new City { Name = "Beijing", Population = 21540000 },
new City { Name = "Singapore", Population = 5612000 },
new City { Name = "New Delhi", Population = 18980000 },
new City { Name = "Bangkok", Population = 8305218 },
new City { Name = "Berlin", Population = 3748000 },
};
}

public ObservableCollection<City> Items { get; set; }


}
 

when the default TokenTemplate is overriden, you will need to implement custom logic for removing
the tokens from the ComboBox:
 
here is a sample logic removing the token when adding TapGestureRecognizer to the Label:

C#
private void TapGestureRecognizer_Tapped(object sender, System.EventArgs e)
{
var closeLabel = sender as Label;
if (closeLabel != null)
{
var item = closeLabel.BindingContext as City;
if (item != null)
{
this.comboBox.SelectedItems.Remove(item);
}
}
}
 

Here is the how the Token and ShowMore Templates look:

695
Telerik UI for Xamarin

The Token and ShowMore Template example can be found in our SDK Browser Application. You can
find the applications in the Examples folder of your local Telerik UI for Xamarin installation or in the
following GitHub repo.
 

Default Templates
Default ItemTemplate and SelectedItemTemplate of RadComboBox provide highlighting of the
matching text while searching - this is implemented through a small auxiliary control in the templates,
named RadHighlightLabel. RadHighlightLabel exposes UnformattedText property that should be
set to the complete text shown in the label and HighlightText that should be set to the highlighted
part of that text.

The example below shows the default ItemTemplate and SelectedItemTemplate with the
RadHighlightLabel properly setup to highlight the search text coming from the RadComboBox input
field.

First, add the required DataTemplates inside the Resources of your page:

XAML
<ResourceDictionary>
<DataTemplate x:Key="CustomItemTemplate">
<telerikPrimitives:RadBorder BorderColor="Transparent"
BorderThickness="0">
<telerikPrimitives:RadHighlightLabel UnformattedText="{Binding City}"
HighlightText="{Binding Source={x:Reference comboBox}, Path=SearchText,
Mode=OneWay}"
VerticalTextAlignment="Center"
TextColor="Black"
HighlightTextColor="#429CE3"
MinimumHeightRequest="32"
Padding="10, 6, 0, 6"/>
</telerikPrimitives:RadBorder>
</DataTemplate>
<DataTemplate x:Key="CustomSelectedItemTemplate">
<telerikPrimitives:RadBorder BorderColor="Transparent"
BorderThickness="0"
BackgroundColor="#FFF7DD">
<telerikPrimitives:RadHighlightLabel UnformattedText="{Binding City}"
HighlightText="{Binding Source={x:Reference comboBox}, Path=SearchText,
Mode=OneWay}"
VerticalTextAlignment="Center"
TextColor="Black"
HighlightTextColor="#429CE3"
MinimumHeightRequest="32"
Padding="10, 6, 0, 6"/>
</telerikPrimitives:RadBorder>
</DataTemplate>
</ResourceDictionary>
 

696
Telerik UI for Xamarin

Add the required namespace:

C#
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

And here is the RadComboBox definition with the defined templates referenced:

XAML
<telerikInput:RadComboBox x:Name="comboBox"
ItemsSource="{Binding Stores}"
DisplayMemberPath="City"
IsEditable="true"
SearchTextPath="City"
Placeholder="Select Store"
ItemTemplate="{StaticResource CustomItemTemplate}"
SelectedItemTemplate="{StaticResource CustomSelectedItemTemplate}"/>
 

Check the result in the screenshot below:

See Also
 Key Features
 Header and Footer
 Searching
 Single and Multiple Selection
 Styling

697
Telerik UI for Xamarin

Theming and Style


ComboBox Styling
ComboBox control for Xamarin provides the following Style properties for customizing its look:

 PlaceholderColor(Xamarin.Forms.Color): Defines the color for the placeholder text.


 TextColor(Xamarin.Forms.Color): Defines the color of the text when the control is editable
and color of the selected item when it is not editable and selection mode is single.
 BackgroundColor(Xamarin.Forms.Color): Defines the background color of the control.
 BorderColor(Xamarin.Forms.Color): Defines the color of the border.
 BorderThickness(Xamarin.Forms.Color): Defines the thickness of the border.
 FocusedBorderColor(Xamarin.Forms.Color): Defines the color of the nborder when the
control is focused.
 ClearButtonStyle(of type Style with target type Xamarin.Forms.Button): Defines the style for
the clear button.
 Font Options(FontAttributes, FontFamily, FontSize): Define the font options to the text
of the RadComboBox. It is applied to the Placeholder, Selected Text(for single selection) and
when the control is in Editable Mode.

Example for ComboBox Styling


Here is the ComboBox definition in XAML:

XAML
<telerikInput:RadComboBox ItemsSource="{Binding Items}"
Placeholder="Select City!"
PlaceholderColor="Blue"
BackgroundColor="LightGray"
FocusedBorderColor="Blue"
BorderColor="Black"
BorderThickness="2"
ClearButtonStyle="{StaticResource ClearButtonStyle}"
DisplayMemberPath="Name">
<telerikInput:RadComboBox.BindingContext>
<local:ViewModel/>
</telerikInput:RadComboBox.BindingContext>
</telerikInput:RadComboBox>
 

in addition you will need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

698
Telerik UI for Xamarin

the sample business model

C#
public class City
{
public string Name { get; set; }
public int Population { get; set; }
}
 

and the ViewModel used:

C#
public class ViewModel : NotifyPropertyChangedBase
{
public ViewModel()
{
this.Items = new ObservableCollection<City>
{
new City { Name = "Tokyo", Population = 13929286 },
new City { Name = "New York", Population = 8623000 },
new City { Name = "London", Population = 8908081 },
new City { Name = "Madrid", Population = 3223334 },
new City { Name = "Los Angeles", Population = 4000000},
new City { Name = "Paris", Population = 2141000 },
new City { Name = "Beijing", Population = 21540000 },
new City { Name = "Singapore", Population = 5612000 },
new City { Name = "New Delhi", Population = 18980000 },
new City { Name = "Bangkok", Population = 8305218 },
new City { Name = "Berlin", Population = 3748000 },
};
}

public ObservableCollection<City> Items { get; set; }


}
 

Here is how the Combobox looks when styling is applied:

699
Telerik UI for Xamarin

Here is how the styling is applied when the control is focused and item is selected:

The ComboBox Styling example can be found in our SDK Browser Application. You can find the
applications in the Examples folder of your local Telerik UI for Xamarin installation or in the following
GitHub repo.
 

DropDown Styling
The following properties styles the ComboBox Drop Down:

700
Telerik UI for Xamarin

 DropDownBorderColor(Xamarin.Forms.Color): Defines the color of the border around the


drop down part of the control.
 DropDownBorderThickness(Xamarin.Forms.Thickness): Defines the thickness of the border
that is around of the drop down part of the control.
 DropDownBorderCornerRadius(Xamarin.Forms.Thickness): Defines the corner radius of the
border that is around the drop down part of the control
 DropDownBackgroundColor(Xamarin.Forms.Color): Defines the background color of the
drop down part of the control.
 DropDownButtonStyle(of type Style with target type Xamarin.Forms.Button): Defines the
style for the drop down button.

Example Drop Down Styling


Here is the ComboBox definition in XAML:

XAML
<telerikInput:RadComboBox ItemsSource="{Binding Items}"
IsEditable="True"
SearchTextPath="Name"
DisplayMemberPath="Name"
SelectionMode="Multiple"
HighlightTextColor="Black"
DropDownBorderColor="Blue"
DropDownBorderThickness="2"
DropDownCornerRadius="5"
DropDownBackgroundColor="LightBlue"
DropDownButtonStyle="{StaticResource DropDownButtonStyle}">
<telerikInput:RadComboBox.BindingContext>
<local:ViewModel/>
</telerikInput:RadComboBox.BindingContext>
</telerikInput:RadComboBox>
 

add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

The DropDown Button Style is defined in the Page's ResourceDictionary:

XAML
<Style TargetType="Button" x:Key="DropDownButtonStyle">
<Setter Property="FontSize" Value="14"/>
<Setter Property="HorizontalOptions" Value="Center"/>
<Setter Property="VerticalOptions" Value="Center"/>
<Setter Property="WidthRequest" Value="24"/>
<Setter Property="HeightRequest" Value="24"/>
<Setter Property="Padding" Value="0"/>
<Setter Property="BackgroundColor">

701
Telerik UI for Xamarin

<Setter.Value>
<OnPlatform x:TypeArguments="Color">
<On Platform="Android">Transparent</On>
</OnPlatform>
</Setter.Value>
</Setter>
<Setter Property="TextColor" Value="Blue"/>
<Setter Property="Margin">
<Setter.Value>
<OnPlatform x:TypeArguments="Thickness">
<On Platform="Android">8, 0, 4, 0</On>
<On Platform="iOS">8, 6, 4, 7</On>
<On Platform="UWP">6, 1, 10, 1</On>
</OnPlatform>
</Setter.Value>
</Setter>
</Style>
 

the sample business model

C#
public class City
{
public string Name { get; set; }
public int Population { get; set; }
}
 

and the ViewModel used:

C#
public class ViewModel : NotifyPropertyChangedBase
{
public ViewModel()
{
this.Items = new ObservableCollection<City>
{
new City { Name = "Tokyo", Population = 13929286 },
new City { Name = "New York", Population = 8623000 },
new City { Name = "London", Population = 8908081 },
new City { Name = "Madrid", Population = 3223334 },
new City { Name = "Los Angeles", Population = 4000000},
new City { Name = "Paris", Population = 2141000 },
new City { Name = "Beijing", Population = 21540000 },
new City { Name = "Singapore", Population = 5612000 },
new City { Name = "New Delhi", Population = 18980000 },
new City { Name = "Bangkok", Population = 8305218 },
new City { Name = "Berlin", Population = 3748000 },
};
}

702
Telerik UI for Xamarin

public ObservableCollection<City> Items { get; set; }


}
 

Here is how the Drop Down Styling looks:

The DropDown Styling example can be found in our SDK Browser Application. You can find the
applications in the Examples folder of your local Telerik UI for Xamarin installation or in the following
GitHub repo.
 

Theming
See Also
 CheckBox Getting Started
 CheckBox Key Features

703
Telerik UI for Xamarin

ComboBox with CheckBox


The following article will show you how to display checkbox for each item inside the ComboBox drop
down, select item using the CheckBox control and visualize header inside the drop down part with
Select All functionality.

Example
Here are the steps needed to achieve the functionality describe above.

The ComboBox definition in XAML:

XAML
<telerikInput:RadComboBox Grid.Row="1"
BackgroundColor="White"
ItemsSource="{Binding Items}"
SelectedItems="{Binding SelectedItems}"
IsDropDownClosedOnSelection="False"

704
Telerik UI for Xamarin

SelectionMode="Multiple"
DisplayMemberPath="Name"
ItemTemplate="{StaticResource ComboBoxItemTemplate}"
SelectedItemTemplate="{StaticResource ComboBoxSelectedItemTemplate}"
HeaderTemplate="{StaticResource ComboBoxHeaderTemplate}"
Margin="10, 0, 10, 0">
<telerikInput:RadComboBox.BindingContext>
<local:ViewModel/>
</telerikInput:RadComboBox.BindingContext>
<telerikInput:RadComboBox.DropDownHeight>
<OnPlatform x:TypeArguments="x:Double">
<On Platform="iOS">238</On>
<On Platform="UWP">244</On>
<On Platform="Android">248</On>
</OnPlatform>
</telerikInput:RadComboBox.DropDownHeight>
</telerikInput:RadComboBox>
 

Lets define the CheckBox control inside the ComboBox ItemTemplate:

XAML
<DataTemplate x:Key="ComboBoxItemTemplate">
<telerikPrimitives:RadBorder>
<telerikPrimitives:RadBorder.MinimumHeightRequest>
<OnPlatform x:TypeArguments="x:Double">
<On Platform="iOS" Value="44"/>
<On Platform="Android" Value="48"/>
<On Platform="UWP" Value="32"/>
</OnPlatform>
</telerikPrimitives:RadBorder.MinimumHeightRequest>
<telerikPrimitives:RadBorder.BorderColor>
<OnPlatform x:TypeArguments="Color" Default="#ECECEC">
<On Platform="UWP" Value="Transparent"/>
</OnPlatform>
</telerikPrimitives:RadBorder.BorderColor>
<telerikPrimitives:RadBorder.BorderThickness>
<OnPlatform x:TypeArguments="Thickness" Default="0, 0, 0, 1">
<On Platform="UWP" Value="0"/>
</OnPlatform>
</telerikPrimitives:RadBorder.BorderThickness>
<StackLayout Orientation="Horizontal">
<StackLayout.Padding>
<OnPlatform x:TypeArguments="Thickness" Default="11, 12, 0, 12">
<On Platform="UWP" Value="6, 6, 0, 6"/>
<On Platform="Android" Value="11, 6, 0, 6"/>
</OnPlatform>
</StackLayout.Padding>
<telerikPrimitives:RadCheckBox Margin="0, 0, 6, 0"
CheckedColor="#0E88F2"
IndeterminateColor="#0E88F2"
InputTransparent="True"
IsChecked="False"

705
Telerik UI for Xamarin

VerticalOptions="Center">
<telerikPrimitives:RadCheckBox.Margin>
<OnPlatform x:TypeArguments="Thickness">
<On Platform="iOS" Value="3, 0, 0, 0"/>
<On Platform="Android" Value="8, 0, 0, 0"/>
<On Platform="UWP" Value="10, 0, 0, 0"/>
</OnPlatform>
</telerikPrimitives:RadCheckBox.Margin>
</telerikPrimitives:RadCheckBox>
<Label Text="{Binding Name}"
VerticalTextAlignment="Center"
TextColor="#8A000000"
FontSize="14">
<Label.Padding>
<OnPlatform x:TypeArguments="Thickness">
<On Platform="iOS" Value="3, 0, 0, 0"/>
<On Platform="Android" Value="8, 13, 0, 13"/>
<On Platform="UWP" Value="10, 6, 0, 6"/>
</OnPlatform>
</Label.Padding>
</Label>
</StackLayout>
</telerikPrimitives:RadBorder>
</DataTemplate>
 

and in SelectedItemTemplate:

XAML
<DataTemplate x:Key="ComboBoxSelectedItemTemplate">
<telerikPrimitives:RadBorder>
<telerikPrimitives:RadBorder.MinimumHeightRequest>
<OnPlatform x:TypeArguments="x:Double">
<On Platform="iOS" Value="44"/>
<On Platform="Android" Value="48"/>
<On Platform="UWP" Value="32"/>
</OnPlatform>
</telerikPrimitives:RadBorder.MinimumHeightRequest>
<telerikPrimitives:RadBorder.BorderColor>
<OnPlatform x:TypeArguments="Color" Default="#ECECEC">
<On Platform="UWP" Value="Transparent"/>
</OnPlatform>
</telerikPrimitives:RadBorder.BorderColor>
<telerikPrimitives:RadBorder.BackgroundColor>
<OnPlatform x:TypeArguments="Color" Default="#F8F8F8">
<On Platform="UWP" Value="Accent"/>
</OnPlatform>
</telerikPrimitives:RadBorder.BackgroundColor>
<telerikPrimitives:RadBorder.BorderThickness>
<OnPlatform x:TypeArguments="Thickness" Default="0, 0, 0, 1">
<On Platform="UWP" Value="0"/>
</OnPlatform>
</telerikPrimitives:RadBorder.BorderThickness>

706
Telerik UI for Xamarin

<StackLayout Orientation="Horizontal"
BackgroundColor="#F8F8F8">
<StackLayout.Padding>
<OnPlatform x:TypeArguments="Thickness" Default="11, 12, 0, 12">
<On Platform="UWP" Value="6, 6, 0, 6"/>
<On Platform="Android" Value="11, 6, 0, 6"/>
</OnPlatform>
</StackLayout.Padding>
<telerikPrimitives:RadCheckBox Margin="0, 0, 6, 0"
CheckedColor="#0E88F2"
IndeterminateColor="#0E88F2"
InputTransparent="True"
IsChecked="True"
VerticalOptions="Center">
<telerikPrimitives:RadCheckBox.Margin>
<OnPlatform x:TypeArguments="Thickness">
<On Platform="iOS" Value="3, 0, 0, 0"/>
<On Platform="Android" Value="8, 0, 0, 0"/>
<On Platform="UWP" Value="10, 0, 0, 0"/>
</OnPlatform>
</telerikPrimitives:RadCheckBox.Margin>
</telerikPrimitives:RadCheckBox>
<Label Text="{Binding Name}"
VerticalTextAlignment="Center"
TextColor="#8A000000"
FontSize="14">
<Label.Padding>
<OnPlatform x:TypeArguments="Thickness">
<On Platform="iOS" Value="3, 0, 0, 0"/>
<On Platform="Android" Value="8, 13, 0, 13"/>
<On Platform="UWP" Value="10, 6, 0, 6"/>
</OnPlatform>
</Label.Padding>
</Label>
</StackLayout>
</telerikPrimitives:RadBorder>
</DataTemplate>
 

Then lets add a checkbox inside the Drop Down HeaderTemplate. In this way we can select/unselect
all items from the drop down list.

XAML
<DataTemplate x:Key="ComboBoxHeaderTemplate">
<telerikPrimitives:RadBorder>
<telerikPrimitives:RadBorder.MinimumHeightRequest>
<OnPlatform x:TypeArguments="x:Double">
<On Platform="iOS" Value="44"/>
<On Platform="Android" Value="48"/>
<On Platform="UWP" Value="32"/>
</OnPlatform>
</telerikPrimitives:RadBorder.MinimumHeightRequest>
<telerikPrimitives:RadBorder.BorderColor>

707
Telerik UI for Xamarin

<OnPlatform x:TypeArguments="Color" Default="#ECECEC">


<On Platform="UWP" Value="Transparent"/>
</OnPlatform>
</telerikPrimitives:RadBorder.BorderColor>
<telerikPrimitives:RadBorder.BorderThickness>
<OnPlatform x:TypeArguments="Thickness" Default="0, 0, 0, 1">
<On Platform="UWP" Value="0"/>
</OnPlatform>
</telerikPrimitives:RadBorder.BorderThickness>
<StackLayout Orientation="Horizontal"
BackgroundColor="#DADADA">
<StackLayout.Padding>
<OnPlatform x:TypeArguments="Thickness" Default="11, 12, 0, 12">
<On Platform="UWP" Value="6, 6, 0, 6"/>
<On Platform="Android" Value="11, 6, 0, 6"/>
</OnPlatform>
</StackLayout.Padding>
<telerikPrimitives:RadCheckBox IsChecked="{Binding SelectAllChecked}"
CheckedColor="#0E88F2"
IndeterminateColor="#0E88F2"
InputTransparent="True"
VerticalOptions="Center">
<telerikPrimitives:RadCheckBox.Margin>
<OnPlatform x:TypeArguments="Thickness">
<On Platform="iOS" Value="3, 0, 0, 0"/>
<On Platform="Android" Value="8, 0, 0, 0"/>
<On Platform="UWP" Value="10, 0, 0, 0"/>
</OnPlatform>
</telerikPrimitives:RadCheckBox.Margin>
</telerikPrimitives:RadCheckBox>
<Label Text="Select All Cities"
TextColor="Black"
FontAttributes="Bold"
VerticalTextAlignment="Center">
<Label.Padding>
<OnPlatform x:TypeArguments="Thickness">
<On Platform="iOS" Value="3, 0, 0, 0"/>
<On Platform="Android" Value="8, 13, 0, 13"/>
<On Platform="UWP" Value="10, 6, 0, 6"/>
</OnPlatform>
</Label.Padding>
</Label>
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Command="{Binding SelectAllCommand}"/>
</StackLayout.GestureRecognizers>
</StackLayout>
</telerikPrimitives:RadBorder>
</DataTemplate>
 

the business model used:

C#

708
Telerik UI for Xamarin

public class City


{
public string Name { get; set; }
public int Population { get; set; }
}
 

In addition, there is a logic inside the ViewModel whether the selection is made internally of from the
UI - SelectAll option.

Here is the ViewModel used:

C#
public class ViewModel : NotifyPropertyChangedBase
{
private ObservableCollection<object> selectedItems;
private bool? selectAllChecked = false;
private bool isInternalCheckChanged;

public ViewModel()
{
this.Items = new ObservableCollection<City>
{
new City { Name = "Tokyo", Population = 13929286 },
new City { Name = "New York", Population = 8623000 },
new City { Name = "London", Population = 8908081 },
new City { Name = "Madrid", Population = 3223334 },
new City { Name = "Los Angeles", Population = 4000000},
new City { Name = "Paris", Population = 2141000 },
new City { Name = "Beijing", Population = 21540000 },
new City { Name = "Singapore", Population = 5612000 },
new City { Name = "New Delhi", Population = 18980000 },
new City { Name = "Bangkok", Population = 8305218 },
new City { Name = "Berlin", Population = 3748000 },
};

this.SelectAllCommand = new Command(this.OnSelectAllCommandExecute);


}

public ObservableCollection<City> Items { get; set; }


public ICommand SelectAllCommand { get; set; }

public ObservableCollection<object> SelectedItems


{
get
{
return this.selectedItems;
}
set
{
if (this.selectedItems != value)
{
if (this.selectedItems != null)

709
Telerik UI for Xamarin

{
this.selectedItems.CollectionChanged -= this.OnSelectedItemsCollectionChanged;
}

this.selectedItems = value;

if (this.selectedItems != null)
{
this.selectedItems.CollectionChanged += this.OnSelectedItemsCollectionChanged;
}

this.OnPropertyChanged();
}
}
}

public bool? SelectAllChecked


{
get
{
return this.selectAllChecked;
}
set
{
if (this.selectAllChecked != value)
{
this.selectAllChecked = value;

if (!this.isInternalCheckChanged && this.selectAllChecked.HasValue)


{
if (this.selectAllChecked.Value)
{
foreach (var store in this.Items)
{
if (!this.SelectedItems.Contains(store))
{
this.SelectedItems.Add(store);
}
}
}
else
{
this.SelectedItems.Clear();
}
}

this.OnPropertyChanged();
}
}
}

private void OnSelectAllCommandExecute(object obj)


{
if (this.selectAllChecked == null)

710
Telerik UI for Xamarin

{
this.SelectAllChecked = false;
}
else
{
this.SelectAllChecked = !this.selectAllChecked;
}
}

private void OnSelectedItemsCollectionChanged(object sender,


NotifyCollectionChangedEventArgs e)
{
var action = e.Action;
if (action == NotifyCollectionChangedAction.Add)
{
this.isInternalCheckChanged = true;
if (this.SelectedItems.Count == this.Items.Count)
{
this.SelectAllChecked = true;
}
else
{
this.SelectAllChecked = null;
}
this.isInternalCheckChanged = false;

return;
}

if (action == NotifyCollectionChangedAction.Remove)
{
this.isInternalCheckChanged = true;
if (this.SelectedItems.Count == 0)
{
this.SelectAllChecked = false;
}
else
{
this.SelectAllChecked = null;
}
this.isInternalCheckChanged = false;
}
}
}
 

This is the result:

711
Telerik UI for Xamarin

Example for ComboBox with CheckBox selection can be found in the ComboBox/How To section
from the SDK Browser Application.
 

See Also
 Key Features
 Data Binding
 Editing
 Searching
 Templates

712
Telerik UI for Xamarin

ComboBox with No Null Values


The following article will show you how to prevent item deselection when the ComboBox selection
mode is single and there is initially selected item.

Here are the steps needed to achieve the functionality describe above.

To prevent item deselection we will need to set IsClearButtonvisible to False and


SelectionMode to Single Here is the ComboBox definition in XAML

XAML
<telerikInput:RadComboBox Grid.Row="1"
ItemsSource="{Binding Items}"
SelectedItem="{Binding SelectedItem}"
DisplayMemberPath="Name"
IsClearButtonVisible="False"

713
Telerik UI for Xamarin

SelectionMode="Single"
Margin="10, 0, 10, 0">
<telerikInput:RadComboBox.BindingContext>
<local:ViewModel/>
</telerikInput:RadComboBox.BindingContext>
</telerikInput:RadComboBox>
 

the business model used:

C#
public class City
{
public string Name { get; set; }
public int Population { get; set; }
}
 

Mainly inside the ViewModel you will need to declare a property and bind it to the ComboBox
SelectedItem property, then set a value for this property in the ViewModel's contructor:

C#
public class ViewModel : NotifyPropertyChangedBase
{
private City selectedItem;

public ViewModel()
{
this.Items = new ObservableCollection<City>
{
new City { Name = "Tokyo", Population = 13929286 },
new City { Name = "New York", Population = 8623000 },
new City { Name = "London", Population = 8908081 },
new City { Name = "Madrid", Population = 3223334 },
new City { Name = "Los Angeles", Population = 4000000},
new City { Name = "Paris", Population = 2141000 },
new City { Name = "Beijing", Population = 21540000 },
new City { Name = "Singapore", Population = 5612000 },
new City { Name = "New Delhi", Population = 18980000 },
new City { Name = "Bangkok", Population = 8305218 },
new City { Name = "Berlin", Population = 3748000 },
};

this.SelectedItem = this.Items[0];
}

public ObservableCollection<City> Items { get; set; }

public City SelectedItem


{
get
{

714
Telerik UI for Xamarin

return this.selectedItem;
}
set
{
if (this.selectedItem != value)
{
this.selectedItem = value;
this.OnPropertyChanged();
}
}
}
}
 

Example for ComboBox No Null Value can be found in the ComboBox/How To section from the SDK
Browser Application.
 

See Also
 Key Features
 Data Binding
 Editing
 Searching
 Templates

715
Telerik UI for Xamarin

ComboBox with Clear Selection in Drop


Down
The following article will show you how to display a clear button inside the dropdown of a ComboBox
and clar the selected item from it.

Example
For this example we will need to add the clear button (in our case for the demo we will use a Label)
inside the drop down header. So we will use the ComboBox HeaderTemplate property.

XAML
<local:SelectedItemToColorConverter x:Key="SelectedItemToColorConverter"/>

716
Telerik UI for Xamarin

<DataTemplate x:Key="ComboBoxClearButtonHeaderTemplate">
<telerikPrimitives:RadBorder>
<telerikPrimitives:RadBorder.MinimumHeightRequest>
<OnPlatform x:TypeArguments="x:Double">
<On Platform="iOS" Value="44"/>
<On Platform="Android" Value="48"/>
<On Platform="UWP" Value="32"/>
</OnPlatform>
</telerikPrimitives:RadBorder.MinimumHeightRequest>
<telerikPrimitives:RadBorder.BorderColor>
<OnPlatform x:TypeArguments="Color" Default="#ECECEC">
<On Platform="UWP" Value="Transparent"/>
</OnPlatform>
</telerikPrimitives:RadBorder.BorderColor>
<telerikPrimitives:RadBorder.BackgroundColor>
<OnPlatform x:TypeArguments="Color" Default="#F8F8F8">
<On Platform="UWP" Value="Accent"/>
</OnPlatform>
</telerikPrimitives:RadBorder.BackgroundColor>
<telerikPrimitives:RadBorder.BorderThickness>
<OnPlatform x:TypeArguments="Thickness" Default="0, 0, 0, 1">
<On Platform="UWP" Value="0"/>
</OnPlatform>
</telerikPrimitives:RadBorder.BorderThickness>
<Label Text="Select City..."
VerticalTextAlignment="Center"
BackgroundColor="{Binding SelectedItem, Converter={StaticResource
SelectedItemToColorConverter}}"
TextColor="Black">
<Label.Padding>
<OnPlatform x:TypeArguments="Thickness">
<On Platform="iOS" Value="3, 12, 0, 13"/>
<On Platform="Android" Value="8, 13, 0, 13"/>
<On Platform="UWP" Value="10, 6, 0, 6"/>
</OnPlatform>
</Label.Padding>
<Label.GestureRecognizers>
<TapGestureRecognizer Command="{Binding ClearSelectionCommand}"/>
</Label.GestureRecognizers>
</Label>
</telerikPrimitives:RadBorder>
</DataTemplate>
 

Here is the ComboBox definition:

XAML
<telerikInput:RadComboBox Grid.Row="1"
ItemsSource="{Binding Items}"
SelectedItem="{Binding SelectedItem, Mode=TwoWay}"
HeaderTemplate="{StaticResource ComboBoxClearButtonHeaderTemplate}"
IsDropDownOpen="{Binding IsDropDownOpen, Mode=TwoWay}"
Placeholder="Select City..."

717
Telerik UI for Xamarin

DisplayMemberPath="Name"
IsClearButtonVisible="False"
SelectionMode="Single"
Margin="10, 0, 10, 0">
<telerikInput:RadComboBox.BindingContext>
<local:ViewModel/>
</telerikInput:RadComboBox.BindingContext>
</telerikInput:RadComboBox>
 

the business model used:

C#
public class City
{
public string Name { get; set; }
public int Population { get; set; }
}
 

Next we will need a clear selection command in our ViewModel, then bind it to the
Label.TapGestureRecognizer Command inside the HeaderTemplate. Here is the ViewModel used:

C#
public class ViewModel : NotifyPropertyChangedBase
{
private City selectedItem;
private bool isDropDownOpen;

public ViewModel()
{
this.Items = new ObservableCollection<City>
{
new City { Name = "Tokyo", Population = 13929286 },
new City { Name = "New York", Population = 8623000 },
new City { Name = "London", Population = 8908081 },
new City { Name = "Madrid", Population = 3223334 },
new City { Name = "Los Angeles", Population = 4000000},
new City { Name = "Paris", Population = 2141000 },
new City { Name = "Beijing", Population = 21540000 },
new City { Name = "Singapore", Population = 5612000 },
new City { Name = "New Delhi", Population = 18980000 },
new City { Name = "Bangkok", Population = 8305218 },
new City { Name = "Berlin", Population = 3748000 },
};

this.ClearSelectionCommand = new Command(this.OnClearSelectionCommandExecuted);


}

public ObservableCollection<City> Items { get; set; }


public ICommand ClearSelectionCommand { get; set; }

718
Telerik UI for Xamarin

public City SelectedItem


{
get
{
return this.selectedItem;
}
set
{
if (this.selectedItem != value)
{
this.selectedItem = value;
this.OnPropertyChanged();
}
}
}

public bool IsDropDownOpen


{
get
{
return this.isDropDownOpen;
}
set
{
if (this.isDropDownOpen != value)
{
this.isDropDownOpen = value;
this.OnPropertyChanged();
}
}
}

private void OnClearSelectionCommandExecuted(object obj)


{
this.SelectedItem = null;
this.IsDropDownOpen = false;
}
}
 

and the SelectedItemToColorConverter class:

C#
public class SelectedItemToColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo
culture)
{
var isUWP = Device.RuntimePlatform == Device.UWP;
return value == null
? isUWP ? Color.Accent : Color.FromHex("#F8F8F8")
: isUWP ? Color.FromHex("#F2F2F2") : Color.White;
}

719
Telerik UI for Xamarin

public object ConvertBack(object value, Type targetType, object parameter,


CultureInfo culture)
{
throw new NotImplementedException();
}
}
 

Example for Clear Selection in DropDown can be found in the ComboBox/How To section from the
SDK Browser Application.
 

See Also
 Key Features
 Data Binding
 Editing
 Searching
 Templates

720
Telerik UI for Xamarin

ComboBox Clear Text when DropDown is


Closed
The following article will show you how to clear the Text of the ComboBox when the
SelectionMode is Multiple and the dropdown is closed.

Example
Here are the steps needed to achieve the functionality describe above.

First, if we want to clear the Text, the control should be in Editable mode. In addition we will use
Multiple Selection:

XAML

721
Telerik UI for Xamarin

<telerikInput:RadComboBox x:Name="comboBox"
Grid.Row="1"
BackgroundColor="White"
ItemsSource="{Binding Items}"
Text="{Binding Text, Mode=TwoWay}"
DisplayMemberPath="Name"
SearchTextPath="Name"
SelectionMode="Multiple"
IsDropDownClosedOnSelection="False"
IsEditable="True"
Margin="10, 0, 10, 0"
Unfocused="comboBox_Unfocused">
<telerikInput:RadComboBox.BindingContext>
<local:ViewModel/>
</telerikInput:RadComboBox.BindingContext>
</telerikInput:RadComboBox>
 

Inside the ComboBox Unfocused event we will set the ComboBox.Text prioperty to
srting.Empty:

C#
private void comboBox_Unfocused(object sender, FocusEventArgs e)
{
this.comboBox.Text = string.Empty;
}
 

the business model used:

C#
public class City
{
public string Name { get; set; }
public int Population { get; set; }
}
 

Here is the ViewModel used:

C#
public class ViewModel : NotifyPropertyChangedBase
{
private string text;

public ViewModel()
{
this.Items = new ObservableCollection<City>
{
new City { Name = "Tokyo", Population = 13929286 },
new City { Name = "New York", Population = 8623000 },

722
Telerik UI for Xamarin

new City { Name = "London", Population = 8908081 },


new City { Name = "Madrid", Population = 3223334 },
new City { Name = "Los Angeles", Population = 4000000},
new City { Name = "Paris", Population = 2141000 },
new City { Name = "Beijing", Population = 21540000 },
new City { Name = "Singapore", Population = 5612000 },
new City { Name = "New Delhi", Population = 18980000 },
new City { Name = "Bangkok", Population = 8305218 },
new City { Name = "Berlin", Population = 3748000 },
};
}

public ObservableCollection<City> Items { get; set; }

public string Text


{
get
{
return this.text;
}
set
{
if (this.Text != value)
{
this.text = value;
this.OnPropertyChanged();
}
}
}
}
 

Example for Clear Text when DropDown is closed can be found in the ComboBox/How To section
from the SDK Browser Application.
 

See Also
 Key Features
 Data Binding
 Editing
 Searching
 Templates

723
Telerik UI for Xamarin

Overview
Telerik RadChat for Xamarin is a UI component that enables easy implementation of conversational
UI in Xamarin applications, whether by utilizing certain chatbot framework, by following a predefined
logical tree, or just for integrating peer-to-peer chat capabilities.

Key features
 A variety of chat items for great user experience: You could choose between simple text
messages, various pickers such as list view, calendar, date and time pickers, and cards. For
more details go to Chat Items Overview topic.
 Highly customizable messages: You have full control over the visual appearance of the chat
items. Through the provided ItemTemplateSelector you can apply different template and
styling to the chat items according to a certain condition. Check ItemTemplateSelector help
article for more information on this.
 MVVM Support: With RadChat control you could easily utilize the Model-View-ViewModel
pattern. This could be achieved through the ItemsSource property that can be bound/set to a

724
Telerik UI for Xamarin

collection of any data items that should be then converted into chat items. For detailed
information on this check MVVM Support topic.
 Integration with conversational UI APIs: RadChat control can be used with all the major
conversational UI APIs or services such as Microsoft Bot, Google’s API.AI, Amazon LEX,
and more.
 Theming Support: RadChat comes with built-in theming support that helps you achieve
consistent look with the rest controls from Telerik UI for Xamarin suite. To learn more about
this go to Theme Overview.

Check out RadChat Getting Started help article that shows how to use it in a basic scenario.
 

See Also
 Chat Items
 ItemTemplateSelector
 MVVM Support

725
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a RadChat control in your application.

 Setting up the app


 Adding the required Telerik references
 Adding RadChat control

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic. Note that RadChat control does not have a separate nuget package.
 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadChat component:

Platform Assemblies
Portable Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.ConversationalUI.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.Primitives.dll
Android Telerik.Xamarin.Android.Common.dll
Telerik.Xamarin.Android.Data.dll
Telerik.Xamarin.Android.Input.dll
Telerik.Xamarin.Android.List.dll
Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.ConversationalUI.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.Primitives.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.ConversationalUI.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.Input.dll

726
Telerik UI for Xamarin

Telerik.XamarinForms.Primitives.dll
UWP Telerik.Core.dll
Telerik.Data.dll
Telerik.UI.Xaml.Controls.Data.UWP.dll
Telerik.UI.Xaml.Input.UWP.dll
Telerik.UI.Xaml.Primitives.UWP.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.ConversationalUI.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.Primitives.dll

3. Adding RadChat control


You could use one of the following approaches:

Drag the control from the Toolbox.

Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML or C#.

The snippet below shows a simple RadChat definition:

XAML
<telerikConversationalUI:RadChat x:Name="chat" />
 

In addition to this you need to add the following namespace:

XAML
xmlns:telerikConversationalUI="clr-namespace:Telerik.XamarinForms.ConversationalUI;ass
embly=Telerik.XamarinForms.ConversationalUI"
 

So, for a simple demonstration purpose a sample echo bot will be defined.

C#
public class RepeatBotService
{
private Action<string> onReceiveMessage;
internal void AttachOnReceiveMessage(Action<string> onMessageReceived)
{
this.onReceiveMessage = onMessageReceived;
}

727
Telerik UI for Xamarin

internal void SendToBot(string text)


{
Task.Delay(500).ContinueWith(t => this.onReceiveMessage?.Invoke(text));
}
}
 

Then, initialize the RepeatBotService and subscribe to the CollectionChanged event of the Items
collection of the Chat instance:

C#
private RepeatBotService botService;
private Author botAuthor;

public ChatGettingStartedXaml()
{
InitializeComponent();

this.botService = new RepeatBotService();


this.botService.AttachOnReceiveMessage(this.OnBotMessageReceived);
this.botAuthor = new Author { Name = "botty"};

((INotifyCollectionChanged)this.chat.Items).CollectionChanged +=
ChatItems_CollectionChanged; ;
}
 

Finally, add the needed event handlers:

C#
private void ChatItems_CollectionChanged(object sender,
NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
TextMessage chatMessage = (TextMessage)e.NewItems[0];
if (chatMessage.Author == chat.Author)
{
this.botService.SendToBot(chatMessage.Text);
}
}
}
private void OnBotMessageReceived(string message)
{
Device.BeginInvokeOnMainThread(() =>
{
TextMessage textMessage = new TextMessage();
textMessage.Data = message;
textMessage.Author = this.botAuthor;
textMessage.Text = message;
chat.Items.Add(textMessage);
});

728
Telerik UI for Xamarin

}
 

Figure 1: RadChat Getting Started

SDK Browser and QSF applications contain different examples that show RadChat's main features.
You can find the applications in the Examples and QSF folders of your local Telerik UI for Xamarin
installation.
 

See Also
 Key Features

729
Telerik UI for Xamarin

Key Features
RadChat is a Xamarin UI component that can be used for chatbots and chat-based user interfaces.
In this topic we will go through the basic properties of the Chat component as well as the key
features it provides.

Basic Setup
RadChat exposes the following properties you could use to setup the component:

 Author – represents the current user who sends messages using the Chat UI. This instance
determines the messages alignment – incoming messages are placed on the left, outgoing
messages - on the right;
 Message – defines the current message typed into the input field.
 Items collection – contains all the chat items included in the conversation such
TextMessages, PickerItems, etc. For more details on the available chat items go to Chat
Items topic.
 Picker – defines the ChatPicker that is shown either as overlay over the messages’ view or
inline as part of the conversation and could display different pickers in order to provide the
end user with a selection of choices. Go to ChatPicker topic for more details on the matter.

MVVM and Commands Support

730
Telerik UI for Xamarin

The Chat control supports data binding through the ItemsSource property that can be bound to a
collection of any data objects which then have to be converted into chat items. In addition, you can
implement the MVVM pattern through the provided commands of both Chat and ChatPicker controls.

You could find detailed instructions on how to use the Chat component in a MVVM setup in the
MVVM Support and Commands topics.

See Also
 Chat Items
 ChatPicker
 MVVM Support
 ItemTemplateSelector

731
Telerik UI for Xamarin

Control Template
RadChat's visual appearance is defined through a Control Template. In order to customize the way
the Conversational UI looks, you would need to take the default ControlTemplate and modify it.

This topic gives an overview of the ControlTemplate of the Chat control, so you can copy it to your
app and make changes.

The original ControlTemplate

The XAML defined below relies on the following namespaces to be set:

XAML
xmlns:telerikCommon="clr-namespace:Telerik.XamarinForms.Common;assembly=Telerik.Xamari
nForms.Common"
xmlns:telerikConversationalUI="clr-namespace:Telerik.XamarinForms.ConversationalUI;ass
embly=Telerik.XamarinForms.ConversationalUI"
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

Then here is the RadChat default control template. Add it to the Page resources:

XAML
<ResourceDictionary>
<telerikConversationalUI:ChatListViewMarginConverter
x:Key="ChatListViewMarginConverter" />

<ControlTemplate x:Key="RadChat_ControlTemplate">
<Grid telerikInput:KeyboardHelper.IsTranslationTarget="True"
RowSpacing="2">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<telerikConversationalUI:ChatListView
telerikCommon:StyleManager.InheritedStyleClass="{TemplateBinding ActualStyleClass}"
AutoScrollMode="{TemplateBinding AutoScrollMode}"
ScrollMediator="{TemplateBinding ActualScrollMediator}"
Margin="{Binding Height, Source={x:Reference PickerContainer},
Converter={StaticResource ChatListViewMarginConverter}}"
ItemTemplate="{TemplateBinding ItemTemplateSelector}"
ItemsSource="{TemplateBinding Items}"
AutomationProperties.Name="ChatListView" />
<telerikCommon:RadContentView
telerikCommon:StyleManager.InheritedStyleClass="{TemplateBinding ActualStyleClass}"
Grid.Row="1"
Content="{TemplateBinding TypingIndicator}" />
<telerikCommon:RadContentView

732
Telerik UI for Xamarin

telerikCommon:StyleManager.InheritedStyleClass="{TemplateBinding ActualStyleClass}"
x:Name="PickerContainer"
VerticalOptions="End"
Content="{TemplateBinding Picker}" />
<Grid x:Name="PART_InputAreaGrid"
Grid.Row="2"
Padding="5, 0, 0, 0"
telerikInput:KeyboardHelper.IsTranslationPivot="True">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>

<telerikConversationalUI:ChatEntry
telerikCommon:StyleManager.InheritedStyleClass="{TemplateBinding
ActualStyleClass}"
Text="{TemplateBinding Message, Mode=TwoWay}"
BackgroundColor="Transparent"
VerticalOptions="Center"
CompletedCommand="{TemplateBinding ActualSendMessageCommand}"
FocusMediator="{TemplateBinding FocusMediator}"
telerikInput:KeyboardHelper.IsTranslationSource="True" />

<telerikInput:RadButton x:Name="PART_SendMessageButton"
telerikCommon:StyleManager.InheritedStyleClass="{TemplateBinding
ActualStyleClass}"
Grid.Column="1"
Margin="0, 0, 10, 0"
BackgroundColor="Transparent"
Command="{TemplateBinding ActualSendMessageCommand}"
WidthRequest="30"
HeightRequest="30"
VerticalOptions="Center" />
</Grid>
</Grid>
</ControlTemplate>
</ResourceDictionary>
 

Finally, use the custom ControlTemplate as a StaticResource on any instance of RadChat:

XAML
<telerikConversationalUI:RadChat x:Name="chat"
ControlTemplate="{StaticResource RadChat_ControlTemplate}"/>
 

See Also
 Key Features
 Chat Items
 ItemTemplateSelector

733
Telerik UI for Xamarin

Chat Items
RadChat works with a collection of ChatItem objects. The control provides different chat items that
you could use, such as the basic TextMessage as well as various pickers (itempicker, datapicker,
timepicker) and predefined cards (defined through a cardpicker).

This section covers the specific details of the different chat items RadChat provides:

 Message - the basic message unit in RadChat; apart from the text of the message itself, each
TextMessage instance contains information about the Author of the message as well as any
additional data;
 Time Break - used to encapsulate messages in a conversation by a certain condition such as
read/unread, time intervals or any other you would choose. It is visualizes as a dividing line
across the messages board with a text message attached to it.
 PickerItem - special ChatItem type which contains RadChatPicker control used for providing
a selection to the end user. Depending on the information that is presented and the choice
that should be made, the pickers can be one of the types listed below:
 DatePicker – for displaying a Calendar to choose a date;
 TimePicker - for displaying a clock view to choose a time;
 ItemPicker – for presenting a list of suggestions the end user could choose from;
 CardPicker - for presenting a list of cards with structured layout;

Additionally, you could create your own chat items with custom item templates and add them to the
Items collection of the control. For more details go to MVVM Support and ItemTemplateSelector
topics.
 

See Also
 Messages
 Time Break
 PickerItem
 MVVM Support
 ItemTemplateSelector

734
Telerik UI for Xamarin

Messages
ChatMessage is the basic message unit in RadChat. It contains information about the Author of the
message as well as any additional data regarding the message.

The Author property is of type Telerik.XamarinForms.ConversationalUI.Author and exposes the


following properties:

 Name – author name;


 Avatar – image related to the author, displayed in the Chat UI;
 Data - you could use it to preserve additional information about the author;

By default, when the end user types in the textbox and confirms the message, it is set to the to
RadChat's Message property. In addition, the SendMessage event is fired each time a new message
is about to be added to the chat UI. It is allowed to modify the message itself.

TextMessage
The TextMessage is intended to be used for sending a simple string type message. It derives from
ChatMessage and provides an additional Text property which holds the string message.

Adding a message

You could create a sample TextMessage message like this:

C#
var bot = new Author() { Name = "bot", Avatar = "SampleAvatar.png" };
chat.Items.Add(new TextMessage { Author = bot, Text = "Hi." });
chat.Items.Add(new TextMessage { Author = bot, Text = "This is a message." });
 

And here is the result:

735
Telerik UI for Xamarin

See Also
 Key Features

736
Telerik UI for Xamarin

Time Break
TimeBreak item of RadChat is intended to encapsulate a group of messages according to a certain
condition, such as given time intervals or read/unread messages. It is visualized as a dividing line
across the messages board with a text message attached to it.

TimeBreak derives from ChatItem and provides an additional Text property which holds the string
message.

Adding a TimeBreak

You could create a sample TimeBreak item like this:

C#
chat.Items.Add(new TextMessage { Author = bot, Text = "Hello there" });
chat.Items.Add(new TimeBreak() { Text = "Unread" });
chat.Items.Add(new TextMessage() { Author = bot, Text = "How are you today?"});
 

And here is the result:

See Also
 Key Features
 Messages

737
Telerik UI for Xamarin

Overview
RadChat offers different pickers to present the user a selection of choices either as part of the
conversation, or over the messages' view.

Depending on the information that is presented and the choice that should be made, the pickers can
be one of the types listed below.

 DatePicker – for displaying a Calendar to choose a date;


 TimePicker - for displaying a clock view to choose a time;
 ItemPicker – for presenting a list of suggestions the end user could choose from;
 CardPicker - for presenting a list of cards with structured layout;

Each of these pickers is part of the RadChatPicker control and is defined through the corresponding
PickerContext property, namely DatePickerContext, TimPickerContext, ItemPickerContext, etc,

RadChatPicker can be used in three different ways:

 Inline as part of the conversation – through a PickerItem added to the Chat’s Items collection.
 Inside the Chat but not part of the conversation - the picker is placed between the entry and the
conversation; implemented through the RadChat’s Picker property.
 As a separate ChatPicker control - shown outside the RadChat control.

Inline as part of the conversation


In this case you would need to create an item of type PickerItem that actually derives from the
ChatItem, set its Context and add it to the Items collection of the Chat. Here is a quick example:

C#
DatePickerContext context = new DatePickerContext {
MinDate = new DateTime(2019, 1, 1),
MaxDate = new DateTime(2019, 2, 2),
DisplayDate = new DateTime(2019, 1, 16)};
PickerItem pickerItem = new PickerItem { Context = context };
chat.Items.Add(new TextMessage { Text = "Select a date", Author = chat.Author });
chat.Items.Add(pickerItem);

context.PropertyChanged += (s, e) =>


{
if (e.PropertyName == "SelectedDate")
{
if (context.SelectedDate != null)
{
chat.Items.Remove(pickerItem);
chat.Items.Add(new TextMessage { Author = chat.Author, Text = "" +
context.SelectedDate });
}
}
};

738
Telerik UI for Xamarin

When the user makes a selection, you can add a new TextMessage with the SelectedDate and
remove the PickerItem from the conversation.

Figure 1: RadChat with an inline DatePicker

Inside the Chat but not part of the conversation


If you choose this approach you would need to create a RadChatPicker instance and set it to the
Picker property of the Chat:

XAML
<telerikConversationalUI:RadChat x:Name="chat">
<telerikConversationalUI:RadChat.Picker>
<telerikConversationalUI:RadChatPicker x:Name="picker"
IsOkButtonVisible="False"
IsCancelButtonVisible="False"
BackgroundColor="LightGray" />
</telerikConversationalUI:RadChat.Picker>
</telerikConversationalUI:RadChat>
 

Then, when you need to display any of the available pickers, you will have to set the Context
property of the ChatPicker. Check the example below with DatePickerContext:

C#
DatePickerContext context = new DatePickerContext

739
Telerik UI for Xamarin

{
MinDate = new DateTime(2019, 1, 1),
MaxDate = new DateTime(2019, 2, 2),
DisplayDate = new DateTime(2019, 1, 16)
};

context.PropertyChanged += (s, e) =>


{
if (e.PropertyName == "SelectedDate")
{
if (context.SelectedDate != null)
{
chat.Items.Add(new TextMessage { Author = this.chat.Author, Text = "" +
context.SelectedDate });
(chat.Picker as RadChatPicker).Context = null;
}
}
};
(chat.Picker as RadChatPicker).Context = context;
 

When the user chooses a date, the Context is reset to null and a new TextMessage with the
SelectedDate can be added to the conversation.

Figure 2: RadChat with DatePicker between the entry and the conversation

In the example above, RadChatPicker is used for immediate selection by setting its
IsOkButtonVisible and IsCancelButtonVisible to false. You could also show Ok and Cancel buttons
and use the provided events/commands in order to handle the selection.

740
Telerik UI for Xamarin

See Also
 DatePicker
 TimePicker
 ItemPicker
 CardPicker

741
Telerik UI for Xamarin

DatePicker
RadChatPicker control provides DatePickerContext that can be used to display a Calendar to
choose a date.

DatePickerContext exposes the following properties you could use to provide a list of possible
options to the user:

 SelectedDate - defines the currently selected date;


 MinDate - defines the min date that can be displayed and selected;
 MaxDate - defines the max date that can be displayed and selected;
 DisplayDate - defines a date in the current view;

Here is a quick example on how to user DatePicker:

C#
DatePickerContext context = new DatePickerContext {
MinDate = new DateTime(2019, 1, 1),
MaxDate = new DateTime(2019, 2, 2),
DisplayDate = new DateTime(2019, 1, 16)};
PickerItem pickerItem = new PickerItem { Context = context };
chat.Items.Add(new TextMessage { Text = "Select a date", Author = chat.Author });
chat.Items.Add(pickerItem);

context.PropertyChanged += (s, e) =>


{
if (e.PropertyName == "SelectedDate")
{
if (context.SelectedDate != null)
{
chat.Items.Remove(pickerItem);
chat.Items.Add(new TextMessage { Author = chat.Author, Text = "" +
context.SelectedDate });
}
}
};
 

Figure 1: Chat with DatePicker

742
Telerik UI for Xamarin

See Also
 ChatPicker
 TimePicker
 ItemPicker
 CardPicker

743
Telerik UI for Xamarin

TimePicker
RadChatPicker control provides TimePickerContext that can be used to display a clock view to
choose a time.

TimePickerContext exposes the following properties you could use to adjust the clock items:

 SelectedValue - defines the currently selected time;


 StartTime - it is of type TimeSpan and represents the starting time of the clock's items.
 EndTime - it is of type TimeSpan and corresponds to the time of the last clock item.
 TimeInterval - it is also of type TimeSpan and defines the step between the clock's items.
Default value is 1 hour.

Here is a quick example on how to user TimePicker in RadChat:

C#
TimePickerContext context = new TimePickerContext
{
StartTime = TimeSpan.FromHours(1),
EndTime = TimeSpan.FromHours(5),
};
PickerItem pickerItem = new PickerItem { Context = context };
chat.Items.Add(new TextMessage { Text = "Select a time" });
chat.Items.Add(pickerItem);
context.PropertyChanged += (s, e) =>
{
if (e.PropertyName == "SelectedValue")
{
if (context.SelectedValue != null)
{
chat.Items.Remove(pickerItem);
chat.Items.Add(new TextMessage { Author = chat.Author, Text = "" +
context.SelectedValue });
}
}
};
 

Figure 1: Chat with TimePicker

744
Telerik UI for Xamarin

See Also
 ChatPicker
 TimePicker
 ItemPicker
 CardPicker

745
Telerik UI for Xamarin

ItemPicker
RadChatPicker control provides ItemPickerContext that can be used to display a list of options the
end user could choose from.

ItemPickerContext exposes the following properties you could use to provide a list of possible
options to the user:

 ItemsSource - defines the data source used to generate the content of the ItemPicker
control;
 SelectionMode - ItemPicker allows users to select one or many items out of the provides
ItemsSource;
 SelectedItems - defines the currently selected items;
 SelectedItem - defines the last selected item;

Here is a quick example on how to user ItemPicker:

C#
ItemPickerContext context = new ItemPickerContext
{
ItemsSource = new List<string>() { "2 days", "5 days", "7 days", "Another period"
}
};
PickerItem pickerItem = new PickerItem { Context = context, HeaderText = "Select an
item" };

chat.Items.Add(pickerItem);
context.PropertyChanged += (s, e) =>
{
if (e.PropertyName == "SelectedItem")
{
if (context.SelectedItem != null)
{
chat.Items.Remove(pickerItem);
chat.Items.Add(new TextMessage { Author = chat.Author, Text = "" +
context.SelectedItem });
}
}
};
 

Figure 1: Chat with ItemPicker

746
Telerik UI for Xamarin

See Also
 ChatPicker
 DatePicker
 TimePicker
 CardPicker

747
Telerik UI for Xamarin

CardPicker Overview
RadChatPicker control provides CardPickerContext that can be used to display a list of cards. Each
card presents more complex information in a user-friendly structured manner and allows the user to
interact with it.

CardPickerContext exposes the following property:

 Cards - it is of type IEnumerable<CardContext> and contains the available Cards defined by


the CardContext;

Depending on the information that is presented, the CardContext can be one of the following types:

 BasicCardContext - for displaying a card with Title, SubTitle and Descrption;


 ImageCardContext - derives from BasicCardContext with an additional Image property;

Here is a quick example with BasicCardContext:

C#
PickerItem pickerItem = new PickerItem();
var context = new CardPickerContext { Cards = this.GetCards(pickerItem) };
pickerItem.Context = context;
chat.Items.Add(new TextMessage { Text = "Select a destination" });
chat.Items.Add(pickerItem);
 

And the used GetCards() method:

C#
private IEnumerable<CardContext> GetCards(ChatItem chatItem)
{
List<CardContext> cards = new List<CardContext>()
{
new BasicCardContext() {Title="Rome", Subtitle="Italy", Description="Italy’s
capital is one of the world’s most romantic and inspiring cities"},
new BasicCardContext() {Title="Barcelona", Subtitle="Spain",
Description="Barcelona is an enchanting seaside city with remarkable architecture"}
};
return cards;
}
 

Figure 1: RadChat with BasicCard

748
Telerik UI for Xamarin

Cards Actions

Each card allows you to add a certain action that can be handled through a command. The
CardContext exposes an Actions collection of type IEnumerable<CardActionContext> that supplies
all the details needed for handling the action.

CardActionContext provides the following properties:

 Text - represents the action inside the Card layout;


 Command - the command that is raised when the user selects that action;
 Data - can be used to preserve additional details if needed;

The next snippet uses the Cards defined in the previous example and add Actions to them.

C#
private IEnumerable<CardContext> GetCards(ChatItem chatItem)
{
List<CardContext> cards = new List<CardContext>()
{
new BasicCardContext() {
Title ="Rome",
Subtitle ="Italy",
Description ="Italy’s capital is one of the world’s most romantic and inspiring
cities",
Actions = GetCardActions(chatItem, "Rome")},
new BasicCardContext() {
Title ="Barcelona",
Subtitle ="Spain",
Description ="Barcelona is an enchanting seaside city with remarkable
architecture",

749
Telerik UI for Xamarin

Actions = GetCardActions(chatItem, "Barcelona")}


};
return cards;
}

private ICollection<CardActionContext> GetCardActions(ChatItem chatItem, string Title)


{
var selectAction = new CardActionContext
{
Text = "Select",
Command = new Command(() =>
{
var index = chat.Items.IndexOf(chatItem);
chat.Items.RemoveAt(index);
chat.Items.Add(new TextMessage { Author = this.chat.Author, Text = "You
selected " + Title });
}),
};
return new List<CardActionContext>() { selectAction };
}
 

Figure 2: RadChat with BasicCard with Actions

See Also
 ChatPicker
 ImageCard

750
Telerik UI for Xamarin

ImageCard
ImageCardContext enhances the functionality of the BasicCardContext by providing an additional
Image property, so you could add an image to the Card definition.

Here is a quick example on how to create a sequence of ImageCards and show it through the
RadChat Picker's control.

C#
var cardsContext = new CardPickerContext {
Cards = new List<CardContext>()
{
new ImageCardContext() {
Title ="Rome",
Subtitle ="Italy",
Description ="Italy’s capital is one of the world’s most romantic and inspiring
cities",
Image = "RomeCard.png"
},
new ImageCardContext() {
Title ="Barcelona",
Subtitle ="Spain",
Description ="Barcelona is an enchanting seaside city with remarkable
architecture",
Image = "BarcelonaCard.png"
}}
};
(chat.Picker as RadChatPicker).Context = cardsContext;
 

Figure 1: RadChat with ImageCard

751
Telerik UI for Xamarin

See Also
 ChatPicker
 BasicCard

752
Telerik UI for Xamarin

MVVM Support
With RadChat control you could easily utilize the Model-View-ViewModel (MVVM) pattern. This could
be achieved through the ItemsSource property that can be bound/set to a collection of any data
items that should be then converted into chat items.

This help article will demonstrate how to use RadChat in MVVM scenarios.

First, create a sample class used to hold the needed information for the chat items:

C#
public class SimpleChatItem
{
public Author Author { get; set; }
public string Text { get; set; }
}
 

Create a ViewModel containing a collection of your SimpleChatItem items. You could also bind the
Chat's Author property that represents the end user typing in the input field.

C#
public class ViewModel : NotifyPropertyChangedBase
{
private Author me;
public ViewModel()
{
string suffix = Device.RuntimePlatform == Device.UWP ? "Assets/" : null;

this.Me = new Author() { Name = "human", Avatar = suffix + "sampleAvatar.png"};


this.Bot = new Author() { Name = "Bot", Avatar = suffix + "sampleBot.png"};

this.Items = new ObservableCollection<SimpleChatItem>();

// Simulate async data loading


Device.StartTimer(TimeSpan.FromMilliseconds(500), () =>
{
this.Items.Add(new SimpleChatItem { Author = this.Bot, Text = "Hi." });
this.Items.Add(new SimpleChatItem { Author = this.Bot, Text = "How can I help
you?" });
return false;
});
}
public Author Me
{
get
{
return this.me;
}

753
Telerik UI for Xamarin

set
{
if (this.me != value)
{
this.me = value;
this.OnPropertyChanged(nameof(this.Me));
}
}
}
public Author Bot { get; set; }
public IList<SimpleChatItem> Items { get; set; }
}
 

The next step is to create a Converter class of type IChatItemConverter in order to convert the data
items into chat messages and vice versa:

C#
public class SimpleChatItemConverter : IChatItemConverter
{
public ChatItem ConvertToChatItem(object dataItem, ChatItemConverterContext
context)
{
SimpleChatItem item = (SimpleChatItem)dataItem;
TextMessage textMessage = new TextMessage()
{
Data = dataItem,
Author = item.Author,
Text = item.Text
};
return textMessage;
}
public object ConvertToDataItem(object message, ChatItemConverterContext context)
{
ViewModel vm = (ViewModel)context.Chat.BindingContext;
return new SimpleChatItem { Author = vm.Me, Text = (string)message, };
}
}
 

And finally, all that is left is to add the RadChat control to your page with previously defined
ItemsSource and ItemConverter properties:

XAML
<ContentView.Resources>
<ResourceDictionary>
<local:SimpleChatItemConverter x:Key="SimpleChatItemConverter" />
</ResourceDictionary>
</ContentView.Resources>
<telerikConversationalUI:RadChat x:Name="chat"
Author="{Binding Me}"
ItemsSource="{Binding Items}"

754
Telerik UI for Xamarin

ItemConverter="{StaticResource SimpleChatItemConverter}">
<telerikConversationalUI:RadChat.BindingContext>
<local:ViewModel />
</telerikConversationalUI:RadChat.BindingContext>
</telerikConversationalUI:RadChat>
 

Figure 1: RadChat in MVVM setup

See Also
 Key Features
 Commands
 ItemTemplateSelector

755
Telerik UI for Xamarin

Typing Indicator
The TypingIndicator functionality of Conversational UI can be used to indicate that a participant (or
participants) is currently typing.

By default, the TypingIndicator is not visible. As soon as its Authors (or ItemsSource) collection is
updated, it is displayed with a text message indicating the authors’ names.

The text message is built according to the count of authors like this:

 If the collection of Authors contains 1 item: “[Author name] is typing”;


 If there are two authors: “[Author1 name] and [Author2 name] are typing”;
 In case of three authors: “[Author1 name], [Author2 name] and [Author3 name] are typing”;
 In case of more authors: [Author1 name], [Author2 name] and 2 others are typing”;

When the Authors (or ItemsSource) collection is cleared, the TypingIndicator is hidden.

In addition, by setting Text property the text message could be replaced with any other of your
choice.

Adding a TypingIndicator

In order to add a typing indicator just set TypingIndicator property of RadChat control:

XAML
<telerikConversationalUI:RadChat x:Name="chat">
<telerikConversationalUI:RadChat.TypingIndicator>
<telerikConversationalUI:TypingIndicator x:Name="typingIndicator" />
</telerikConversationalUI:RadChat.TypingIndicator>
</telerikConversationalUI:RadChat>
 

There are two ways to display the typing indicator:

Using Authors collection:

You can use directly Authors collection which is of type ObservableCollection to show the
participants who are currently typing. Here is a quick example:

C#
var author1 = new Author { Name = "Sandra" };
var author2 = new Author { Name = "John" };
chat.Author = author2;

chat.Items.Add(new TextMessage { Author = author2, Text = "Hello there" });


chat.Items.Add(new TextMessage { Author = author1, Text = "Hi, John" });

typingIndicator.Authors.Add(author1);

756
Telerik UI for Xamarin

typingIndicator.Authors.Add(author2);

Task.Delay(3000).ContinueWith(t =>
{
Device.BeginInvokeOnMainThread(() =>
{
this.typingIndicator.Authors.Clear();
this.chat.Items.Add(new TextMessage { Author = author2, Text = "What are you
doing today?" });
this.chat.Items.Add(new TextMessage { Author = author1, Text = "Do you have any
plans for the afternoon?" });
});
});
 

And the result is:

Using ItemsSource collection:

If you prefer the MVVM pattern, you can use ItemsSource property of the TypingIndicator -
ItemsSource property could be bound/set to a collection of any data items that should be then
converted into Author items.

First, create a sample Participant class which will hold the details for the participants in the
conversation:

C#
public class Participant
{

757
Telerik UI for Xamarin

public int ID { get; set; }


public string ShortName { get; set; }
public string Avatar { get; set; }
public bool IsAdmin { get; set; }
}
 

Create a ViewModel containing a collection of your Participant items:

C#
public class ViewModel
{
public ViewModel()
{
var author1 = new Participant { ID = 1, ShortName = "Sandra", IsAdmin = true };
var author2 = new Participant { ID = 2, ShortName = "John" };
var author3 = new Participant { ID = 3, ShortName = "Billy" };

this.TypingParticipants = new ObservableCollection<Participant>();

Device.StartTimer(TimeSpan.FromMilliseconds(500), () =>
{
this.TypingParticipants.Add(author1);
this.TypingParticipants.Add(author2);
this.TypingParticipants.Add(author3);
return false;
});
}
public IList<Participant> TypingParticipants { get; set; }
}
 

The next step is to create a Converter class of type IAuthorConverter in order to convert the data
items into Authors:

C#
public class ChatParticipantConverter : IAuthorConverter
{
public Author ConvertToAuthor(object dataItem, AuthorConverterContext context)
{
Participant participant = (Participant)dataItem;
return new Author()
{
Name = participant.ShortName,
Avatar = participant.Avatar,
Data = participant
};
}
}
 

And finally, all that is left is to add the RadChat control to your page with previously defined

758
Telerik UI for Xamarin

ItemsSource and ItemConverter properties of the TypingIndicator:

XAML
<ContentView.Resources>
<local:ChatParticipantConverter x:Key="ChatParticipantConverter" />
</ContentView.Resources>
<telerikConversationalUI:RadChat x:Name="chat">
<telerikConversationalUI:RadChat.TypingIndicator>
<telerikConversationalUI:TypingIndicator x:Name="typingIndicator"
ItemsSource="{Binding TypingParticipants}"
ItemConverter="{StaticResource ChatParticipantConverter}"/>
</telerikConversationalUI:RadChat.TypingIndicator>
</telerikConversationalUI:RadChat>
 

And here is result:

See Also
 Key Features
 MVVM Support

759
Telerik UI for Xamarin

ItemTemplateSelector
RadChat control exposes an ItemTemplateSelector property which you can use to apply different
templates to each chat item depending on a specific condition.

Default ItemTemplateSelector
Any change on the appearance of the chat items depends on the ChatItemTemplateSelector and the
containing templates and referenced Styles. The default selector includes separate templates for the
incoming and outgoing messages (so they're aligned on the left/right accordingly), as well as for
single and the first, middle and last messages (in case there area a few messages in a row) - this is
needed in order to achieve the "balloon" look & feel of the messages. In addition, the TimeBreak
template is also assigned through the ItemTemplateSelector.

Below you can find the default ItemTemplateSelector which you can use as a base for any further
customizations to the way the messages look.

In short, the default templates contain RadBorder (used to achieve the rounded edges), image
control (used for the avatar image) only for the single and first messages, and a Label for the text
message itself.

The snippet below contains the default templates and the accompanying styles:

XAML
<ResourceDictionary>
<Style x:Key="MessageImageStyle" TargetType="Image">
<Setter Property="WidthRequest" Value="24" />
<Setter Property="HeightRequest" Value="24" />
<Setter Property="VerticalOptions" Value="Start" />
</Style>

<Style x:Key="OutgoingMessageImageStyle" TargetType="Image"


BasedOn="{StaticResource MessageImageStyle}">
<Setter Property="HorizontalOptions" Value="End" />
<Setter Property="Margin" Value="0, 4, 10, 4" />
</Style>

<Style x:Key="IncomingMessageImageStyle" TargetType="Image"


BasedOn="{StaticResource MessageImageStyle}">
<Setter Property="HorizontalOptions" Value="Start" />
<Setter Property="Margin" Value="10, 4, 0, 4" />
</Style>

<Style x:Key="IncomingBorderStyle" TargetType="telerikPrimitives:RadBorder">


<Setter Property="BackgroundColor" Value="#FFFFFF" />
<Setter Property="Margin" Value="45, 0, 70, 0" />
<Setter Property="HorizontalOptions" Value="Start" />
</Style>

760
Telerik UI for Xamarin

<Style x:Key="OutgoingBorderStyle" TargetType="telerikPrimitives:RadBorder">


<Setter Property="BackgroundColor" Value="#E0E0E0" />
<Setter Property="Margin" Value="70, 0, 45, 0" />
<Setter Property="HorizontalOptions" Value="End" />
</Style>

<Style x:Key="DefaultLabelStyle" TargetType="Label">


<Setter Property="Margin" Value="20, 5, 20, 5" />
<Setter Property="FontSize" Value="16" />
<Setter Property="LineBreakMode" Value="WordWrap" />
<Setter Property="TextColor" Value="Black" />
<Setter Property="HorizontalOptions" Value="Start" />
</Style>

<Style x:Key="OutgoingLabelStyle" TargetType="Label" BasedOn="{StaticResource


DefaultLabelStyle}">
<Setter Property="HorizontalOptions" Value="End" />
</Style>

<DataTemplate x:Key="OutgoingSingleTemplate">
<Grid Padding="0, 2, 0, 10">
<Image Source="{Binding Author.Avatar}" Style="{StaticResource
OutgoingMessageImageStyle}" />
<telerikPrimitives:RadBorder Style="{StaticResource OutgoingBorderStyle}"
CornerRadius="7, 0, 7, 7" >
<Label Text="{Binding Text}" Style="{StaticResource OutgoingLabelStyle}" />
</telerikPrimitives:RadBorder>
</Grid>
</DataTemplate>

<DataTemplate x:Key="OutgoingFirstTemplate">
<Grid Padding="0, 2, 0, 2">
<Image Source="{Binding Author.Avatar}"
Style="{StaticResource OutgoingMessageImageStyle}" />
<telerikPrimitives:RadBorder Style="{StaticResource OutgoingBorderStyle}"
CornerRadius="7, 0, 0, 7" >
<Label Text="{Binding Text}" Style="{StaticResource OutgoingLabelStyle}" />
</telerikPrimitives:RadBorder>
</Grid>
</DataTemplate>

<DataTemplate x:Key="OutgoingMiddleTemplate">
<Grid Padding="0, 2, 0, 2">
<telerikPrimitives:RadBorder Style="{StaticResource OutgoingBorderStyle}"
CornerRadius="7, 0, 0, 7" >
<Label Text="{Binding Text}" Style="{StaticResource OutgoingLabelStyle}" />
</telerikPrimitives:RadBorder>
</Grid>
</DataTemplate>

<DataTemplate x:Key="OutgoingLastTemplate">
<Grid Padding="0, 2, 0, 10">
<telerikPrimitives:RadBorder Style="{StaticResource OutgoingBorderStyle}"
CornerRadius="7, 0, 7, 7" >

761
Telerik UI for Xamarin

<Label Text="{Binding Text}" Style="{StaticResource OutgoingLabelStyle}" />


</telerikPrimitives:RadBorder>
</Grid>
</DataTemplate>

<DataTemplate x:Key="IncomingSingleTemplate">
<Grid Padding="0, 2, 0, 10">
<Image Source="{Binding Author.Avatar}"
Style="{StaticResource IncomingMessageImageStyle}" />
<telerikPrimitives:RadBorder Style="{StaticResource IncomingBorderStyle}"
CornerRadius="0, 7, 7, 7" >
<Label Text="{Binding Text}" Style="{StaticResource DefaultLabelStyle}" />
</telerikPrimitives:RadBorder>
</Grid>
</DataTemplate>

<DataTemplate x:Key="IncomingFirstTemplate">
<Grid Padding="0, 2, 0, 2">
<Image Source="{Binding Author.Avatar}"
Style="{StaticResource IncomingMessageImageStyle}" />
<telerikPrimitives:RadBorder Style="{StaticResource IncomingBorderStyle}"
CornerRadius="0, 7, 7, 0" >
<Label Text="{Binding Text}" Style="{StaticResource DefaultLabelStyle}" />
</telerikPrimitives:RadBorder>
</Grid>
</DataTemplate>

<DataTemplate x:Key="IncomingMiddleTemplate">
<Grid Padding="0, 2, 0, 2">
<telerikPrimitives:RadBorder Style="{StaticResource IncomingBorderStyle}"
CornerRadius="0, 7, 7, 0" >
<Label Text="{Binding Text}" Style="{StaticResource DefaultLabelStyle}" />
</telerikPrimitives:RadBorder>
</Grid>
</DataTemplate>

<DataTemplate x:Key="IncomingLastTemplate">
<Grid Padding="0, 2, 0, 10">
<telerikPrimitives:RadBorder Style="{StaticResource IncomingBorderStyle}"
CornerRadius="0, 7, 7, 7" >
<Label Text="{Binding Text}" Style="{StaticResource DefaultLabelStyle}" />
</telerikPrimitives:RadBorder>
</Grid>
</DataTemplate>

<ControlTemplate x:Key="TimeBreakView_ControlTemplate">
<Grid Padding="10">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="Auto" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<BoxView BackgroundColor="{TemplateBinding Stroke}"

762
Telerik UI for Xamarin

HeightRequest="{TemplateBinding StrokeThickness}"
VerticalOptions="Center" />
<Label Text="{TemplateBinding Text}"
TextColor="{TemplateBinding TextColor}"
FontSize="{TemplateBinding FontSize}"
FontFamily="{TemplateBinding FontFamily}"
FontAttributes="{TemplateBinding FontAttributes}"
Grid.Column="1"
VerticalOptions="Center" />
<BoxView BackgroundColor="{TemplateBinding Stroke}"
HeightRequest="{TemplateBinding StrokeThickness}"
Grid.Column="2"
VerticalOptions="Center" />
</Grid>
</ControlTemplate>

<DataTemplate x:Key="TimeBreakTemplate">
<telerikConversationalUI:TimeBreakView Text="{Binding Text}"
ControlTemplate="{StaticResource TimeBreakView_ControlTemplate}" />
</DataTemplate>

<telerikConversationalUI:ChatItemTemplateSelector
x:Key="MyChatItemTemplateSelector"
IncomingFirstTextMessageTemplate="{StaticResource IncomingFirstTemplate}"
IncomingMiddleTextMessageTemplate="{StaticResource IncomingMiddleTemplate}"
IncomingSingleTextMessageTemplate="{StaticResource IncomingSingleTemplate}"
IncomingLastTextMessageTemplate="{StaticResource IncomingLastTemplate}"
OutgoingFirstTextMessageTemplate="{StaticResource OutgoingFirstTemplate}"
OutgoingMiddleTextMessageTemplate="{StaticResource OutgoingMiddleTemplate}"
OutgoingSingleTextMessageTemplate="{StaticResource OutgoingSingleTemplate}"
OutgoingLastTextMessageTemplate="{StaticResource OutgoingLastTemplate}"
TimeBreakTemplate="{StaticResource TimeBreakTemplate}" />
</ResourceDictionary>
 

You can make any changes to the templates and then assign the template selector to the
ItemTemplateSelector property of the Chat control:

XAML
<telerikConversationalUI:RadChat x:Name="chat"
ItemTemplateSelector="{StaticResource MyChatItemTemplateSelector}" />
 

Custom ItemTemplateSelector
You can also create a custom ChatItemTemplateSelector to conditionally apply different messages
styles depending on any of the used chat item properties.

Let's, for example, have the following ChatItem class with a custom MessageCategory property to
distinguish important messages:

763
Telerik UI for Xamarin

C#
public enum MessageCategory
{
Important,
Normal
}
public class SimpleChatItem
{
public Author Author { get; set; }
public string Text { get; set; }
public MessageCategory Category { get; set; }
}
 

Add a few sample Items to the Chat's ItemsSource:

C#
public class ViewModel : NotifyPropertyChangedBase
{
private Author me;
public ViewModel()
{
string prefix = Device.RuntimePlatform == Device.UWP ? "Assets/" : null;

this.Me = new Author() { Name = "human", Avatar = prefix + "sampleAvatar.png"


};
this.Bot = new Author() { Name = "Bot", Avatar = prefix + "sampleBot.png" };
this.Items = new ObservableCollection<SimpleChatItem>();

// Simulate async data loading


Device.StartTimer(TimeSpan.FromMilliseconds(500), () =>
{
this.Items.Add(new SimpleChatItem { Author = this.Bot, Text = "Hi.", Category =
MessageCategory.Normal });
this.Items.Add(new SimpleChatItem { Author = this.Bot, Text = "Please check our
new privacy policy here:...", Category = MessageCategory.Important });
return false;
});
}

public Author Me
{
get
{
return this.me;
}
set
{
if (this.me != value)
{
this.me = value;
this.OnPropertyChanged(nameof(this.Me));
}

764
Telerik UI for Xamarin

}
}
public Author Bot { get; set; }
public IList<SimpleChatItem> Items { get; set; }
}
 

You would need to supply an ItemsConverter as you're using custom items as demonstrated inside
MVVM Support topic.
 
C#
public class SimpleChatItemConverter : IChatItemConverter
{
public ChatItem ConvertToChatItem(object dataItem, ChatItemConverterContext
context)
{
SimpleChatItem item = (SimpleChatItem)dataItem;
TextMessage textMessage = new TextMessage()
{
Data = dataItem,
Author = item.Author,
Text = item.Text
};
return textMessage;
}
public object ConvertToDataItem(object message, ChatItemConverterContext context)
{
ViewModel vm = (ViewModel)context.Chat.BindingContext;
return new SimpleChatItem { Author = vm.Me, Text = (string)message,
Category=MessageCategory.Normal };
}
}
 

Create a CustomChatItemTemplateSelector class that derives from the ChatItemTemplateSelector:

C#
public class CustomChatItemTemplateSelector : ChatItemTemplateSelector
{
public DataTemplate ImportantMessageTemplate { get; set; }

protected override DataTemplate OnSelectTemplate(object item, BindableObject


container)
{
ChatItem chatItem = item as ChatItem;
var myItem = chatItem?.Data as SimpleChatItem;
if (myItem != null && myItem.Category == MessageCategory.Important)
{
return this.ImportantMessageTemplate;
}
return base.OnSelectTemplate(item, container);
}

765
Telerik UI for Xamarin

}
 

Create the needed XAML resources:

XAML
<ResourceDictionary>
<local:SimpleChatItemConverter x:Key="SimpleChatItemConverter" />

<Style x:Key="MessageImageStyle" TargetType="Image">


<Setter Property="Source" Value="{Binding Author.Avatar}" />
<Setter Property="WidthRequest" Value="30" />
<Setter Property="HeightRequest" Value="30" />
</Style>

<Style x:Key="IncomingMessageImageStyle" TargetType="Image"


BasedOn="{StaticResource MessageImageStyle}">
<Setter Property="HorizontalOptions" Value="Start" />
<Setter Property="Margin" Value="10, 0, 0, 0" />
</Style>

<DataTemplate x:Key="ImportantMessageTemplate">
<Grid Margin="0, 2, 0, 10">
<Image Style="{StaticResource IncomingMessageImageStyle}" />
<telerikPrimitives:RadBorder CornerRadius="0, 7, 7, 7"
Margin="45, 0, 50, 0"
HorizontalOptions="Start"
BackgroundColor="#FF0000">
<StackLayout Orientation="Horizontal" Margin="20, 0, 20, 0">
<Label Text="! " FontAttributes="Bold" FontSize="Medium" />
<Label Text="{Binding Text}" FontSize="Medium" />
</StackLayout>
</telerikPrimitives:RadBorder>
</Grid>
</DataTemplate>
<local:CustomChatItemTemplateSelector x:Key="CustomChatItemTemplateSelector"
ImportantMessageTemplate="{StaticResource ImportantMessageTemplate}" />
</ResourceDictionary>
 

Set it to the Chat's ItemTemplateSelector property:

XAML
<telerikConversationalUI:RadChat x:Name="chat"
Author="{Binding Me}"
ItemsSource="{Binding Items}"
ItemConverter="{StaticResource SimpleChatItemConverter}"
ItemTemplateSelector="{StaticResource CustomChatItemTemplateSelector}">
<telerikConversationalUI:RadChat.BindingContext>
<local:ViewModel />
</telerikConversationalUI:RadChat.BindingContext>
</telerikConversationalUI:RadChat>

766
Telerik UI for Xamarin

and add the telerikPrimitives namespace:

XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
 

Figure 1: RadChat with ItemTemplateSelector

See Also
 Time Break
 Key Features
 MVVM Support
 Commands

767
Telerik UI for Xamarin

Localization
Conversational UI for Xamarin provides language localization. In short, you can translate the used
across the Chat control phrases to other languages, so that your app can be adapted to different
regions.

To learn in details about the localization process of Telerik UI for Xamarin components, please go
through the common Localization and Globalization topic.
 
In RadChat you can localize the following string:

Localization Key Default Value


ConversationalUI_EntryWatermark Type a message...
The localization key refers to the watermark message that is shown in the input field of the Chat as
shown in the image below:

768
Telerik UI for Xamarin

See Also
 Chat Items
 ChatPicker
 MVVM Support
 ItemTemplateSelector

769
Telerik UI for Xamarin

Commands
RadChat allows you to attach commands that will be executed when certain actions such as
SendMessage occur.

Before proceeding check the MVVM Support topic for more details on how to use RadChat in a
MVVM setup.
 

Chat Commands
You could take advantage of the SendMessageCommand that is triggered by two actions when the
send-message button is clicked. The command is raised before the Chat auto-creates a ChatItem
and adds it to the Items.

Here is a quick example on how to define a command in the ViewModel and bind the
SendMessageCommand to it:

C#
public ViewModel()
{
this.Items = new ObservableCollection<ChatItem>();
this.NewMessageCommand = new Command(NewMessageCommandExecute);

this.MessagesLog = new ObservableCollection<string>();


}

public ObservableCollection<string> MessagesLog { get; set; }


public ICommand NewMessageCommand { get; set; }
public IList<ChatItem> Items { get; set; }
 

And the command Execute method:

C#
private void NewMessageCommandExecute(object obj)
{
var newMessage = (string)obj;
//any additional logic you need to implement
this.MessagesLog.Add("You just added a new message with text " + newMessage);
}
 

Following the definition of RadChat components:

XAML
<telerikConversationalUI:RadChat x:Name="chat"

770
Telerik UI for Xamarin

Grid.Row="1"
ItemsSource="{Binding Items}"
SendMessageCommand="{Binding NewMessageCommand}" />
 

ChatPicker Commands
RadChatPicker control exposes OkCommand and CancelCommand fired when the corresponding
"Ok" and "Cancel" buttons are clicked.

See Also
 Key Features
 MVVM Support
 ItemTemplateSelector

771
Telerik UI for Xamarin

Overview
RadDataForm for Xamarin is a customizable component allowing you to easily create a form for
collecting or editing business object data. The control supports different commit modes allowing you
to commit property values one by one or commit the whole form at once. You could also determine
at what moment the properties should be validated choosing between different validation modes.
The control lets you use rich set of editors out of the box.

Key features
 Built-in Editors: RadDataForm provides a set of built-in editors for the available primitive
types such as numeric, string, Boolean and enumerations. The control detects the types of
the data object’s properties and automatically displays the appropriate editor. For additional
details go to the Editors topic.
 Validation with Feedback: Telerik DataForm for Xamarin features built-in validation, which
gives you full control over the data collected through the control. You could check how to use
the validation functionality in Validate and Commit topic.
 Commit Modes: DataForm provides editing support with three types of commit modes to
determine when the edited value should be synchronized with the business object. Read
Validate and Commit topic for more info on this.
 Data Annotations Support: In order to customize the way data is interpreted in DataForm you
can use helpers in the form of Data Annotations. RadDataForm provides a number of data
annotations, such as ConverterAttribute, DisplayOptionsAttribute, ValidationAttribute and
others. For more details go to Data Annotations section in DataForm documentation.
 Grouping: RadDataForm provides collapsible groups option that will help significantly users
to navigate through large lists. For more info check DisplayOptionsAttribute topic.

772
Telerik UI for Xamarin

 Layouts: Provides support for stack and grid layout. Read more on this in the Layouts article.
 Read-only Mode: The control has a read-only mode for cases in which the end-user should
only see the values of the properties, rather than edit them. Check the ReadOnlyAttribute
topic for more details.

Check out RadDataForm Getting Started help article that shows how to use it in a basic scenario.
 

See Also
 Editors
 Validate and Commit
 Data Annotations
 Layouts
 DisplayOptionsAttribute
 ReadOnlyAttribute

773
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadDataForm control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadDataForm control
 Setting RadDataForm Source object

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadDataForm control you have to install the
Telerik.UI.for.Xamarin.Input nuget package. This nuget will automatically refer the
Telerik.UI.for.Xamarin.Primitives, Telerik.UI.for.Xamarin.Common, and
Telerik.UI.for.Xamarin.DataControls nuget packages. In additon inside the UWP project you will
need to add a reference to the Telerik.UI.Xaml.Controls.Data.UWP dll.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadDataForm component:

Platform Assemblies
Portable Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll
Android Telerik.Xamarin.Android.Common.dll
Telerik.Xamarin.Android.Data.dll
Telerik.Xamarin.Android.List.dll
Telerik.Xamarin.Android.Input.dll
Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll
iOS Telerik.Xamarin.iOS.dll

774
Telerik UI for Xamarin

Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll
UWP Telerik.Core.dll
Telerik.Data.dll
Telerik.UI.Xaml.Controls.Data.UWP.dll
Telerik.UI.Xaml.Input.UWP.dll
Telerik.UI.Xaml.Primitives.UWP.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll

3. Adding RadDataForm control


You could use one of the following approaches:

Drag the control from the Toolbox.

Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML or C#.

The snippet below shows a simple RadDataForm definition:

XAML
<telerikInput:RadDataForm x:Name="dataForm" />
 

C#
var dataForm = new RadDataForm();
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

C#
using Telerik.XamarinForms.Input;
 

4. Setting RadDataForm Source object


First, let's create a sample class that will be the source of the data form:

775
Telerik UI for Xamarin

C#
public class SourceItem : NotifyPropertyChangedBase
{
string name = "Anna";
double weight = 60.5;
int height = 163;
int age = 27;

[DisplayOptions(Header = "Name")]
public string Name
{
get { return this.name; }
set
{
if (value != this.name)
{
this.name = value;
OnPropertyChanged();
}
}
}

[DisplayOptions(Header = "Age")]
public int Age
{
get { return this.age; }
set
{
if (value != this.age)
{
this.age = value;
OnPropertyChanged();
}
}
}

[DisplayOptions(Header = "Weight (kg)")]


public double Weight
{
get { return this.weight; }
set
{
if (value != this.weight)
{
this.weight = value;
OnPropertyChanged();
}
}
}

[DisplayOptions(Header = "Height (cm)")]


public int Height
{

776
Telerik UI for Xamarin

get { return this.height; }


set
{
if (value != this.height)
{
this.height = value;
OnPropertyChanged();
}
}
}
}
 

Assign it to the Source property of RadDataForm:

XAML
<telerikInput:RadDataForm x:Name="dataForm">
<telerikInput:RadDataForm.Source>
<local:SourceItem />
</telerikInput:RadDataForm.Source>
</telerikInput:RadDataForm>
 

C#
var dataForm = new RadDataForm
{
Source = new SourceItem()
};
 

You also need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

C#
using Telerik.XamarinForms.Input;
 

After that you have to specify the editor types:

C#
dataForm.RegisterEditor(nameof(SourceItem.Age), EditorType.IntegerEditor);
dataForm.RegisterEditor(nameof(SourceItem.Name), EditorType.TextEditor);
dataForm.RegisterEditor(nameof(SourceItem.Weight), EditorType.DecimalEditor);
dataForm.RegisterEditor(nameof(SourceItem.Height), EditorType.IntegerEditor);
 

777
Telerik UI for Xamarin

This is the result:

SDK Browser and QSF applications contain different examples that show RadDataForm's main
features. You can find the applications in the Examples and QSF folders of your local Telerik UI for
Xamarin installation.
 

See Also
 DataForm Editors
 Project Wizard
 Getting Started on Windows
 Getting Started on Mac

778
Telerik UI for Xamarin

Data Source
Data Class
One way to set data form source is to use a class and decorate its properties with data annotations.
These data annotations are used to build metadata for each property used by the data form to
customize its UI. Here are listed all available data annotations:

 Display Options Attribute


 Ignore Attribute
 Read Only Attribute
 Data Source Key Attribute
 Validation Attribute
 Converter Attribute
 Display Value Format Attribute

Example
Here is a sample class decorated with annotations:

C#
public class Customer
{
[DisplayOptions(Group = "Basic Info", PlaceholderText = "First name", Header =
"First Name")]
[NonEmptyValidator("Please fill the first name", "OK")]
public string FirstName { get; set; }

[DisplayOptions(Group = "Basic Info", PlaceholderText = "Last Name", Header =


"Last Name")]
[NonEmptyValidator("Please fill the last name", "OK")]
public string LastName { get; set; }

[DisplayOptions(Group = "Additional Info", Header = "Age")]


[NumericalRangeValidator(0, 100)]
public int Age { get; set; }
}
 

Here is how to set an instance of the class as data form source:

C#
var dataForm = new RadDataForm
{
Source = new Customer()
};
 

779
Telerik UI for Xamarin

Third Party Data Source


Sometimes the source is not an instance of a specific class that can be decorated with data
annotations. In these cases you have to provide your own metadata through the
RadDataForm.MetadataProvider property.

Example
This example will demonstrate how to use a dictionary as data form source.

C#
var source = new Dictionary<string, string>();

source.Add("FirstName", "John");
source.Add("LastName", "Dow");
source.Add("Country", "Unknown");
 

You have to set a custom metadata provider that will provide information for each property, in this
case dictionary item. The data form will use this metadata when building its UI.

The metadata provider has to inherit from the PropertyMetadataProviderBase class:

C#
public class CustomMetadataProvider : PropertyMetadataProviderBase
{
private readonly List<IEntityProperty> entityProperties = new
List<IEntityProperty>();

public override List<IEntityProperty> EntityProperties


{
get
{
return entityProperties;
}
}

public override void Initialize(object source)


{
var sourceDictionary = source as Dictionary<string, string>;

foreach (var item in sourceDictionary)


{
var metadata = new EntityPropertyMetadata
{
Header = item.Key
};

var property = new CustomEntityProperty(item.Key, sourceDictionary, metadata);

this.entityProperties.Add(property);

780
Telerik UI for Xamarin

}
}
}
 

In the Initialize method you have to add the metadata for each dictionary item using the
EntityPropertyMetadata class. It contains all metadata information that can be set on a property and
you can modify it as per your needs.

You also need a custom entity property class that is responsible for committing the values entered in
the data form:

C#
public class CustomEntityProperty : IEntityProperty
{
private readonly Dictionary<string, string> dataItem;

private readonly string propertyName;


private readonly EntityPropertyMetadata metadata;

public CustomEntityProperty(string propertyName, Dictionary<string, string> item,


EntityPropertyMetadata metadata)
{
this.metadata = metadata;
this.propertyName = propertyName;
this.dataItem = item;
}

public object OriginalValue


{
get
{
return this.dataItem[propertyName];
}
}

public EntityPropertyMetadata Metadata


{
get
{
return this.metadata;
}
}

public object DataItem


{
get
{
return this.dataItem;
}
}

public string PropertyName

781
Telerik UI for Xamarin

{
get
{
return this.propertyName;
}
}

public object PropertyValue { get; set; }

public Type PropertyType


{
get
{
return typeof(string);
}
}

public bool IsReadOnly


{
get
{
return false;
}
}

public void Commit()


{
this.dataItem[propertyName] = (string)this.PropertyValue;
}
}
 

Here is the data form setup:

C#
dataForm.MetadataProvider = new CustomMetadataProvider();
dataForm.Source = source;
 

See Also
 DataForm Editors
 DataForm Layouts
 Validate and Commit

782
Telerik UI for Xamarin

Editors
The RadDataForm provides the following methods to replace the default editors:

 void RegisterEditor(string propertyName, EditorType editorType): Registers an editor type for


a property with a specific name.
 void RegisterEditor(Type propertyType, EditorType editorType): Registers an editor type for
a specific property type.

The editors registered for property name are with higher priority than the ones registered for property
type.
 

Editor Types
The values from the EditorType enumeration are interpreted differently by each platform and when
an editor type is missing, the closest type is used. The following table shows the type mapping:

Editor Type Native Editors Value Type


SliderEditor Android: float
DataFormSeekBarEditor
iOS: TKDataFormSliderEditor
UWP: SliderCustomEditor
PickerEditor Android: **requires
DataFormSpinnerEditor PropertyDataSourceProvider
iOS:
TKDataFormPickerViewEditor
UWP: ListEditor
TextEditor Android: DataFormTextEditor string
iOS:
TKDataFormTextFieldEditor
UWP: StringEditor
SegmentedEditor Android: **requires
DataFormSegmentedEditor PropertyDataSourceProvider
iOS:
TKDataFormSegmentedEdito
r
UWP:
SegmentedCustomEditor
NumberPickerEditor Android: double
DataFormNumberPickerEdito
r
iOS:
TKDataFormStepperEditor
UWP: NumericEditor

783
Telerik UI for Xamarin

IntegerEditor Android: int


DataFormIntegerEditor
iOS:
TKDataFormNumberEditor
UWP: *StringEditor
DecimalEditor Android: double
DataFormDecimalEditor
iOS:
TKDataFormDecimalEditor
UWP: *StringEditor
CheckBoxEditor Android: double
DataFormCheckBoxEditor
iOS:
*TKDataFormSwitchEditor
UWP: BooleanEditor
ToggleButtonEditor Android: bool
DataFormToggleButtonEditor
iOS:
*TKDataFormSwitchEditor
UWP: *BooleanEditor
DateEditor Android: DataFormDateEditor DateTime
iOS:
TKDataFormDatePickerEditor
UWP: DateEditor
TimeEditor Android: DataFormTimeEditor DateTime
iOS:
TKDataFormTimePickerEditor
UWP: TimeEditor
* Some editors are not supported in all native platforms. In these cases we use the closest
substitute.
** PropertyDataSourceProvider

Sometimes your property type will not be the same as the type supported by the editor, e.g. when
you wish to edit integers with a NumberPicker editor. In this case you will have to use a converter.
 
The image below shows how different editors are visualized on Android, iOS and UWP platforms.

784
Telerik UI for Xamarin

Events
RadDataForm provides the following event related to editors' values:

 EditorValueChanged: Occurs when a value of a DataForm editor is updated. The


EditorValueChanged event handler receives two parameters:
 The sender argument which is of type object, but can be cast to the RadDataForm type.
 An EditorValueChangedEventArgs object which has a reference to the PropertyName (of
the DataForm Source property that has been edited) as well as the new value.

Custom Editors
If any of the described above editors provided in RadDataForm for Xamarin is not suitable to achieve
a certain requirement, a custom native editor could be created for each platform.

Through custom renderers you can use any of the available editors for the native DataForm controls
on Android, iOS and UWP that are not exposed to Xamarin.Forms. You could find more information
on them at the links below: - DataForm for Xamarin.Android Editors - DataForm for Xamarin.iOS Editors
 
First, you need to specify the property for which a custom editor will be used through RegisterEditor
method of the DataForm:

C#
dataForm.RegisterEditor("Gender", EditorType.Custom);
 

When a Custom editor type is registered, specific renderer methods will be called on each platform.
You will have to inherit from the renderers and override specific methods to setup a custom editor.

C#

785
Telerik UI for Xamarin

[assembly: ExportRenderer(typeof(RadDataForm), typeof(CustomRenderer))]

CustomRenderer : DataFormRenderer
{
...
}
 

The DataFormRenderer works differently on each platform - see the specific methods available for
override below.
 

Android
Android DataFormRenderer available methods for override:

 GetCustomEditorForProperty
 GetCustomViewerForProperty
 UpdateEditor
 UpdateViewer

On Android if a property is read-only, a viewer is used.


 
You can find an example demonstrating a custom editor on Android here: Autocomplete editor in
Android.
 

iOS
iOS DataFormRenderer available methods for override:

 GetCustomEditorType
 InitEditor
 UpdateEditor

On iOS if a property is read-only, the editor is disabled.


 
You can find an example demonstrating a custom editor on iOS here: Email and Password editors on
iOS.
 

UWP
UWP DataFormRenderer available methods for override:

 GetCustomEditorType
 UpdateEditor

786
Telerik UI for Xamarin

See Also
 DataForm Layouts
 Validate and Commit

787
Telerik UI for Xamarin

ConverterAttribute
There are cases when the editors require types that are not the same as the property type defined in
the business object. In these case users can use a converter class. This is a custom class
implementing the IPropertyConverter interface. The next example demonstrates how such converted
can be used.

Example
In this example we will demonstrate how we can use a number picker editor, which supports double
type, for property of type decimal. First, you need a proper converter:

C#
class DecimalToDoublePropertyConverter : IPropertyConverter
{
public object Convert(object value)
{
return System.Convert.ToDouble((decimal)value);
}

public object ConvertBack(object value)


{
return System.Convert.ToDecimal((double)value);
}
}
 

Here is the decoration of the source class with attributes:

C#
public class Item : NotifyPropertyChangedBase
{
decimal price;

[DisplayOptions(Header = "Name")]
public string Name { get; set; } = "vase";

[DisplayOptions(Header = "Price")]
[Converter(typeof(DecimalToDoublePropertyConverter))]
public decimal Price
{
get
{
return this.price;
}
set
{
if (this.price != value)
{
this.price = value;

788
Telerik UI for Xamarin

this.OnPropertyChanged();
}
}
}
}
 

Finally, you have to register a number picker editor for the item Price property:

C#
var dataForm = new RadDataForm
{
Source = new Item()
};

dataForm.RegisterEditor("Price", EditorType.NumberPickerEditor);
 

See Also
 DataSourceKey Attribute
 DisplayOptions Attribute
 DisplayValueFormat Attribute
 Ignore Attribute
 NativeConversionContext Attribute
 ReadOnly Attribute
 Validation Attribute

789
Telerik UI for Xamarin

DataSourceKeyAttribute
The DataSourceKey attribute is used when a property can have one of many (known in advance)
values. This attribute should be used along with a PropertyDataSourceProvider. The attribute
defines the following property:

 Key (object): Specifies the key that is used by PropertyDataSourceProvider of


RadDataForm.

Some editors require a list of possible values which the end user will pick one from, e.g. picker
editors. These values are provided by a special class that implements the
IPropertyDataSourceProvider interface. It has two methods:

 IList GetSourceForKey(object key): Provides a list of values for properties with specific key
defined with the DataSourceKeyAttribute.
 IList GetSourceForType(Type type): Provides a list of values for a specific property type.
This method has less priority than the GetSourceForKey method.

The default implementation of this interface - the PropertyDataSourceProvider class automatically


provides values for enum types. In all other cases users have to create their own implementation of
the IPropertyDataSourceProvider interface.

Example
Here is the implementation of the IPropertyDataSourceProvider interface that will provide a list of
available locations for all properties that have DataSourceKeyAttribute defined with Key="Location".

C#
public class LocationProvider : PropertyDataSourceProvider
{
public override IList GetSourceForKey(object key)
{
if (key.ToString() == "LocationsSource")
{
return new List<string> { "Top", "Bottom", "Left", "Right" };
}

return null;
}
}
 

Here is the decoration of the source class properties:

C#
public class LocationData
{
[DisplayOptions(Header = "Location")]
[DataSourceKey("LocationsSource")]

790
Telerik UI for Xamarin

public string Location { get; set; }


}
 

And here is the data form setup, you have to specify the property data source provider for the data
form:

C#
var dataForm = new RadDataForm
{
Source = new LocationData(),
PropertyDataSourceProvider = new LocationProvider()
};

dataForm.RegisterEditor("Location", EditorType.PickerEditor);
 

See Also
 Converter Attribute
 DisplayOptions Attribute
 DisplayValueFormat Attribute
 Ignore Attribute
 NativeConversionContext Attribute
 ReadOnly Attribute
 Validation Attribute

791
Telerik UI for Xamarin

DisplayOptionsAttribute
The DisplayOptionsAttribute controls the way an editor is presented. It provides the following
properties:

 Header (string): Sets the label of the respective editor.


 HeaderResourceKey(string): Sets the key which will be used for globalizing the control´s
property headers. The key should be present in a custom RESX file in your application.
 Group (string): Sets the group which the editor is part of.
 GroupResourceKey(string): Sets the key which will be used for globalizing the control´s group
headers. The key should be present in a custom RESX file in your application.
 Position (int): Sets the position of the editor in the layout.
 ColumnPosition (int): Sets the column position of the editor in the layout.
 ColumnSpan (int): Sets the column span of the editor in the layout.
 PlaceholderText (string): Sets the empty content of the editor.
 PlaceholderResourceKey(string): Sets the key which will be used for globalizing the
placeholder texts of the different properties. The key should be present in a custom RESX file
in your application.

All properties are optional.


 

Example
Here is the decoration of the source class:

C#
public class Person
{
[DisplayOptions(Header = "FirstName", PlaceholderText = "first name", Group =
"Public Info")]
public string FirstName { get; set; } = "Peter";

[DisplayOptions(Header = "LastName", PlaceholderText = "last name", Group =


"Public Info")]
public string LastName { get; set; } = "Pan";

[DisplayOptions(Header = "Age", PlaceholderText = "age", Group = "Private Info")]


public int Age { get; set; } = 13;

[DisplayOptions(Header = "Weight", PlaceholderText = "weight", Group = "Private


Info")]
public double Weight { get; set; } = 48;
}
 

And here is the data form setup:

792
Telerik UI for Xamarin

C#
var dataForm = new RadDataForm
{
Source = new Person()
};

dataForm.RegisterEditor("Weight", EditorType.DecimalEditor);
dataForm.RegisterEditor("Age", EditorType.IntegerEditor);
 

See Also
 Converter Attribute
 DataSourceKey Attribute
 DisplayValueFormat Attribute
 Ignore Attribute
 NativeConversionContext Attribute
 ReadOnly Attribute
 Validation Attribute

793
Telerik UI for Xamarin

DisplayValueFormatAttribute
For the scenarios when the provided property value is not the same as the required visualization the
DisplayValueFormat attribute comes handy. This attribute provides formatting options for Date, Time
and NumberPicker editor types. Here is how it can be used.

Example
Here is the decoration of the source class properties:

C#
public class VoteResults
{
[DisplayOptions(Header = "Votes")]
[DisplayValueFormat(Plural = "{0} votes", Single = "{0} vote", Zero = "no votes")]
public double Votes { get; set; }

[DisplayOptions(Header = "Date")]
[DisplayValueFormat(Date = "yyyy-MM-dd")]
public DateTime Date { get; set; } = new DateTime(2016, 10, 27);
}
 

And here is the data form setup:

C#
var dataForm = new RadDataForm
{
Source = new VoteResults()
};

dataForm.RegisterEditor("Votes", EditorType.NumberPickerEditor);
dataForm.RegisterEditor("Date", EditorType.DateEditor);
 

See Also
 Converter Attribute
 DataSourceKey Attribute
 DisplayOptions Attribute
 Ignore Attribute
 NativeConversionContext Attribute
 ReadOnly Attribute
 Validation Attribute

794
Telerik UI for Xamarin

IgnoreAttribute
Properties marked with the Ignore attribute will force the RadDataForm to skip creating editor for
them.

Example
Here is the decoration of the source class properties:

C#
public class Person
{
[DisplayOptions(Header = "Name")]
public string Name { get; set; } = "Peter";

[DisplayOptions(Header = "Age")]
public int Age { get; set; } = 30;

[Ignore]
public double Weight { get; set; }
}
 

Here is the data form setup:

C#
var dataForm = new RadDataForm
{
Source = new Person()
};
 

No editor will be created for the "Weight" property.

See Also
 Converter Attribute
 DataSourceKey Attribute
 DisplayOptions Attribute
 DisplayValueFormat Attribute
 NativeConversionContext Attribute
 ReadOnly Attribute
 Validation Attribute

795
Telerik UI for Xamarin

NativeConversionContextAttribute
Working with properties of type DateTime could be tricky because of the DateTime.Kind property.
There is no straightforward way to map the kind while converting between CLR DateTime and
Android/iOS dates. This is why sometimes you should explicitly specify the kind of the property. This
can be done with the NativeConversionContextAttribute.

C#
public class SourceItem : NotifyPropertyChangedBase
{
private DateTime utc = new DateTime(2010, 1, 1, 0, 0, 0, DateTimeKind.Utc);

[NativeConversionContext(DateTimeKind.Utc)]
public DateTime Utc
{
get
{
return this.utc;
}
set
{
if (this.utc != value)
{
this.utc = value;
this.OnPropertyChanged();
}
}
}
}
 

See Also
 Converter Attribute
 DataSourceKey Attribute
 DisplayOptions Attribute
 DisplayValueFormat Attribute
 Ignore Attribute
 ReadOnly Attribute
 Validation Attribute

796
Telerik UI for Xamarin

ReadOnlyAttribute
Properties marked with the ReadOnly attribute will force the RadDataForm to create editors that can
not be edited by the end users. There are differences in the behavior of the generated native
components in the different platforms:

 iOS: The editors are in disabled state.


 Android: Viewers are used instead of editors.

Example
Here is the decoration of the source class properties:

C#
public class Employee
{
[DisplayOptions(Header = "FirstName")]
public string FirstName { get; set; } = "John";

[DisplayOptions(Header = "LastName")]
public string LastName { get; set; } = "Doe";

[DisplayOptions(Header = "Manager")]
[ReadOnly]
public string Manager { get; set; } = "Michael";
}
 

And here is the data form setup:

C#
var dataForm = new RadDataForm
{
Source = new Employee()
};
 

See Also
 Converter Attribute
 DataSourceKey Attribute
 DisplayOptions Attribute
 DisplayValueFormat Attribute
 Ignore Attribute
 NativeConversionContext Attribute
 Validation Attribute

797
Telerik UI for Xamarin

Validation Annotations
Validators are special type of attributes that can be used to ensure that the users' input falls within
an expected range of values. Validators should implement the IPropertyValidator interface defining
the following members:

 PositiveFeedback (string): The message that is displayed in the editor if the property value is
valid.
 NegativeFeedback (string): The message that is displayed in the editor if the property value
is invalid.
 bool Validate (object value): A method that decides whether the property value is valid or not.

The following list contains the available implementations that we provide and can be used out of the
box:

 DateRangeValidatorAttribute: Validates if a DateTime value falls within a given interval. Here


are the validator properties:
 MinYear (int)
 MinMonth (int)
 MinDay (int)
 MaxYear (int)
 MaxMonth (int)
 MaxDay (int)
 EmailValidatorAttribute: Validates if a string matches the e-mail format
[string]@[string].[string].
 NonEmptyValidatorAttribute: Validates if an editor has non null value.
 NumericalRangeValidatorAttribute: Validates if a number falls within a given interval. Here
are the validator properties:
 Min (double)
 Max (double)
 Step (double)

This attribute sets the Minimum, Maximum and Step properties of the created editor (e.g.
RadSlider).
 

 PhoneNumberValidatorAttribute: Validates if a string matches the phone number


requirements.
 RegularExpressionValidatorAttribute: Validates if a string matches a custom regex pattern.
 Pattern (string)
 Options (RegexOptions)
 StringLengthValidatorAttribute: Validates if a string has specific length.
 MinLength (int)
 MaxLength (int)

Users can also define their custom validators. The only requirement is to implement the
IPropertyValidator interface or to inherit from the base implementation - the ValidatorBaseAttribute
class.

798
Telerik UI for Xamarin

Example
This example will demonstrate how to create a custom validator and also how to use the default
ones.

Here is a sample class that has an "Occupation" property:

C#
public enum Occupation { Unspecified, Unemployed, Employed }

public class Person


{
[NumericalRangeValidator(10, 15, "Age must be 10 and 15 years!")]
public int Age { get; set; }

[OccupationValidator]
public Occupation Occupation { get; set; } = Occupation.Unspecified;

[NonEmptyValidator("Name is required!")]
public string Name { get; set; }
}
 

Let's create a validator that ensures that the person occupation is not "Unspecified".

C#
public class OccupationValidatorAttribute : ValidatorBaseAttribute
{
public OccupationValidatorAttribute()
{
this.NegativeFeedback = "Occupation must be specified";
}

protected override bool ValidateCore(object value)


{
return (Occupation)value != Occupation.Unspecified;
}
}
 

And here is the data form setup:

C#
dataForm.Source = new Person();
dataForm.RegisterEditor("Occupation", EditorType.SegmentedEditor);
 

See Also
 Converter Attribute
 DataSourceKey Attribute

799
Telerik UI for Xamarin

 DisplayOptions Attribute
 DisplayValueFormat Attribute
 Ignore Attribute
 NativeConversionContext Attribute
 ReadOnly Attribute

800
Telerik UI for Xamarin

Validate
RadDataForm for Xamarin provides built-in validation, which gives you full control over the data
collected through the control. You could specify the validation rules for each property of the source
object through Validation Annotations.

The next sections list all DataForm members related to validation.

Validation modes

You could choose between three validation modes described below:

 Immediate: Property value is validated after every change in editor.


 OnLostFocus: Property value is validated after editor looses focus.
 Manual: Property value is validated only with explicit call of a validate method or on commit.

The selected mode is applied through ValidationMode property of the DataForm control.

Manual validation through methods

RadDataForm provides the following methods you can use in case of manual validation mode:

 ValidateAll(): Validates all properties and when finished, raises the FormValidationCompleted
event.
 ValidateProperty(string propertyName): Validates the property with the specified name and
when finished raises the PropertyValidationCompleted event.

Validation events

You can use the validation events below to get notified when RadDataForm has validated its fields.

 FormValidationCompleted: Occurs when all form properties are validated. Provides a list of
failed properties.
 PropertyValidationCompleted: Occurs when a property validation has finished. Provides
information about whether the property has passed validation.

Example

The example below shows how you could use Manual ValidationMode with RadDataForm.

First, create a sample User object with a few validation annotations added:

C#
public class User : NotifyPropertyChangedBase
{
private string name;
private double payment;
private DateTime birthDate = new DateTime(1959, 1, 1);

801
Telerik UI for Xamarin

[DisplayOptions(Header = "Name")]
[StringLengthValidator(2, int.MaxValue, "Your name should be longer than 2
symbols.", "ok")]
public string Name
{
get
{
return this.name;
}
set
{
if (this.name != value)
{
this.name = value;
this.OnPropertyChanged();
}
}
}

[DisplayOptions(Header = "Payment amount (USD)")]


[NumericalRangeValidator(100, 5000, "Only payments between $100 and $5000 are
accepted.", "ok")]
public double Payment
{
get
{
return this.payment;
}
set
{
if (this.payment != value)
{
this.payment = value;
this.OnPropertyChanged();
}
}
}

[DisplayOptions(Header = "Birth Date")]


[DateRangeValidator(1960, 1, 1, 1990, 12, 31, "You must be born between 1960 and
1990 year.", "ok")]
[DisplayValueFormat(Date = "d")]
public DateTime BirthDate
{
get
{
return this.birthDate;
}
set
{
if (this.birthDate != value)
{
this.birthDate = value;

802
Telerik UI for Xamarin

this.OnPropertyChanged();
}
}
}
}
 

Add RadDataForm definition with ValidationMode property applied:

XAML
<telerikInput:RadDataForm x:Name="dataForm"
Source="{Binding}"
ValidationMode="Manual"
FormValidationCompleted="DataFormValidationCompleted" />
 

Set the BindingContext to a new User object and register the needed editors:

C#
this.BindingContext = new User();

dataForm.RegisterEditor("Payment", EditorType.DecimalEditor);
dataForm.RegisterEditor("BirthDate", EditorType.DateEditor);
 

Check the event handler of the FormValidationCompleted event below:

C#
private async void DataFormValidationCompleted(object sender,
FormValidationCompletedEventArgs e)
{
if (e.IsValid)
{
await Application.Current.MainPage.DisplayAlert("Success!", "User was
successfully updated.", "OK");
}
}
 

The defined validation rules will be executed as soon as any of the validation methods is called or
the dataform is committed. You could use, for example, ValidateAll method:

C#
dataForm.ValidateAll();
 

The image below shows how RadDataForm will look when ValidateAll is called:

803
Telerik UI for Xamarin

Commit
The values entered in the DataForm can be submitted to the underlying data object on three
different occasions, using the CommitMode property of the DataForm.

All members related to committing are listed below:

Commit Modes

You could choose between three commit modes described below:

 Immediate: Property value is committed after each change in the editor.


 OnLostFocus: Property value is committed after editor looses focus.
 Manual: Property value is committed only with explicit call of commit method.

The selected mode is applied through CommitMode property of the DataForm control.

Manual commit through methods

RadDataForm provides the following methods you can use in case of manual commit mode:

 CommitAll(): Commits all properties.


 CommitProperty(string propertyName): Commits the property with the specified name.

All commit methods call validation first. If the property value passes validation, then the
corresponding validation finished event is raised and the value is committed successfully.
 

804
Telerik UI for Xamarin

Example

The example below demonstrates how you could utilize Manual CommitMode and CommitProperty
methods.

Let's use the same User object from the previous Validation example.

The next step is to add a DataForm control with CommitMode applied:

XAML
<telerikInput:RadDataForm x:Name="dataForm"
Source="{Binding}"
CommitMode="Manual" />
 

You could submit the entered "Name" value like shown in the snippet below.

C#
dataForm.CommitProperty("Name");
 

The image below displays RadDataForm with submitted "Name" property.

Sample examples demonstrating validation and commit features of DataForm control can be found
inside the RadDataForm -> Commit/Validate section within the SDK Samples Browser application.
 

See Also
805
Telerik UI for Xamarin

 Editors
 DataForm Annotations

806
Telerik UI for Xamarin

Dynamic PropertyDataSource
Some DataForm Editors such as PickerEditor and SegmentedEditor allow the app user to choose a
value from a predefined list of values. In this case RadDataForm provides a mechanism to set a data
source to these editors through the PropertyDataSourceProvider.

With R1 2020 release of Telerik UI for Xamarin RadDataForm provides means to refresh the data
source of its Picker and Segmented editors. There are two ways to update the data source of a
certain editor - either use an ObservableCollection, so that any changes are reflected to the
underlying data source, or manually update it through the UpdatePropertyDataSource method. Both
approaches are described in details in the next sections.

Dynamic PropertyDataSourceProvider updates are supported only in Manual CommitMode. For


more details on the commit modes of RadDataForm check Validate and Commit topic.
 

Using ObservableCollection
Let's have the following source item for the DataForm:

C#
public class Customer
{
[DisplayOptions(Header = "Name", Position = 0)]
public string Name { get; set; }

[DisplayOptions(Header = "Email", Position = 1)]


public string Email { get; set; }

[DisplayOptions(Header = "Country", Position = 2)]


public string Country { get; set; }

[DisplayOptions(Header = "City", Position = 3)]


public string City { get; set; }
}
 

For the Country and City properties you can use PickerEditors in order to provide a list the user can
choose from. The cities will depend on the chosen Country, meaning that you would need to refresh
the City PickerEditor every time the selected Country is changed.

Let's continue with the implementation - add the DataForm definition:

XAML
<telerikInput:RadDataForm x:Name="dataForm"
CommitMode="Manual"
EditorValueChanged="DataForm_EditorValueChanged" />
 

807
Telerik UI for Xamarin

Configure the DataForm Editors and set PropertyDataSourceProvider:

C#
dataForm.Source = new Customer();

dataForm.RegisterEditor(nameof(Customer.Country), EditorType.PickerEditor);
dataForm.RegisterEditor(nameof(Customer.City), EditorType.PickerEditor);

this.locationProvider = new LocationProvider();


this.locationProvider.Countries = new ObservableCollection<string>()
{ "Germany", "Argentina", "USA"};
this.UpdateCities(locationProvider.Countries[0]);

dataForm.PropertyDataSourceProvider = locationProvider;
 

Next, create the LocationProvider class which inherits from PropertyDataSourceProvider and defines
two ObservableCollections that should hold the Countries and Cities values:

C#
public class LocationProvider : PropertyDataSourceProvider
{
public ObservableCollection<string> Cities = new ObservableCollection<string>();
public ObservableCollection<string> Countries = new
ObservableCollection<string>();
public override IList GetSourceForKey(object key)
{
string keyString = key as string;

if (keyString == nameof(Customer.Country))
{
return this.Countries;
}
else if (keyString == nameof(Customer.City))
{
return this.Cities;
}
else
{
return base.GetSourceForKey(key);
}
}
}
 

Lastly, add the EditorValueChanged event handler and in it update the City PickerEditor's Source
depending on the selected Country:

C#
private void DataForm_EditorValueChanged(object sender,
Telerik.XamarinForms.Input.DataForm.EditorValueChangedEventArgs e)
{

808
Telerik UI for Xamarin

if (e.PropertyName == nameof(Customer.Country))
{
this.UpdateCities((string)e.NewValue);
}
}

private void UpdateCities(string country)


{
this.locationProvider.Cities.Clear();

if (country == "Germany")
{
this.locationProvider.Cities.Add("Berlin");
this.locationProvider.Cities.Add("Frankfurt am Main");
this.locationProvider.Cities.Add("Hamburg");
}
else if (country == "Argentina")
{
this.locationProvider.Cities.Add("Buenos Aires");
this.locationProvider.Cities.Add("Cordoba");
}
else
{
this.locationProvider.Cities.Add("Miami");
this.locationProvider.Cities.Add("New York");
this.locationProvider.Cities.Add("Los Angeles");
}
}
 

Using UpdatePropertyDataSource method


Through the UpdatePropertyDataSource method of the DataForm you can manually refresh the
editor DataSource. The method received one argument - the name of the property corresponding to
the editor.

Let's have the same scenario as in the first section with dependent Country-City Picker editors. Here
is the DataForm source class:

C#
public class Customer
{
[DisplayOptions(Header = "Name", Position = 0)]
public string Name { get; set; }

[DisplayOptions(Header = "Email", Position = 1)]


public string Email { get; set; }

[DisplayOptions(Header = "Country", Position = 2)]


public string Country { get; set; }

[DisplayOptions(Header = "City", Position = 3)]

809
Telerik UI for Xamarin

public string City { get; set; }


}
 

And the DataForm definition:

XAML
<telerikInput:RadDataForm x:Name="dataForm"
CommitMode="Manual"
EditorValueChanged="DataForm_EditorValueChanged" />
 

Next, setup the DataForm editors and define PropertyDataSourceProvider:

C#
dataForm.Source = new Customer();

dataForm.RegisterEditor(nameof(Customer.Country), EditorType.PickerEditor);
dataForm.RegisterEditor(nameof(Customer.City), EditorType.PickerEditor);

this.locationProvider = new LocationProvider();


this.locationProvider.Countries = new List<string>() { "Germany", "Argentina", "USA"
};
this.UpdateCities(locationProvider.Countries[0]);

dataForm.PropertyDataSourceProvider = locationProvider;
 

Here is the LocationProvider class definition - note that Countries and Cities are defined as Lists:

C#
public class LocationProvider : PropertyDataSourceProvider
{
public List<string> Cities = new List<string>();
public List<string> Countries;

public override IList GetSourceForKey(object key)


{
string keyString = key as string;

if (keyString == nameof(Customer.Country))
{
return this.Countries;
}
else if (keyString == nameof(Customer.City))
{
return this.Cities;
}
else
{
return base.GetSourceForKey(key);
}

810
Telerik UI for Xamarin

}
}
 

Lastly, add the EditorValueChanged event handler and in it call the UpdatePropertyDataSource
method to force the update of the City PickerEditor data source:

C#
private void DataForm_EditorValueChanged(object sender,
Telerik.XamarinForms.Input.DataForm.EditorValueChangedEventArgs e)
{
if (e.PropertyName == nameof(Customer.Country))
{
this.UpdateCities((string)e.NewValue);
dataForm.UpdatePropertyDataSource(nameof(Customer.City));
}
}

private void UpdateCities(string country)


{
this.locationProvider.Cities = new List<string>();

if (country == "Germany")
{
this.locationProvider.Cities.Add("Berlin");
this.locationProvider.Cities.Add("Frankfurt am Main");
this.locationProvider.Cities.Add("Hamburg");
}
else if (country == "Argentina")
{
this.locationProvider.Cities.Add("Buenos Aires");
this.locationProvider.Cities.Add("Cordoba");
}
else
{
this.locationProvider.Cities.Add("Miami");
this.locationProvider.Cities.Add("New York");
this.locationProvider.Cities.Add("Los Angeles");
}
}
 

See Also
 DataForm Layouts
 Validate and Commit

811
Telerik UI for Xamarin

DataForm Group Layouts


RadDataForm supports different group layouts through the following properties:

 GroupLayoutDefinition: Defines a layout definition that will be used to arrange editors in all
data form groups.
 GroupLayoutDefinitionSelector: Gets or sets a layout definition selector that applies specific
layout for each group.

If no groups are defined all editors are arranged in a default group.


 
The information for editors arrangement is defined in the source class metadata with the
DisplayOptionsAttribute. Here are all DisplayOptionsAttribute properties that are interpreted by the
layouts:

 Position: default value: 0


 ColumnPosition: default value: 0
 ColumnSpan: default value: 1

Stack Layout Definition


The DataFormGroupStackLayoutDefinition arranges the editors in stack ordered by the
DisplayOptions Position value.

Here is a sample source object class:

C#
public class SourceItem
{
[DisplayOptions(Group = "Value", Header = "1:", Position = 2)]
public int Value { get; set; } = 2;

[DisplayOptions(Group = "Value", Header = "2:", Position = 1)]


public int Value1 { get; set; } = 1;

[DisplayOptions(Group = "Value", Header = "3:", Position = 0)]


public int Value2 { get; set; } = 0;

[DisplayOptions(Group = "Name", Header = "Name 1: ", Position = 0)]


public string Name { get; set; } = "position 0";

[DisplayOptions(Group = "Name", Header = "Name 2:", Position = 1)]


public string Name1 { get; set; } = "position 1";
}
 

The following sample demonstrates how to set stack layout for all groups:

812
Telerik UI for Xamarin

XAML
<telerikInput:RadDataForm x:Name="dataForm">
<telerikInput:RadDataForm.Source>
<local:SourceItem />
</telerikInput:RadDataForm.Source>
<telerikInput:RadDataForm.GroupLayoutDefinition>
<telerikInputDataForm:DataFormGroupStackLayoutDefinition />
</telerikInput:RadDataForm.GroupLayoutDefinition>
</telerikInput:RadDataForm>
 

C#
var dataForm = new RadDataForm
{
GroupLayoutDefinition = new DataFormGroupStackLayoutDefinition(),
Source = new SourceItem()
};
 

Here is the result:

Grid Layout Definition


The DataFormGroupGridLayoutDefinition arranges the editors in grid. Each editor is placed at
position defined by the DisplayOptions Position (row) and ColumnPosition (column) values. The
number of columns that the editor occupies is defined by the DisplayOptions ColumnSpan property.

Here is a sample source object class:

813
Telerik UI for Xamarin

C#
public class SourceItem
{
[DisplayOptions(Group = "Value", Header = "1:", Position = 0, ColumnPosition = 0)]
public int Value { get; set; } = 0;

[DisplayOptions(Group = "Value", Header = "2:", Position = 0, ColumnPosition = 1)]


public int Value1 { get; set; } = 1;

[DisplayOptions(Group = "Value", Header = "3:", Position = 1, ColumnPosition = 0)]


public int Value2 { get; set; } = 2;

[DisplayOptions(Group = "Value", Header = "4: ", Position = 1, ColumnPosition =


1)]
public int Value3 { get; set; } = 3;

[DisplayOptions(Group = "Name", Header = "Name 1: ", Position = 1, ColumnPosition


= 0)]
public string Name { get; set; } = "1, 0";

[DisplayOptions(Group = "Name", Header = "Name 2:", Position = 1, ColumnPosition =


1)]
public string Name1 { get; set; } = "1, 1";

[DisplayOptions(Group = "Name", Header = "Name 3:", Position = 0, ColumnPosition =


0)]
public string Name2 { get; set; } = "0, 0";

[DisplayOptions(Group = "Name", Header = "Name 4:", Position = 0, ColumnPosition =


1)]
public string Name3 { get; set; } = "0, 1";

}
 

The following sample demonstrates how to set grid layout for all groups:

XAML
<telerikInput:RadDataForm x:Name="dataForm">
<telerikInput:RadDataForm.Source>
<local:SourceItem />
</telerikInput:RadDataForm.Source>
<telerikInput:RadDataForm.GroupLayoutDefinition>
<telerikInputDataForm:DataFormGroupGridLayoutDefinition />
</telerikInput:RadDataForm.GroupLayoutDefinition>
</telerikInput:RadDataForm>
 

C#
var dataForm = new RadDataForm
{
GroupLayoutDefinition = new DataFormGroupGridLayoutDefinition(),
Source = new SourceItem()

814
Telerik UI for Xamarin

};
 

Here is the result:

Layout Definition Selector


Sometimes different layout is required for each group. In these cases you can use the layout
definition selector. This is a class that implements the IDataFormGroupLayoutDefinitionSelector
interface and provides layout definition for each group.

Here is a sample layout definition selector class:

C#
public class CustomGroupLayoutDefinitionSelector :
IDataFormGroupLayoutDefinitionSelector
{
public DataFormGroupLayoutDefinition SelectLayoutDefinition(string groupName)
{
if (groupName == "Name")
{
return new DataFormGroupGridLayoutDefinition();
}

if (groupName == "Value")
{
return new DataFormGroupStackLayoutDefinition { Orientation =
Orientation.Vertical };

815
Telerik UI for Xamarin

return null;
}
}
 

Here is a sample source object class:

C#
public class SourceItem
{
[DisplayOptions(Group = "Value", Header = "1:", Position = 2)]
public int Value { get; set; } = 2;

[DisplayOptions(Group = "Value", Header = "2:", Position = 1)]


public int Value1 { get; set; } = 1;

[DisplayOptions(Group = "Value", Header = "3:", Position = 0)]


public int Value2 { get; set; } = 0;

[DisplayOptions(Group = "Name", Header = "Name 1: ", Position = 0)]


public string Name { get; set; } = "position 0";

[DisplayOptions(Group = "Name", Header = "Name 2:", Position = 1)]


public string Name1 { get; set; } = "position 1";
}
 

The following sample demonstrates how to use layout selector in data form:

XAML
<telerikInput:RadDataForm x:Name="dataForm">
<telerikInput:RadDataForm.Source>
<local:SourceItem />
</telerikInput:RadDataForm.Source>
<telerikInput:RadDataForm.GroupLayoutDefinition>
<telerikInputDataForm:DataFormGroupStackLayoutDefinition />
</telerikInput:RadDataForm.GroupLayoutDefinition>
</telerikInput:RadDataForm>
 

C#
var dataForm = new RadDataForm
{
GroupLayoutDefinition = new DataFormGroupStackLayoutDefinition(),
Source = new SourceItem()
};
 

Here is the result:

816
Telerik UI for Xamarin

See Also
 DataForm Editors
 Validate and Commit

817
Telerik UI for Xamarin

DataForm Localization
Localizing an application is an important part of any development process as it ensures that your
product can reach as many people as possible.The RadDataForm control provides a localization
mechanism which you can utilize to expand the reach of your audience and automatically visualize
different strings for the headers, groups and placeholders depending on the culture of the device.

In the same way as the built-in mechanism for localizing .NET applications uses RESX files and the
classes in the System.Resources and System.Globalization namespaces, the RadDataForm control
relies on similar setup to achieve the functionality. In order to localize the visual elements used to
represent the properties of RadDataForm's item, you need to set the
DataFormLocalizationManager.Manager property to use a custom ResourceManager. This
ResourceManager can be obtained through the default resx file which holds a list of key/value pairs.
This article will show you how to set up the localization.

You can find information on how to add different resource files to your project on the following link -
String and Image Localization - Adding Resources
 
By adding separate resource files for different cultures you can easily set up the RadDataForm
control so that the correct values are applied when the culture of the device is changed. Here are all
the steps you need to take:

1. Add resource files for the different cultures and fill in the values for the
respective languages:
In case you would like the RadDataForm control to support two languages - English and Spanish -
you should add a couple of resource files, for example - DataFormResources.resx and
DataFormResources.es.resx. The former will contain the values in English and the latter the values
in Spanish. Here is an example:

2. Map the keys from your resource file to your business object:
In order make the connection between the properties of your business object and the keys you have
added in the resource file, you should set any of the following properties of the
DisplayOptionsAttribute - HeaderResourceKey, PlaceholderTextResourceKey, GroupResourceKey.

818
Telerik UI for Xamarin

The following class shows such setup:

C#
public class Person
{
[DisplayOptions(HeaderResourceKey = "Age",
PlaceholderTextResourceKey = "AgePlaceholder",
GroupResourceKey = "PrivateInfo")]
public int? Age { get; set; }

[DisplayOptions(HeaderResourceKey = "Weight",
PlaceholderTextResourceKey = "WeightPlaceholder",
GroupResourceKey = "PrivateInfo")]
public int? Weight { get; set; }

[DisplayOptions(HeaderResourceKey = "FirstName",
PlaceholderTextResourceKey = "FirstNamePlaceholder",
GroupResourceKey = "PublicInfo")]
public string FirstName { get; set; }

[DisplayOptions(HeaderResourceKey = "LastName",
PlaceholderTextResourceKey = "LastNamePlaceholder",
GroupResourceKey = "PublicInfo")]
public string LastName { get; set; }

[DisplayOptions(Header = "Town",
PlaceholderText = "Not localized...",
Group = "PublicInfo")]
public string HomeTown { get; set; }
}
 

Note that the HomeTown property does not use the "key" properties, meaning that the values will
stay the same for all cultures/languages.
 

3. Set the ResourceManager to be used for the localization:


All that is left is to set the control to use the ResourceManager of your default resource file:

C#
public DataFormGlobalization()
{
DataFormLocalizationManager.Manager = DataFormResources.ResourceManager;
InitializeComponent();
}
 

The custom ResourceManager should be set before initializing the RadDataForm component.
 
Eventually, the RadDataForm control will automatically detect the language set to your device and if

819
Telerik UI for Xamarin

you have added resource file for that language, it will use the values from it. In case the language is
not present in your resources - the values from your default resource file will be used.

You can find an example on how to localize the RadDataForm control in the
RadDataForm/Globalization section within the SDK Browser application.

You can directly explore the code in the SDKBrowser Examples repository on GitHub.

See Also
 Localization and Globalization
 DataForm Editors
 Validate and Commit
 DataForm Annotations

820
Telerik UI for Xamarin

Editors Styling
RadDataForm editors appearance can be customized with the EditorStyle property of type
DataFormEditorStyle. The DataFormEditorStyle exposes the following properties:

 Height: Sets the height of each editor.


 Background: Specifies the background color of the editors.
 HeaderForeground: Defines the foreground color of the editors header.
 HeaderFontSize: Specifies the font size of the editors header.

The properties below are related to the look &feel of the positive and negative feedback messages
related to validating the input fields:

 FeedbackFontSize;
 FeedbackImageSize;
 PositiveFeedbackForeground;
 NegativeFeedbackForeground;
 PositiveFeedbackBackground;
 NegativeFeedbackBackground;
 PositiveFeedbackImage (of type ImageSource);
 NegativeFeedbackImage (of type ImageSource);

Example
XAML
<telerikInput:RadDataForm x:Name="dataForm" BackgroundColor="#B7D8FF"
Source="{Binding}">
<telerikInput:RadDataForm.EditorStyle>
<telerikDataForm:DataFormEditorStyle Height="70"
HeaderFontSize="17"
HeaderForeground="#505050"
FeedbackFontSize="13"
PositiveFeedbackImage="success.png"
NegativeFeedbackImage="fail.png"
NegativeFeedbackForeground="#F8082D">
<telerikDataForm:DataFormEditorStyle.FeedbackImageSize>
<Size Width="10" Height="10" />
</telerikDataForm:DataFormEditorStyle.FeedbackImageSize>
<telerikDataForm:DataFormEditorStyle.Background>
<telerikCommon:Background Fill="#EBF4FF"
StrokeColor="#B2DFF4"
StrokeWidth="2"
StrokeLocation="Bottom" />
</telerikDataForm:DataFormEditorStyle.Background>
<telerikDataForm:DataFormEditorStyle.NegativeFeedbackBackground>
<telerikCommon:Background Fill="#EBF4FF"
StrokeColor="#F8082D"
StrokeWidth="2"

821
Telerik UI for Xamarin

StrokeLocation="All" />
</telerikDataForm:DataFormEditorStyle.NegativeFeedbackBackground>
</telerikDataForm:DataFormEditorStyle>
</telerikInput:RadDataForm.EditorStyle>
</telerikInput:RadDataForm>
 

C#
var negative = "F8082D";

var style = new DataFormEditorStyle


{
Background = new Background
{
Fill = Color.FromHex("EBF4FF"),
StrokeColor = Color.FromHex("B2DFF4"),
StrokeWidth = 2,
StrokeLocation = Location.Bottom
},
HeaderFontSize = 17,
HeaderForeground = Color.FromHex("505050"),
FeedbackFontSize = 13,
PositiveFeedbackImage = ImageSource.FromFile("success.png"),
NegativeFeedbackImage = ImageSource.FromFile("fail.png"),
NegativeFeedbackForeground = Color.FromHex(negative),
NegativeFeedbackBackground = new Background
{
StrokeColor = Color.FromHex(negative),
StrokeWidth = 2,
StrokeLocation = Location.All
},
Height = 70,
FeedbackImageSize = new Size(10, 10),

};

dataForm.EditorStyle = style;
dataForm.BackgroundColor = Color.FromHex("B7D8FF");
 

and add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
xmlns:telerikDataForm="clr-namespace:Telerik.XamarinForms.Input.DataForm;assembly=Tele
rik.XamarinForms.Input"
 

Result:

822
Telerik UI for Xamarin

Sample examples demonstrating editors styling of DataForm control can be found inside the
RadDataForm -> Styling section within the SDK Samples Browser application.
 

See Also
 Editors
 Validate and Commit

823
Telerik UI for Xamarin

Groups Styling
The RadDataForm group headers appearance can be customized with the GroupHeaderStyle
property of type DataFormGroupHeaderStyle.

The DataFormGroupHeaderStyle class exposes the following properties:

 Background: Specifies the background of the group headers.


 BackgroundImageSource (ImageSource): Sets a background image for the group header.
 Foreground: Determines the group header text color.
 Height: Specifies the group header height.
 IsCollapsible: Indicates whether the group will be collapsible.
 IsCollapsed: Specifies whether the group is collapsed. When setting it to "False", the groups
will be collapsed by default.
 Padding: Sets the group header content padding.
 TextAlignment: Specifies the group header text alignment.

Example
Here is an example that demonstrates how to style the data form group headers.

XAML
<telerikInput:RadDataForm Source="{Binding}">
<telerikInput:RadDataForm.GroupHeaderStyle>
<telerikDataForm:DataFormGroupHeaderStyle Background="#90C9E9"
Foreground="Black"
Height="60"
Padding="20"
TextAlignment="Center" />
</telerikInput:RadDataForm.GroupHeaderStyle>
</telerikInput:RadDataForm>
 

C#
var groupHeaderStyle = new DataFormGroupHeaderStyle
{
Background = Color.FromHex("#90C9E9"),
Foreground = Color.Black,
Height = 60,
Padding = new Thickness(20),
TextAlignment = TextAlignment.Center
};

var dataForm = new RadDataForm


{
Source = new Customer(),
GroupHeaderStyle = groupHeaderStyle
};

824
Telerik UI for Xamarin

Don't forget to add the following namespaces:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
xmlns:telerikDataForm="clr-namespace:Telerik.XamarinForms.Input.DataForm;assembly=Tele
rik.XamarinForms.Input"
 

C#
using Telerik.XamarinForms.Input;
using Telerik.XamarinForms.Input.DataForm;
 

Here is the source item class:

C#
public class Customer
{
[DisplayOptions(Group = "Basic Info", Header = "First Name")]
public string FirstName { get; set; } = "John";

[DisplayOptions(Group = "Basic Info", Header = "Last Name")]


public string LastName { get; set; } = "Doe";

[DisplayOptions(Group = "Additional Info", Header = "Age")]


public int Age { get; set; } = 24;

[DisplayOptions(Group = "Additional Info", Header = "Is New")]


public bool IsNew { get; set; } = true;

[DisplayOptions(Group = "Additional Info", Header = "Country")]


public string Country { get; set; } = "unknown";
}
 

And this is how the DataForm Group Styling looks:

825
Telerik UI for Xamarin

Sample examples demonstrating groups styling of DataForm control can be found inside the
RadDataForm -> Styling section within the SDK Samples Browser application.
 

See Also
 Editors
 Group Layouts

826
Telerik UI for Xamarin

Autocomplete editor in Android


This example will demonstrate how to add an autocomplete editor for a property called City on
Android.

First, let's create the source object:

C#
public class SourceItem : NotifyPropertyChangedBase
{
private string city;

[DisplayOptions(Header = "City")]
public string City
{
get { return this.city; }
set
{
if (this.city != value)
{
this.city = value;
this.OnPropertyChanged();
}
}
}
}
 

Then you have to specify that a custom editor will be used for the City property.

C#
this.dataForm.RegisterEditor("City", EditorType.Custom);
 

Then you have to inherit from the default DataFormRenderer and override some of its methods.

C#
public class AutoCompleteEditorRenderer : DataFormRenderer
{
private readonly Java.Lang.Object[] items = new Java.Lang.Object[] { "Madrid",
"Paris", "Barcelona", "New York", "Budapest", "Melbourne", "Bangkok" };

public AutoCompleteEditorRenderer(Context context): base(context)


{

}
protected override NativeCore.EntityPropertyEditor
GetCustomEditorForProperty(NativeViz.RadDataForm form, NativeEngine.IEntityProperty
nativeProperty, Telerik.XamarinForms.Input.DataForm.IEntityProperty property)
{

827
Telerik UI for Xamarin

if (nativeProperty.Name() == "City")
{
return new NativeEditors.DataFormAutoCompleteEditor(form, nativeProperty);
}

return base.GetCustomEditorForProperty(form, nativeProperty, property);


}

protected override void UpdateEditor(NativeCore.EntityPropertyEditor editor,


Telerik.XamarinForms.Input.DataForm.IEntityProperty property)
{
base.UpdateEditor(editor, property);

if (editor.Property().Name() == "City")
{
var autoComplete = editor.EditorView as AutoCompleteTextView;
autoComplete.Adapter = new ArrayAdapter(this.Context,
Resource.Layout.data_form_autocomplete_item, this.items);
}
}
}
 

Where the following namespaces are used:

C#
using Android.Content;
using Android.Widget;
using NativeViz = Com.Telerik.Widget.Dataform.Visualization;
using NativeEngine = Com.Telerik.Widget.Dataform.Engine;
using NativeCore = Com.Telerik.Widget.Dataform.Visualization.Core;
using NativeEditors = Com.Telerik.Widget.Dataform.Visualization.Editors;
using Telerik.XamarinForms.InputRenderer.Android;
using Xamarin.Forms;
 

You have to define the data_form_autocomplete_item resource in the Resources\layout folder of the
Android project. If the folder is missing, you have to create it. Then add the the following file:
data_form_autocomplete_item.xml

XAML
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/data_form_autocomplete_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
 

After that you will have to replace the default DataFormRenderer with the new one in MainActivity.cs:

XAML
[assembly: ExportRenderer(typeof(Telerik.XamarinForms.Input.RadDataForm),

828
Telerik UI for Xamarin

typeof(AutoCompleteEditorRenderer))]
 

Result:

See Also
 Email and Password editors in iOS
 Editors

829
Telerik UI for Xamarin

Email and Password editors on iOS


This example will demonstrate how to add custom editors in iOS DataForm.

First, create a sample class.

C#
public class Account
{
[DisplayOptions(Header = "Username", PlaceholderText = "user name", Group =
"Registration Info")]
[StringLengthValidator(5, 30, "Username should be longer than 5 symbols.")]
public string UserName { get; set; }

[DisplayOptions(Header = "Email", PlaceholderText = "email", Group = "Registration


Info")]
public string Email { get; set; }

[DisplayOptions(Header = "Password", PlaceholderText = "password", Position = 2,


Group = "Registration Info")]
[StringLengthValidator(5, 30, "Password should be longed than 5 symbols.")]
public string Password { get; set; }
}
 

Then, setup the source and register the editor types.

C#
dataForm.Source = new Account();

dataForm.RegisterEditor("Email", EditorType.Custom);
dataForm.RegisterEditor("Password", EditorType.Custom);
dataForm.RegisterEditor("Date", EditorType.DateEditor);
 

After that, you have to inherit from the default DataFormRenderer and override some of its methods.

C#
public class EmailPasswordEditorsRenderer : DataFormRenderer
{
protected override Type GetCustomEditorType(string propertyName, Type
propertyType)
{
if (propertyName == "Email")
{
return typeof(TKDataFormEmailEditor);
}

if (propertyName == "Password")
{

830
Telerik UI for Xamarin

return typeof(TKDataFormPasswordEditor);
}

return base.GetCustomEditorType(propertyName, propertyType);


}
}
 

Finally, replace the default DataFormRenderer with the new one in AppDelegate.cs:

XAML
[assembly: ExportRenderer(typeof(Telerik.XamarinForms.Input.RadDataForm),
typeof(EmailPasswordEditorsRenderer))]
 

You could check the result below:

See Also
 Autocomplete editor in Android
 Editors

831
Telerik UI for Xamarin

How to Modify RadDataForm's TelerikTheme Resources


in Android
When applying the TelerikTheme to the Telerik controls within your application and respectively the
RadDataForm element, you have the option to Modify the default theme by overriding the values of
the resources used within it. You can modify RadDataForm's resources so that different colors than
the default ones are applied. For example:

<!-- DataForm -->


<Color x:Key="TelerikDataFormEditorAccentColor">Orange</Color>
<Color x:Key="TelerikDataFormBackgroundColor">White</Color>
<Color x:Key="TelerikDataFormHeaderFontColor">Orange</Color>
<Color x:Key="TelerikDataFormEditorBorderColor">Orange</Color>
 

If you run your application in Android at this stage you will notice that not all elements are modified
as expected:

Figure 1: DataForm unmodified Editors

832
Telerik UI for Xamarin

As the RadDataForm is built on top of a truly native DataForm element and also uses native
elements as editors, modifying the appearance of these elements requires some additional steps.
The control relies on some Android styles which are applied to the editors in case of setting the
TelerikTheme class for the control. Here are all the native styles applied to the different type of
editors:

<style name="CustomDatePickerThemeBlue" parent="Theme.AppCompat.Light.Dialog">


<item name="colorAccent">#3148CA</item>
</style>

<style name="CustomTimePickerThemeBlue" parent="Theme.AppCompat.Light.Dialog">


<item name="colorAccent">#3148CA</item>
</style>

<style name="CustomCheckBoxEditorThemeBlue">
<item name="colorControlNormal">#919191</item>
<item name="colorControlActivated">#3148CA</item>
</style>

<style name="CustomTextEditorThemeBlue">
<item name="colorControlActivated">#3148CA</item>

833
Telerik UI for Xamarin

<item name="android:editTextColor">#4A4949</item>
<item name="android:textColorSecondary">#D9D9D9</item>
</style>

<style name="CustomIntegerEditorThemeBlue">
<item name="colorControlActivated">#3148CA</item>
</style>

<style name="CustomSeekBarEditorThemeBlue">
<item name="colorAccent">#3148CA</item>
</style>

<style name="CustomToggleButtonEditorThemeBlue">
<item name="colorAccent">#3148CA</item>
<item name="android:textColor">#4A4949</item>
</style>

<style name="CustomSpinnerEditorThemeBlue">
<item name="android:spinnerItemStyle">@style/SpinnerItem</item>
<item
name="android:spinnerDropDownItemStyle">@style/SpinnerItem.DropDownItem</item>
<item name="colorControlActivated">#3148CA</item>
<item name="android:textColorSecondary">#D9D9D9</item>
</style>

<style name="SpinnerItem" parent="@android:style/Widget.TextView.SpinnerItem">


<item name="android:textColor">#4A4949</item>
</style>

<style name="SpinnerItem.DropDownItem"
parent="@android:style/Widget.TextView.SpinnerItem">
<item name="android:textColor">#3148CA</item>
</style>
 

In case you need to modify a specific style of the above, you can copy that style into the
Resources/values/styles.xml file within the Android Project of the Xamarin.Forms solution and
change the colors there.

Example: Changing CheckBoxEditor's Background color to Orange:

Simply copy the whole CustomCheckBoxEditorThemeBlue style and place it at the bottom of the
styles.xml file located in the Resources/values folder of the Android Project. Eventually, you can
change the colors to orange:

<?xml version="1.0" encoding="utf-8" ?>


<resources>

. . .
<style name="CustomCheckBoxEditorThemeBlue">
<item name="colorControlNormal">#FFA500</item>
<item name="colorControlActivated">#FFA500</item>
</style>

834
Telerik UI for Xamarin

</resources>
 

Here is the appearance of the CheckBoxEditor once this style is added:

See Also
 Autocomplete editor in Android
 Email and Password Editors in iOS
 Editors

835
Telerik UI for Xamarin

RadDataGrid Overview
Most of the data on the Internet is stored in tables within a database. RadDataGrid for Xamarin
provides the same abstraction over the data – it has Columns and Rows and the intersection of a
Row and a Column is called a Cell. When the data from a database is sent to the client, it is usually
converted to a Business object (or the so-called ViewModel) where each instance represents a
Table Row and each property of the object represents a Column within the original table.

Key features
 Different column types: RadDataGrid provides plenty of built-in columns such as Text,
Boolean, Numeric, ComboBox, DateTime and Template. These pre-defined templates allow
for handling different data types and user scenarios, each with its specific editor. Go to
Columns topic for more information on this.
 Load on Demand: In some cases you may need to load data in the RadDataGrid when the
control is already displayed as this can improve the performance of your app. RadDataGrid
offers automatic data loading once the user scrolled to the last available record, or by
displaying a customizable button which will initiate loading more data items. For more info go

836
Telerik UI for Xamarin

to Load on Demand topic.


 Commands: RadDataGrid allows you to attach commands that will be executed when certain
actions, such as ColumnHeaderTap, CellTap, BeginEdit, etc, occur. For detailed information
on the matter go to Commands article.
 UI Virtualization: The highly optimized data layer of the DataGrid enables fast grouping,
sorting and filtering operations. The user interface uses virtualization for its row and cell
elements, meaning visual elements are created only when needed and only for the currently
visible cells.
 Editing: You could easily enable app users to edit data presented in the grid. Depending on
the column data type, a relevant editor allows end users to edit content in a friendly
environment. For instance, if one of the columns is a date, a date-picker will be used to offer
user a change in date field. Go to Editing topic for more details.
 Sorting, Filtering, Grouping: Easily perform SORT, FILTER or GROUP operations on your
data via the intuitive user interface or with the convenient API of the DataGrid. Read the
Sorting, Filtering and Grouping topic for more details.
 Selection Modes: DataGrid features single or multiple item selection, as well as controlling
the selection unit – Cell or Row—thus enabling any selection scenario you want your
Xamarin app users to have. Go to Selection topic for more info.
 Rows Alternation: RadDataGrid supports alternating row colors so your app users can easily
distinguish one row from another.
 Styling API and Themes: DataGrid comes with built-in theming support that allows you to
easily build slick interfaces with the look-and-feel of a predefined theme. In addition, it is
highly customizable should you prefer using your own styling. Read the Styling topic for more
details.
 Localization: The control has built-in localization support, which makes it easy to localize
your app to any language your project demands. Read the Localization topic for more details.

Check out RadDataGrid Getting Started help article that shows how to use it in a basic scenario.
 

See Also
 Columns
 Load on Demand
 Commands
 Sorting
 Filtering
 Grouping
 Selection
 Styling
 Localization

837
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadDataGrid control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadDataGrid control
 Setting RadDataGrid ItemsSource

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadDataGrid control you have to install the
Telerik.UI.for.Xamarin.DataGrid nuget package. This nuget will automatically refer the
Telerik.UI.for.Xamarin.Common, Telerik.UI.for.Xamarin.Primitives, Telerik.UI.for.Xamarin.Input,
Telerik.UI.for.Xamarin.DataControls and Telerik.UI.for.Xamarin.SkiaSharp nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadDataGrid component:

Platform Assemblies
Portable Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataGrid.dll
Telerik.XamarinForms.SkiaSharp.dll
Android Telerik.Xamarin.Android.Common.dll
Telerik.Xamarin.Android.Data.dll
Telerik.Xamarin.Android.Input.dll
Telerik.Xamarin.Android.List.dll
Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.DataGrid.dll

838
Telerik UI for Xamarin

Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.SkiaSharp.dll
iOS Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataGrid.dll
Telerik.XamarinForms.SkiaSharp.dll
UWP Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataGrid.dll
Telerik.XamarinForms.SkiaSharp.dll
RadDataGrid is rendered via the SkiaSharp graphics library so you need to install also SkiaSharp
and SkiaSharp.Views.Forms in all projects of the Xamarin solution (portable, android, ios, etc).
 

3. Adding RadDataGrid control


You could use one of the following approaches:

Drag the control from the Toolbox.


Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML:


The snippet below shows a simple RadDataGrid definition:

XAML
<telerikDataGrid:RadDataGrid x:Name="DataGrid"/>
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikDataGrid="clr-namespace:Telerik.XamarinForms.DataGrid;assembly=Telerik.Xa
marinForms.DataGrid"
 

RadDataGrid control provides UI virtualization, so it requires its visual parent to provide vertical or
horizontal space for the control to fill into. The following scenarios will measure the control with
infinity and the virtualization will not work:

 positioning the DataGrid control inside StackLayout which is wrapped in ScrollView.


 positioning the DataGrid inside ScrollView.

For additional information, please check the Controls are not Apppearing article.

839
Telerik UI for Xamarin

 
Now that you have added the control to your view, you need to make sure that is properly loaded
with the required data.

4. Setting RadDataGrid ItemsSource


By default, the RadDataGrid control will autogenerate rows depending on the number of objects in
the collection set as its ItemsSource.

Binding to a collection of objects

The collection of custom objects, then assigned to the ItemsSource property of the control:

C#
this.DataGrid.ItemsSource = new List<Data>
{
new Data { Country = "India", Capital = "New Delhi"},
new Data { Country = "South Africa", Capital = "Cape Town"},
new Data { Country = "Nigeria", Capital = "Abuja" },
new Data { Country = "Singapore", Capital = "Singapore" }
};
 

And the simple business model used:

C#
public class Data
{
public string Country { get; set; }

public string Capital { get; set; }


}
 

Here is the result:

840
Telerik UI for Xamarin

Binding to a DataTable

1. The ViewModel used:

C#
public class DataTableViewModel : NotifyPropertyChangedBase
{
private DataTable data;

public DataTable Data


{
get { return this.data; }
set
{
this.UpdateValue(ref this.data, value);
}
}

public DataTableViewModel()
{
this.Data = this.GetData();
}

private DataTable GetData()


{

DataTable country = new DataTable();


country.TableName = "Cities";
country.Columns.Add("Id", typeof(int));
country.Columns.Add("City", typeof(string));

841
Telerik UI for Xamarin

country.Columns.Add("Population", typeof(int));
country.Columns.Add("Visited On", typeof(DateTime));
country.Columns.Add("IsVisited", typeof(bool));

country.Rows.Add(0, "Sofia", 2000000, new DateTime(2012, 10, 1), true);


country.Rows.Add(1, "New York", 8419000, null, false);
country.Rows.Add(2, "London", 8982000, new DateTime(2019, 02, 11), true);
country.Rows.Add(3, "Los Angeles", 3967000, null, false);
country.Rows.Add(3, "Budapest", 1765000, new DateTime(2013, 02, 1), true);
country.Rows.Add(3, "Tokyo", 9375104, new DateTime(2015, 09, 1), true);

return country;
}
}
 

Where the DataTable namespace is using System.Data;

1. DataGrid definition:

XAML
<telerikDataGrid:RadDataGrid ItemsSource="{Binding Data}">
<telerikDataGrid:RadDataGrid.BindingContext>
<local:DataTableViewModel/>
</telerikDataGrid:RadDataGrid.BindingContext>
</telerikDataGrid:RadDataGrid>
 

Add the namespace:

XAML
xmlns:telerikDataGrid="clr-namespace:Telerik.XamarinForms.DataGrid;assembly=Telerik.Xa
marinForms.DataGrid"
 

Check our DataGrid DataTable support article for more information about this feature.
 
SDK Browser and QSF applications contain different examples that show RadDataGrid's main
features. You can find the applications in the Examples and QSF folders of your local Telerik UI for
Xamarin installation.
 

See Also
 Filtering
 Grouping
 Sorting

842
Telerik UI for Xamarin

Columns Overview
You can add columns in your RadDataGrid by working with the Columns collection of the control.
Generally, there are three approaches that you can take to define differrent columns:

 Manually: by adding columns to the RadDataGrid.Columns collection


 Automatically: by setting RadDataGrid.AutoGenerateColumns="True"
 Mixed: by adding columns to the RadDataGrid.Columns collection and also set
RadDataGrid.AutoGenerateColumns="True"

The RadDataGrid control provides the following type of columns:

 Text Column: Represents a column that converts the content of each associated cell to a
System.String object.
 Numerical Column: Represents an extended DataGridTextColumn that presents numerical
data(int and double types).
 Boolean Column: A special DataGridTypedColumn implementation that presents boolean
data.
 Date Column: An extended DataGridTextColumn that presents data of type DateTime.
 Time Column: Represents an extended DataGridTextColumn that presents the TimeOfDay
of a DateTime type.
 Picker Column: Represents an extended DataGridTextColumn that uses a Picker editor to
select value from a collection.
 Template Column: Represents a column that uses a DataTemplate to describe the content of
each associated grid cell.

When RadDataGrid.AutoGenerateColumns="True" the RadDataGrid generates typed columns


depending on the underlying data type.
 

Properties
All types of columns inherit from the DataGridColumn class which provides the following properties:

 HeaderText (string): Gets or sets the content to be displayed in the Header UI that
represents the column.
 HeaderStyle (DataGridColumnHeaderStyle): Gets or sets the Style instance that defines the
appearance of the DataGridColumnHeader control.
 HeaderContentTemplate (DataTemplate): Gets or sets the DataTemplate instance that
defines the appearance of the header.
 SizeMode (DataGridColumnSizeMode): Gets or sets the DataGridColumnSizeMode value
that controls how the column and its associated cells are sized horizontally.
 Fixed: The column has a fixed width as defined by its Width property.
 Stretch: The column is stretched to the available width proportionally to its desired width.
 Auto: The columns is sized to its desired width. That is the maximum desired width of all
associated cells.
 Width (double): - Gets or sets the fixed width for the column. Applicable when the SizeMode
property is set to DataGridColumnSizeMode.Fixed.

843
Telerik UI for Xamarin

 ActualWidth (double): Gets the actual width of the column.


 IsAutoGenerated (bool): Gets a value indication whether the column is auto-generated
internally.
 CanUserEdit (bool): Gets or sets a value indicating whether the user can edit the values in
this column.
 CanUserGroup (bool): Gets or sets a value indicating whether the user can group-by this
column by using the built-in Grouping UI.
 CanUserFilter (bool): Gets or sets a value indicating whether the user can filter this column
by using the built-in Filtering UI.
 CanUserSort (bool): Gets or sets a value indicating whether the user can sort the data by the
values in this column.
 IsVisible (bool): Gets a value indicating if a specific column should be visualized.
 CellDecorationStyle (DataGridBorderStyle): Defines the Style object that defines the
background of each cell associated with this column.
 CellDecorationStyleSelector (DataGridStyleSelector): Defines the StyleSelector instance that
allows for dynamic decoration on a per cell basis.
 CellContentTemplate (DataTemplate): Defines the appearance of each cell associated with
concrete column.
 CellEditTemplate (DataTemplate): Defines the editor associated with the concrete column.
The CellEditTemplate is displayed when the cell is in edit mode.
 FilterControlTemplate(DataTemplate): Specifies the user defined template used for Filtering
UI. The template must contain an instance of the
Telerik.XamarinForms.DataGrid.DataGridFilterControlBase class

CellContentTemplate, CellEditTemplate and FilterControlTemplate properties are part of the


DataGrid features from R2 2020 Official Release. For more details on celledit and cell content
templates features check the Cell Templatesarticle. For more details on filtercontrol template please
review the FilterControl Template section.
 
More information about CellDecorationStyle and CellDecorationStyleSelector can be found in
Columns Styling topic.
 
In order to enable the user edit mode of the RadDataGrid cell, set the
RadDataGrid.UserEditMode="Cell".
 

Example with DataGrid Columns


Here is an example containing all types of columns RadDataGrid control provides.

Use the following snippet to declare a RadDataGrid in XAML:

XAML
<telerikDataGrid:RadDataGrid x:Name="grid"
ItemsSource="{Binding Clubs}"
AutoGenerateColumns="False"
UserEditMode="Cell">
<telerikDataGrid:RadDataGrid.Columns>
<telerikDataGrid:DataGridTextColumn PropertyName="Name"
HeaderText="Name">

844
Telerik UI for Xamarin

<telerikDataGrid:DataGridTextColumn.CellContentStyle>
<telerikDataGrid:DataGridTextCellStyle TextColor="Green"
FontSize="15"
SelectedTextColor="Orange" />
</telerikDataGrid:DataGridTextColumn.CellContentStyle>
</telerikDataGrid:DataGridTextColumn>

<telerikDataGrid:DataGridNumericalColumn PropertyName="StadiumCapacity"
HeaderText="Stadium Capacity"/>

<telerikDataGrid:DataGridBooleanColumn PropertyName="IsChampion"
HeaderText="Champion?"/>

<telerikDataGrid:DataGridDateColumn PropertyName="Established"
HeaderText="Date Established"/>

<telerikDataGrid:DataGridPickerColumn PropertyName="Country"
HeaderText="Country"
ItemsSourcePath="Countries"/>

<telerikDataGrid:DataGridTemplateColumn HeaderText="Template Column">


<telerikDataGrid:DataGridTemplateColumn.CellContentTemplate>
<DataTemplate>
<StackLayout InputTransparent="True">
<Grid BackgroundColor="Orange"
Margin="0, 10, 0, 0">
<Label Text="{Binding Country}"
Margin="0, 5, 0, 5"
HorizontalOptions="Center"
VerticalTextAlignment="Center"/>
</Grid>
<Label Text="Some Custom Text"
TextColor="DarkGreen"
FontSize="10"/>
</StackLayout>
</DataTemplate>
</telerikDataGrid:DataGridTemplateColumn.CellContentTemplate>
</telerikDataGrid:DataGridTemplateColumn>

<telerikDataGrid:DataGridTimeColumn PropertyName="Time"
HeaderText="Time Column"/>
</telerikDataGrid:RadDataGrid.Columns>
</telerikDataGrid:RadDataGrid>
 

Where the telerikDataGrid namespace is the following:

xml
xmlns:telerikDataGrid="clr-namespace:Telerik.XamarinForms.DataGrid;assembly=Telerik.Xa
marinForms.DataGrid"
 

The ViewModel class is declared as following:

845
Telerik UI for Xamarin

C#
public class ColumnsViewModel
{
private ObservableCollection<Club> clubs;

public ObservableCollection<Club> Clubs => clubs ?? (clubs = CreateClubs());

private ObservableCollection<Club> CreateClubs()


{
return new ObservableCollection<Club>
{
new Club("UK Liverpool ", new DateTime(1892, 1, 1), new DateTime(2018, 2, 22,
3, 28, 33), 45362, "England"),
new Club("Manchester Utd.", new DateTime(1878, 1, 1), new DateTime(2018, 1, 1,
2, 56, 44), 76212, "England") { IsChampion = true },
new Club("Chelsea", new DateTime(1905, 1, 1), new DateTime(2018, 6, 17, 6, 19,
59), 42055, "England"),
new Club("Barcelona", new DateTime(1899, 1, 1), new DateTime(2018, 7, 12, 12,
25, 31), 99354, "Spain")
};
}
}
 

And the Club custom object:

C#
public class Club : INotifyPropertyChanged
{
private string name;
private DateTime established;
private DateTime time;
private int stadiumCapacity;
private bool isChampion;
private string country;

public Club(string name, DateTime established, DateTime time, int stadiumCapacity,


string country)
{
Name = name;
Established = established;
Time = time;
StadiumCapacity = stadiumCapacity;
Country = country;
}

public string Name


{
get { return this.name; }
set { this.UpdateValue(ref this.name, value); }
}
public DateTime Established
{

846
Telerik UI for Xamarin

get { return this.established; }


set { this.UpdateValue(ref this.established, value); }
}

public DateTime Time


{
get { return this.time; }
set { this.UpdateValue(ref this.time, value); }
}

public int StadiumCapacity


{
get { return this.stadiumCapacity; }
set { this.UpdateValue(ref this.stadiumCapacity, value); }
}

public string Country


{
get { return this.country; }
set { this.UpdateValue(ref this.country, value); }
}

public bool IsChampion


{
get { return this.isChampion; }
set { this.UpdateValue(ref this.isChampion, value); }
}

public List<string> Countries => new List<string> { "England", "Spain", "France",


"Bulgaria" };

public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged([CallerMemberName] string propertyName =


null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

protected void UpdateValue<T>(ref T field, T newValue, [CallerMemberName] string


propertyName = null)
{
if (!object.Equals(field, newValue))
{
field = newValue;
this.OnPropertyChanged(propertyName);
}
}
}
 

An example with DataGrid columns can be found in the DataGrid/Columns folder of the SDK
Samples Browser application.
 

847
Telerik UI for Xamarin

See Also
 Picker Column
 Template Column
 Text Column

848
Telerik UI for Xamarin

DataGrid TextColumn
A DataGridTextColumn converts the content of each associated cell to a System.String object.

A DataGridTextColumn has better performance than a DataGridTemplateColumn.


 

Important Properties
Here are the specific properties for TextColumns:

 PropertyName: Specifies the name of the property of the object type that represents each
row within the grid.
 HeaderText: Defines the content to be displayed in the Header UI that represents the
column.
 CellContentFormat: Defines the custom format for each cell value. The String.Format routine
is used and the format passed should be in the form required by this method.
 CellContentStyle: Defines the Style object that defines the appearance of each cell
associated with this column.
 CellContentStyleSelector: Defines the StyleSelector instance that allows for dynamic
appearance on a per cell basis.
 CellContentTemplate (DataTemplate): Defines the appearance of each cell associated with
the concrete column. CellContenTemplate gives you the opportunity to wrap the text inside
each datagrid column. You can add a Label as a content of the Text, Template Column and
wrap its text using the Label's LineBreakMode property.
 CellEditTemplate (DataTemplate): Defines the editor associated with the concrete column.
The CellEditTemplate is displayed when the cell is in edit mode.
 FilterControlTemplate(DataTemplate): Specifies the user defined template used for Filtering
UI. The template must contain an instance of the
Telerik.XamarinForms.DataGrid.DataGridFilterControlBase class

More information about CellDecorationStyle and CellDecorationStyleSelector can be found in


Columns Styling topic.
 
CellContentTemplate, CellEditTemplate and FilterControlTemplate properties are part of the
DataGrid features from R2 2020 Official Release. For more details on celledit and cell content
templates features check the Cell Templatesarticle. For more details on filtercontrol template please
review the FilterControl Template section.
 
CellContentFormat uses the format string provided by the framework. For more details check the
String.Format article.
 
The CellContentStyle property is not applied when CellContentTemplate is used.
 

Example

849
Telerik UI for Xamarin

Here is an example how the Text Column properties can be used:

XAML
<telerikGrid:DataGridTextColumn PropertyName="Name"
HeaderText="Name"
CellContentFormat="FC {0}">
<telerikGrid:DataGridTextColumn.CellContentStyle>
<telerikGrid:DataGridTextCellStyle TextColor="Green"
FontSize="15"
SelectedTextColor="Orange" />
</telerikGrid:DataGridTextColumn.CellContentStyle>
</telerikGrid:DataGridTextColumn>
 

See Also
 Columns Styling

850
Telerik UI for Xamarin

 Numerical Column
 Boolean Column

851
Telerik UI for Xamarin

DataGrid NumericalColumn
The DataGridNumericalColumn is used to represent only numerical values. It uses an entry control
to edit the value in EditMode. The difference between this column and the text one is that it will
directly invoke the numeric keyboard on the mobile devices

Important Properties
 PropertyName: Specifies the name of the property of the object type that represents each
row within the grid.
 HeaderText: Defines the content to be displayed in the Header UI that represents the
column.
 CellContentStyle: Defines the Style object that defines the appearance of each cell
associated with this column. The TargetType of the Style should be TextBlock type.
 CellContentStyleSelector: Defines the StyleSelector instance that allows for dynamic
appearance on a per cell basis.
 CellContentFormat: Defines the custom format for each cell value. The String.Format routine
is used and the format passed should be in the form required by this method.
 CellContentTemplate (DataTemplate): Defines the appearance of each cell associated with
the concrete column. CellContenTemplate gives you the opportunity to wrap the text inside
each datagrid column. You can add a Label as a content of the Text, Template Column and
wrap its text using the Label's LineBreakMode property.
 CellEditTemplate (DataTemplate): Defines the editor associated with the concrete column.
The CellEditTemplate is displayed when the cell is in edit mode.
 FilterControlTemplate(DataTemplate): Specifies the user defined template used for Filtering
UI. The template must contain an instance of the
Telerik.XamarinForms.DataGrid.DataGridFilterControlBase class

More information about CellDecorationStyle and CellDecorationStyleSelector can be found in


Columns Styling topic.
 
CellContentTemplate, CellEditTemplate and FilterControlTemplate properties are part of the
DataGrid features from R2 2020 Official Release. For more details on celledit and cell content
templates features check the Cell Templatesarticle. For more details on filtercontrol template please
review the FilterControl Template section.
 
CellContentFormat uses the format string provided by the framework. For more details check the
Standard Numeric Formatting and Custom Numeric Formatting articles.
 
The CellContentStyle is not applied when CellContentTemplate is used.
 

Example
XAML
<telerikGrid:DataGridNumericalColumn PropertyName="StadiumCapacity"
HeaderText="Stadium Capacity"

852
Telerik UI for Xamarin

CellContentFormat=" Seats - {0:D}">


<telerikGrid:DataGridNumericalColumn.CellContentStyle>
<telerikGrid:DataGridTextCellStyle TextColor="Green"
FontSize="18"
SelectedTextColor="LightCoral" />
</telerikGrid:DataGridNumericalColumn.CellContentStyle>
</telerikGrid:DataGridNumericalColumn>
 

See Also
 Columns Styling
 Boolean Column
 Date Column

853
Telerik UI for Xamarin

DataGrid BooleanColumn
The DataGridBooleanColumn is used to represent boolean values. It uses Switch control to edit its
values in EditMode.

Important Properties
 PropertyName: Specifies the name of the property of the object type that represents each
row within the grid.
 HeaderText: Defines the content to be displayed in the Header UI that represents the
column.
 CellContentStyle: Defines the Style object that defines the appearance of each cell
associated with this column. The TargetType of the Style should be TextBlock type.
 CellContentStyleSelector: Defines the StyleSelector instance that allows for dynamic
appearance on a per cell basis.
 CellContentFormat: Defines the custom format for each cell value. The String.Format routine
is used and the format passed should be in the form required by this method.
 CellContentTemplate (DataTemplate): Defines the appearance of each cell associated with
the concrete column. CellContenTemplate gives you the opportunity to wrap the text inside
each datagrid column. You can add a Label as a content of the Text, Template Column and
wrap its text using the Label's LineBreakMode property.
 CellEditTemplate (DataTemplate): Defines the editor associated with the concrete column.
The CellEditTemplate is displayed when the cell is in edit mode.
 FilterControlTemplate(DataTemplate): Specifies the user defined template used for Filtering
UI. The template must contain an instance of the
Telerik.XamarinForms.DataGrid.DataGridFilterControlBase class

More information about CellDecorationStyle and CellDecorationStyleSelector can be found in


Columns Styling topic.
 
CellContentTemplate, CellEditTemplate and FilterControlTemplate properties are part of the
DataGrid features from R2 2020 Official Release. For more details on celledit and cell content
templates features check the Cell Templatesarticle. For more details on filtercontrol template please
review the FilterControl Template section.
 
CellContentFormat uses the format string provided by the framework. For more details check the
String.Format article.
 
The CellContentStyle property is not applied when CellContentTemplate is used.
 

Example
XAML
<telerikGrid:DataGridBooleanColumn PropertyName="IsChampion"
HeaderText="Champion?">
<telerikGrid:DataGridBooleanColumn.CellContentStyle>

854
Telerik UI for Xamarin

<telerikGrid:DataGridTextCellStyle TextColor="Green"
FontSize="18"
SelectedTextColor="Blue" />
</telerikGrid:DataGridBooleanColumn.CellContentStyle>
</telerikGrid:DataGridBooleanColumn>
 

See Also
 Columns Styling
 Text Column
 Numerical Column

855
Telerik UI for Xamarin

DataGrid DateColumn
The DataGridDateColumn is used to represent DateTime objects. It uses the DatePicker control to
pick a value in EditMode.

Important Properties
 PropertyName: Specifies the name of the property of the object type that represents each
row within the grid.
 HeaderText: Defines the content to be displayed in the Header UI that represents the
column.
 CellContentStyle: Defines the Style object that defines the appearance of each cell
associated with this column. The TargetType of the Style should be TextBlock type.
 CellContentStyleSelector: Defines the StyleSelector instance that allows for dynamic
appearance on a per cell basis.
 CellContentFormat: Specifies the custom format for each cell value. The String.Format
routine is used and the format passed should be in the form required by this method.
 CellContentTemplate (DataTemplate): Defines the appearance of each cell associated with
the concrete column. CellContenTemplate gives you the opportunity to wrap the text inside
each datagrid column. You can add a Label as a content of the Text, Template Column and
wrap its text using the Label's LineBreakMode property.
 CellEditTemplate (DataTemplate): Defines the editor associated with the concrete column.
The CellEditTemplate is displayed when the cell is in edit mode.
 FilterControlTemplate(DataTemplate): Specifies the user defined template used for Filtering
UI. The template must contain an instance of the
Telerik.XamarinForms.DataGrid.DataGridFilterControlBase class

More information about CellDecorationStyle and CellDecorationStyleSelector can be found in


Columns Styling topic.
 
CellContentTemplate, CellEditTemplate and FilterControlTemplate properties are part of the
DataGrid features from R2 2020 Official Release. For more details on celledit and cell content
templates features check the Cell Templatesarticle. For more details on filtercontrol template please
review the FilterControl Template section.
 
CellContentFormat uses the format string provided by the framework. For more details check the
Standard Date and Time Formatting and Custom Date and Time Formatting articles.
 
The CellContentStyle is not applied when CellContentTemplate is used.
 

Example
XAML
<telerikGrid:DataGridDateColumn PropertyName="Established"
HeaderText="Date Established"
CellContentFormat="{}{0: ddd-d-MMM-yyyy}">

856
Telerik UI for Xamarin

<telerikGrid:DataGridDateColumn.CellContentStyle>
<telerikGrid:DataGridTextCellStyle TextColor="LightBlue"
FontSize="18"
SelectedTextColor="Blue" />
</telerikGrid:DataGridDateColumn.CellContentStyle>
</telerikGrid:DataGridDateColumn>
 

See Also
 Columns Styling
 Text Column
 Time Column

857
Telerik UI for Xamarin

DataGrid TimeColumn
The DataGridTimeColumn is used to represent DateTime objects. It uses the TimePicker control to
pick a value in EditMode.

Important Properties
 PropertyName: Specifies the name of the property of the object type that represents each
row within the grid.
 HeaderText: Defines the content to be displayed in the Header UI that represents the
column.
 CellContentStyle: Defines the Style object that defines the appearance of each cell
associated with this column. The TargetType of the Style should be TextBlock type.
 CellContentStyleSelector: Defines the StyleSelector instance that allows for dynamic
appearance on a per cell basis.
 CellContentFormat: Defines the custom format for each cell value. The String.Format routine
is used and the format passed should be in the form required by this method.
 CellContentTemplate (DataTemplate): Defines the appearance of each cell associated with
the concrete column. CellContenTemplate gives you the opportunity to wrap the text inside
each datagrid column. You can add a Label as a content of the Text, Template Column and
wrap its text using the Label's LineBreakMode property.
 CellEditTemplate (DataTemplate): Defines the editor associated with the concrete column.
The CellEditTemplate is displayed when the cell is in edit mode.
 FilterControlTemplate(DataTemplate): Specifies the user defined template used for Filtering
UI. The template must contain an instance of the
Telerik.XamarinForms.DataGrid.DataGridFilterControlBase class

More information about CellDecorationStyle and CellDecorationStyleSelector can be found in


Columns Styling topic.
 
CellContentFormat uses the format string provided by the framework. For more details check the
Standard Date and Time Formatting and Custom Date and Time Formatting articles.
 
CellContentTemplate, CellEditTemplate and FilterControlTemplate properties are part of the
DataGrid features from R2 2020 Official Release. For more details on celledit and cell content
templates features check the Cell Templatesarticle. For more details on filtercontrol template please
review the FilterControl Template section.
 
The CellContentStyle property is not applied when CellContentTemplate is used.
 

Example
XAML
<telerikGrid:DataGridTimeColumn PropertyName="Time"
HeaderText="Time Column"
CellContentFormat="{}{0: hh:mm:ss}">

858
Telerik UI for Xamarin

<telerikGrid:DataGridTimeColumn.CellContentStyle>
<telerikGrid:DataGridTextCellStyle TextColor="Lime"
FontSize="18"
SelectedTextColor="Red" />
</telerikGrid:DataGridTimeColumn.CellContentStyle>
</telerikGrid:DataGridTimeColumn>
 

See Also
 Columns Styling
 Text Column
 Date Column

859
Telerik UI for Xamarin

DataGrid PickerColumn
The DataGridPickerColumn uses a Picker control in Edit mode to select a value from list of
possibilities.

Important Properties
Here are the specific properties defined for DataGridPickerColumn:

 ItemsSource (IEnumerable): This property is used when the source of the Picker items is not
part of the data and is the same for all items in the grid.
 ItemsSourcePath (string): This property is used to specify a property of your data class to be
used as source for the Picker control.
 ItemDisplayBindingPath (string): Sets the display path of the items in the Picker selector. It
points to a field in the items from the ItemsSource collection of the Picker.
 PropertyName: Defines the name of the property of the object type that represents each row
within the grid.
 HeaderText: Defines the content to be displayed in the Header UI that represents the
column.
 CellContentStyle: Defines the Style object that defines the appearance of each cell
associated with this column. The TargetType of the Style should be TextBlock type.
 CellContentStyleSelector: Defines the StyleSelector instance that allows for dynamic
appearance on a per cell basis.
 CellContentFormat: Defines the custom format for each cell value. The String.Format routine
is used and the format passed should be in the form required by this method.
 CellContentTemplate (DataTemplate): Defines the appearance of each cell associated with
the concrete column. CellContenTemplate gives you the opportunity to wrap the text inside
each datagrid column. You can add a Label as a content of the Text, Template Column and
wrap its text using the Label's LineBreakMode property.
 CellEditTemplate (DataTemplate): Defines the editor associated with the concrete column.
The CellEditTemplate is displayed when the cell is in edit mode.
 FilterControlTemplate(DataTemplate): Specifies the user defined template used for Filtering
UI. The template must contain an instance of the
Telerik.XamarinForms.DataGrid.DataGridFilterControlBase class

More information about CellDecorationStyle and CellDecorationStyleSelector can be found in


Columns Styling topic.
 
CellContentTemplate, CellEditTemplate and FilterControlTemplate properties are part of the
DataGrid features from R2 2020 Official Release. For more details on celledit and cell content
templates features check the Cell Templatesarticle. For more details on filtercontrol template please
review the FilterControl Template section.
 
CellContentFormat uses the format string provided by the framework. For more details check the
String.Format article.
 
The CellContentStyle is not applied when CellContentTemplate is used.
 

860
Telerik UI for Xamarin

Example
XAML
<telerikGrid:DataGridPickerColumn PropertyName="Country"
HeaderText="Country"
CellContentFormat="Picked: {0}"
ItemsSourcePath="Countries">
<telerikGrid:DataGridPickerColumn.CellContentStyle>
<telerikGrid:DataGridTextCellStyle SelectedTextColor="DarkGreen"
TextColor="Black"
FontSize="15" />
</telerikGrid:DataGridPickerColumn.CellContentStyle>
</telerikGrid:DataGridPickerColumn>
 

See Also
 Columns Styling
 Text Column
 Time Column

861
Telerik UI for Xamarin

DataGrid TemplateColumn
If you want to completely customize the content of the cells in a grid column you can use
DataGridTemplateColumn, which uses a DataTemplate to describe the content of each associated
grid cell.

Important Properties:
 HeaderText: Defines the content to be displayed in the Header UI that represents the
column.
 SortDescriptor (SortDescriptorBase)
 GroupDescriptor (GroupDescriptorBase)
 CellContentTemplate (DataTemplate): Defines the DataTemplate instance that defines the
appearance of each cell associated with this column.
 CellContentTemplateSelector (DataTemplateSelector): Defines a DataTemplateSelector
instance that may be used to retrieve dynamic data templates on a per cell basis.
 CellEditTemplate (DataTemplate): Defines the editor associated with the concrete column.
The CellEditTemplate is displayed when the cell is in edit mode.
 FilterControlTemplate(DataTemplate): Specifies the user defined template used for Filtering
UI. The template must contain an instance of the
Telerik.XamarinForms.DataGrid.DataGridFilterControlBase class

More information about Sorting and Grouping can be found in DataGrid Soting and DataGrid Grouping
articles.
 
CellContentTemplate, CellEditTemplate and FilterControlTemplate properties are part of the
DataGrid features from R2 2020 Official Release. For more details on celledit and cell content
templates features check the Cell Templatesarticle. For more details on filtercontrol template please
review the FilterControl Template section.
 

Sorting and Grouping for Template Column


The example below shows how Sorting and Grouping can be applied to the DataGrid Template
Column.

Here is how the VieWModel and the business object are defined:

C#
public class ViewModel
{
public ViewModel()
{
var source = new ObservableCollection<Person>();
source.Add(new Person() { Name = "Kiko", Age = 23 });
source.Add(new Person() { Name = "Jerry", Age = 23 });
source.Add(new Person() { Name = "Ethan", Age = 51 });

862
Telerik UI for Xamarin

source.Add(new Person() { Name = "Isabella", Age = 23 });


source.Add(new Person() { Name = "Joshua", Age = 51 });
source.Add(new Person() { Name = "Logan", Age = 51 });
source.Add(new Person() { Name = "Aaron", Age = 23 });

this.Data = source;
}

public ObservableCollection<Person> Data { get; set; }


}

public class Person


{
public string Name { get; set; }
public int Age { get; set; }
}
 

The DataGrid definition:

XAML
<telerikDataGrid:RadDataGrid AutoGenerateColumns="False"
ItemsSource="{Binding Data}"
UserSortMode="Multiple">
<telerikDataGrid:RadDataGrid.BindingContext>
<local:ViewModel/>
</telerikDataGrid:RadDataGrid.BindingContext>
<telerikDataGrid:RadDataGrid.Columns>
<telerikDataGrid:DataGridTextColumn PropertyName="Name"
HeaderText="Name"
CanUserSort="True"/>
<telerikDataGrid:DataGridTemplateColumn HeaderText="Age"
CanUserSort="True">
<telerikDataGrid:DataGridTemplateColumn.CellContentTemplate>
<DataTemplate>
<Label Text="{Binding Age}" />
</DataTemplate>
</telerikDataGrid:DataGridTemplateColumn.CellContentTemplate>

<!-- Tell the DataGrid to sort using Age property with a SortDescriptor -->
<telerikDataGrid:DataGridTemplateColumn.SortDescriptor>
<telerikCommon:PropertySortDescriptor PropertyName="Age" />
</telerikDataGrid:DataGridTemplateColumn.SortDescriptor>

<!-- Tell the DataGrid to group using Age property with a GroupDescriptor -->
<telerikDataGrid:DataGridTemplateColumn.GroupDescriptor>
<telerikCommon:PropertyGroupDescriptor PropertyName="Age" />
</telerikDataGrid:DataGridTemplateColumn.GroupDescriptor>
</telerikDataGrid:DataGridTemplateColumn>
</telerikDataGrid:RadDataGrid.Columns>
</telerikDataGrid:RadDataGrid>
 

863
Telerik UI for Xamarin

See Also
 Columns Styling
 Boolean Column
 Date Column

864
Telerik UI for Xamarin

Columns Cell Templates


This article describes how to set the content and edit templates to the DataGrid column using the
CellContentTemplate and CellEditTemplate properties.

 CellContentTemplate (DataTemplate): Defines the appearance of each cell associated with


the concrete column. CellContenTemplate gives you the opportunity to wrap the text inside
each datagrid column. You can add a Label as a content of the Text, Template Column and
wrap its text using the Label's LineBreakMode property.
 CellEditTemplate (DataTemplate): Defines the editor associated with the concrete column.
The CellEditTemplate is displayed when the cell is in edit mode.

CellContentTemplate and CellEditTemplate properties are part of the DataGrid features from R2
2020 Official Release.
 

Cell Content Template Example


Use the following snippet to declare a RadDataGrid in XAML:

XAML
<telerikDataGrid:RadDataGrid x:Name="dataGrid"
ItemsSource="{Binding Clubs}"
AutoGenerateColumns="False"
UserEditMode="Cell">
<telerikDataGrid:RadDataGrid.Columns>
<telerikDataGrid:DataGridTextColumn PropertyName="Name"
Width="100"
SizeMode="Fixed"
HeaderText="Name">
<telerikDataGrid:DataGridColumn.CellContentTemplate>
<DataTemplate>
<Label Text="{Binding Name}"
LineBreakMode="TailTruncation"
VerticalOptions="Center"/>
</DataTemplate>
</telerikDataGrid:DataGridColumn.CellContentTemplate>
</telerikDataGrid:DataGridTextColumn>

<telerikDataGrid:DataGridBooleanColumn PropertyName="IsChampion"
HeaderText="Champion?">
<telerikDataGrid:DataGridColumn.CellContentTemplate>
<DataTemplate>
<Switch IsToggled="{Binding IsChampion}"
VerticalOptions="Center"/>
</DataTemplate>
</telerikDataGrid:DataGridColumn.CellContentTemplate>
</telerikDataGrid:DataGridBooleanColumn>

865
Telerik UI for Xamarin

<telerikDataGrid:DataGridDateColumn PropertyName="Established"
HeaderText="Date Established">
<telerikDataGrid:DataGridColumn.CellContentTemplate>
<DataTemplate>
<telerikInput:RadDateTimePicker Date="{Binding Established}"
DisplayStringFormat="yyyy/MMM/dd"
VerticalOptions="Center"/>
</DataTemplate>
</telerikDataGrid:DataGridColumn.CellContentTemplate>
</telerikDataGrid:DataGridDateColumn>

<telerikDataGrid:DataGridTemplateColumn HeaderText="Template Column">


<telerikDataGrid:DataGridColumn.CellContentTemplate>
<DataTemplate>
<Label Text="{Binding Country}"
Margin="0, 5, 0, 5"
HorizontalOptions="Center"
VerticalTextAlignment="Center"/>
</DataTemplate>
</telerikDataGrid:DataGridColumn.CellContentTemplate>
</telerikDataGrid:DataGridTemplateColumn>
</telerikDataGrid:RadDataGrid.Columns>
</telerikDataGrid:RadDataGrid>
 

And add the following namespaces:

xml
xmlns:telerikGrid="clr-namespace:Telerik.XamarinForms.DataGrid;assembly=Telerik.Xamari
nForms.DataGrid"
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

The ViewModel class is declared as following:

C#
public class ColumnsViewModel
{
private ObservableCollection<Club> clubs;

public ObservableCollection<Club> Clubs => clubs ?? (clubs = CreateClubs());

private ObservableCollection<Club> CreateClubs()


{
return new ObservableCollection<Club>
{
new Club("UK Liverpool ", new DateTime(1892, 1, 1), new DateTime(2018, 2, 22,
3, 28, 33), 45362, "England"),
new Club("Manchester Utd.", new DateTime(1878, 1, 1), new DateTime(2018, 1, 1,
2, 56, 44), 76212, "England") { IsChampion = true },
new Club("Chelsea", new DateTime(1905, 1, 1), new DateTime(2018, 6, 17, 6, 19,
59), 42055, "England"),

866
Telerik UI for Xamarin

new Club("Barcelona", new DateTime(1899, 1, 1), new DateTime(2018, 7, 12, 12,


25, 31), 99354, "Spain")
};
}
}
 

And the Club custom object:

C#
public class Club : INotifyPropertyChanged
{
private string name;
private DateTime established;
private DateTime time;
private int stadiumCapacity;
private bool isChampion;
private string country;

public Club(string name, DateTime established, DateTime time, int stadiumCapacity,


string country)
{
Name = name;
Established = established;
Time = time;
StadiumCapacity = stadiumCapacity;
Country = country;
}

public string Name


{
get { return this.name; }
set { this.UpdateValue(ref this.name, value); }
}
public DateTime Established
{
get { return this.established; }
set { this.UpdateValue(ref this.established, value); }
}

public DateTime Time


{
get { return this.time; }
set { this.UpdateValue(ref this.time, value); }
}

public int StadiumCapacity


{
get { return this.stadiumCapacity; }
set { this.UpdateValue(ref this.stadiumCapacity, value); }
}

public string Country

867
Telerik UI for Xamarin

{
get { return this.country; }
set { this.UpdateValue(ref this.country, value); }
}

public bool IsChampion


{
get { return this.isChampion; }
set { this.UpdateValue(ref this.isChampion, value); }
}

public List<string> Countries => new List<string> { "England", "Spain", "France",


"Bulgaria" };

public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged([CallerMemberName] string propertyName =


null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

protected void UpdateValue<T>(ref T field, T newValue, [CallerMemberName] string


propertyName = null)
{
if (!object.Equals(field, newValue))
{
field = newValue;
this.OnPropertyChanged(propertyName);
}
}
}
 

DataGrid Date Column with CellContentTemplate property and inside the template we have added a
DateTime Picker control

868
Telerik UI for Xamarin

An example with DataGrid CellContentTemplate can be found in the DataGrid/Columns folder of the
SDK Samples Browser application.
 

Cell Edit Template Example


Use the following snippet to declare a RadDataGrid in XAML:

XAML
<telerikDataGrid:RadDataGrid x:Name="dataGrid"
ItemsSource="{Binding Clubs}"
AutoGenerateColumns="False"
SelectionMode="None"
UserEditMode="Cell">
<telerikDataGrid:RadDataGrid.Columns>
<telerikDataGrid:DataGridTextColumn PropertyName="Name"
HeaderText="Name">
<telerikDataGrid:DataGridColumn.CellEditTemplate>
<DataTemplate>
<StackLayout>
<Entry Text="{Binding Item.Name, Mode=TwoWay}" Margin="5">
<VisualElement.Behaviors>
<telerikCommon:RadEventToCommandBehavior EventName="Completed"
Command="{Binding CommitEditCommand}" />
</VisualElement.Behaviors>
</Entry>
<Button Text="Cancel" Command="{Binding CancelEditCommand}" />
</StackLayout>
</DataTemplate>

869
Telerik UI for Xamarin

</telerikDataGrid:DataGridColumn.CellEditTemplate>
</telerikDataGrid:DataGridTextColumn>

<telerikDataGrid:DataGridBooleanColumn PropertyName="IsChampion"
HeaderText="Champion?">
<telerikDataGrid:DataGridColumn.CellEditTemplate>
<DataTemplate>
<StackLayout>
<Switch IsToggled="{Binding Item.IsChampion, Mode=TwoWay}" />
<Button Text="X" Command="{Binding CancelEditCommand}" />
<Button Text="OK" Command="{Binding CommitEditCommand}" />
</StackLayout>
</DataTemplate>
</telerikDataGrid:DataGridColumn.CellEditTemplate>
</telerikDataGrid:DataGridBooleanColumn>

<telerikDataGrid:DataGridNumericalColumn PropertyName="StadiumCapacity">
<telerikDataGrid:DataGridColumn.CellEditTemplate>
<DataTemplate>
<StackLayout Orientation="Horizontal"
BackgroundColor="LightGray">
<Slider Maximum="80000" Minimum="30000"
Value="{Binding Item.StadiumCapacity}"
HorizontalOptions="FillAndExpand" />
<Button Text="X" Command="{Binding CancelEditCommand}" />
<Button Text="OK" Command="{Binding CommitEditCommand}" />
</StackLayout>
</DataTemplate>
</telerikDataGrid:DataGridColumn.CellEditTemplate>
</telerikDataGrid:DataGridNumericalColumn>
<telerikDataGrid:DataGridDateColumn PropertyName="Established"
CellContentFormat="{}{0: yyyy/MMM/dd}">
<telerikDataGrid:DataGridColumn.CellEditTemplate>
<DataTemplate>
<telerikInput:RadDatePicker Date="{Binding Item.Established, Mode=TwoWay}"
DisplayStringFormat="yyyy/MMM/dd">
<telerikInput:RadDatePicker.SelectorSettings>
<telerikInput:PickerPopupSelectorSettings AcceptCommand="{Binding
CommitEditCommand}"
CancelCommand="{Binding CancelEditCommand}"/>
</telerikInput:RadDatePicker.SelectorSettings>
</telerikInput:RadDatePicker>
</DataTemplate>
</telerikDataGrid:DataGridColumn.CellEditTemplate>
</telerikDataGrid:DataGridDateColumn>
<telerikDataGrid:DataGridTimeColumn PropertyName="Time">
<telerikDataGrid:DataGridColumn.CellEditTemplate>
<DataTemplate>
<telerikInput:RadTimePicker Time="{Binding Item.Time, Mode=TwoWay}">
<telerikInput:RadTimePicker.SelectorSettings>
<telerikInput:PickerPopupSelectorSettings AcceptCommand="{Binding
CommitEditCommand}"
CancelCommand="{Binding CancelEditCommand}"/>
</telerikInput:RadTimePicker.SelectorSettings>

870
Telerik UI for Xamarin

</telerikInput:RadTimePicker>
</DataTemplate>
</telerikDataGrid:DataGridColumn.CellEditTemplate>
</telerikDataGrid:DataGridTimeColumn>
</telerikDataGrid:RadDataGrid.Columns>
</telerikDataGrid:RadDataGrid>
 

And add the following namespaces

xml
xmlns:telerikGrid="clr-namespace:Telerik.XamarinForms.DataGrid;assembly=Telerik.Xamari
nForms.DataGrid"
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

The ViewModel class is declared as following:

C#
public class ColumnsViewModel
{
private ObservableCollection<Club> clubs;

public ObservableCollection<Club> Clubs => clubs ?? (clubs = CreateClubs());

private ObservableCollection<Club> CreateClubs()


{
return new ObservableCollection<Club>
{
new Club("UK Liverpool ", new DateTime(1892, 1, 1), new DateTime(2018, 2, 22,
3, 28, 33), 45362, "England"),
new Club("Manchester Utd.", new DateTime(1878, 1, 1), new DateTime(2018, 1, 1,
2, 56, 44), 76212, "England") { IsChampion = true },
new Club("Chelsea", new DateTime(1905, 1, 1), new DateTime(2018, 6, 17, 6, 19,
59), 42055, "England"),
new Club("Barcelona", new DateTime(1899, 1, 1), new DateTime(2018, 7, 12, 12,
25, 31), 99354, "Spain")
};
}
}
 

And the Club custom object:

C#
public class Club : INotifyPropertyChanged
{
private string name;
private DateTime established;
private DateTime time;
private int stadiumCapacity;

871
Telerik UI for Xamarin

private bool isChampion;


private string country;

public Club(string name, DateTime established, DateTime time, int stadiumCapacity,


string country)
{
Name = name;
Established = established;
Time = time;
StadiumCapacity = stadiumCapacity;
Country = country;
}

public string Name


{
get { return this.name; }
set { this.UpdateValue(ref this.name, value); }
}
public DateTime Established
{
get { return this.established; }
set { this.UpdateValue(ref this.established, value); }
}

public DateTime Time


{
get { return this.time; }
set { this.UpdateValue(ref this.time, value); }
}

public int StadiumCapacity


{
get { return this.stadiumCapacity; }
set { this.UpdateValue(ref this.stadiumCapacity, value); }
}

public string Country


{
get { return this.country; }
set { this.UpdateValue(ref this.country, value); }
}

public bool IsChampion


{
get { return this.isChampion; }
set { this.UpdateValue(ref this.isChampion, value); }
}

public List<string> Countries => new List<string> { "England", "Spain", "France",


"Bulgaria" };

public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged([CallerMemberName] string propertyName =

872
Telerik UI for Xamarin

null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

protected void UpdateValue<T>(ref T field, T newValue, [CallerMemberName] string


propertyName = null)
{
if (!object.Equals(field, newValue))
{
field = newValue;
this.OnPropertyChanged(propertyName);
}
}
}
 

DataGrid Boolean Column with CellEditTemplate property and inside the template we have added a
switch, and two buttons. The edit template is visualized when the cell is in edit mode.

A sample example with DataGrid CellEditTemplate can be found in the DataGrid/Columns folder of
the SDK Samples Browser application.
 

See Also
 Picker Column
 Template Column
 Text Column

873
Telerik UI for Xamarin

Columns Width
This article describes how to set a width to the DataGrid column using the SizeMode and Width
properties.

 SizeMode (DataGridColumnSizeMode): Defines the DataGridColumnSizeMode value that


controls how the column and its associated cells are sized horizontally.
 Fixed: The column has a fixed width as defined by its Width property.
 Stretch: The column is stretched to the available width proportionally to its desired width.
 Auto: The columns is sized to its desired width. That is the maximum desired width of all
associated cells.
 Width (double): - Specifies the fixed width for the column. Applicable when the SizeMode
property is set to DataGridColumnSizeMode.Fixed.
 ActualWidth (double): Gets the actual width of the column.

Example
For the purpose of this example, we are going to use the following business object:

C#
public class Data
{
public string Country { get; set; }
public string Capital { get; set; }
}
 

After you have created your collection of custom objects, you should assign it to the ItemsSource
property of the control:

C#
this.grid.ItemsSource = new List<Data>
{
new Data { Country = "Columbia", Capital = "Bogota" },
new Data { Country = "Germany", Capital = "Berlin" },
new Data { Country = "Italy", Capital = "Rome" },
new Data { Country = "France", Capital = "Paris" },
new Data { Country = "Bulgaria", Capital = "Sofia" },
};
 

1. First scenario when SizeMode="Fixed":

XAML
<telerikGrid:RadDataGrid x:Name="grid" AutoGenerateColumns="False"
BackgroundColor="Red">
<telerikGrid:RadDataGrid.Columns>
<telerikGrid:DataGridTextColumn PropertyName="Country" HeaderText="Country"

874
Telerik UI for Xamarin

Width="100" SizeMode="Fixed"/>
<telerikGrid:DataGridTextColumn PropertyName="Capital" HeaderText="Capital"
Width="200" SizeMode="Fixed"/>
</telerikGrid:RadDataGrid.Columns>
</telerikGrid:RadDataGrid>
```
 

Where the telerikGrid namespace is the following:

xml
xmlns:telerikGrid="clr-namespace:Telerik.XamarinForms.DataGrid;assembly=Telerik.Xamari
nForms.DataGrid"
```
 

The Width property of columns will apply only when SizeMode="Fixed".


 
The first and second columns have set widths of 100 and 200, respectively:

2. Second scenario when SizeMode="Stretch":

XAML
<telerikGrid:RadDataGrid x:Name="grid" AutoGenerateColumns="False"
BackgroundColor="Red">
<telerikGrid:RadDataGrid.Columns>
<telerikGrid:DataGridTextColumn PropertyName="Country" HeaderText="Country"
Width="100" SizeMode="Stretch"/>
<telerikGrid:DataGridTextColumn PropertyName="Capital" HeaderText="Capital"
Width="200" SizeMode="Stretch"/>
</telerikGrid:RadDataGrid.Columns>
</telerikGrid:RadDataGrid>
```
 

875
Telerik UI for Xamarin

Where the telerikGrid namespace is the following:

xml
xmlns:telerikGrid="clr-namespace:Telerik.XamarinForms.DataGrid;assembly=Telerik.Xamari
nForms.DataGrid"
```
 

The columns take all the available space proportionally. The Width property is ignored.

3. Third scenario when SizeMode="Auto":

XAML
<telerikGrid:RadDataGrid x:Name="grid" AutoGenerateColumns="False"
BackgroundColor="Red">
<telerikGrid:RadDataGrid.Columns>
<telerikGrid:DataGridTextColumn PropertyName="Country" HeaderText="Country"
Width="100" SizeMode="Auto"/>
<telerikGrid:DataGridTextColumn PropertyName="Capital" HeaderText="Capital"
Width="200" SizeMode="Auto"/>
</telerikGrid:RadDataGrid.Columns>
</telerikGrid:RadDataGrid>
```
 

Where the telerikGrid namespace is the following:

xml
xmlns:telerikGrid="clr-namespace:Telerik.XamarinForms.DataGrid;assembly=Telerik.Xamari
nForms.DataGrid"
```
 

The columns take only as much space as they need. The Width property is ignored.

876
Telerik UI for Xamarin

Lastly, lets use three columns to fully clarify the SizeMode behavior:

XAML
<telerikGrid:RadDataGrid x:Name="grid" AutoGenerateColumns="False">
<telerikGrid:RadDataGrid.Columns>
<telerikGrid:DataGridTextColumn PropertyName="Country" HeaderText="Country"
Width="100" SizeMode="Fixed"/>
<telerikGrid:DataGridTextColumn PropertyName="Capital" HeaderText="Capital"
Width="200" SizeMode="Auto"/>
<telerikGrid:DataGridTextColumn PropertyName="Country" HeaderText="Country"
Width="200" SizeMode="Stretch"/>
</telerikGrid:RadDataGrid.Columns>
</telerikGrid:RadDataGrid>
 

Where the telerikGrid namespace is the following:

xml
xmlns:telerikGrid="clr-namespace:Telerik.XamarinForms.DataGrid;assembly=Telerik.Xamari
nForms.DataGrid"
 

The first and the third columns each have a fixed size of 100 and the second column takes all the
available space because of SizeMode="Stretch":

877
Telerik UI for Xamarin

See Also
 Picker Column
 Template Column
 Text Column

878
Telerik UI for Xamarin

Nested Properties Support


With R3 2018 RadDataGrid provides support for nested properties - this allows binding of complex
objects to the grid columns.

In addition, the DataGrid control provides the following property:

 ListenForNestedPropertyChange (bool): Allows the DataGrid to listen for changes of the


nested properties' values. By default it is false.

ListenForNestedPropertyChange is false due to optimization purposes, you could enable it in case


you'd need to update the nested properties' values.
 

Example
Here is an example how you could utilize the nested properties feature in DataGrid:

First, create the needed business objects, for example type Person that will have property of type
Address:

C#
public class Person : NotifyPropertyChangedBase
{
private string name;
private double age;
private Address address;

public string Name


{
get { return this.name; }
set { this.UpdateValue(ref this.name, value); }
}
public double Age
{
get { return this.age; }
set { this.UpdateValue(ref this.age, value); }
}
public Address Address
{
get { return this.address; }
set { this.UpdateValue(ref this.address, value); }
}
}
 

C#
public class Address : NotifyPropertyChangedBase

879
Telerik UI for Xamarin

{
private string city;
private string street;
public string City
{
get { return this.city; }
set { this.UpdateValue(ref this.city, value); }
}
public string Street
{
get { return this.street; }
set { this.UpdateValue(ref this.street, value); }
}
}
 

In the sample both classes inherit from NotifyPropertyChangedBase class which basically
implements the INotifyPropertyChanged interface. You would need to add the following namespace
to use it:

C#
using Telerik.XamarinForms.Common;
 

Then create a ViewModel with a collection of Person objects:

C#
public class ViewModel
{
public ObservableCollection<Person> Persons { get; set; }

public ViewModel()
{
var source = new ObservableCollection<Person>();

source.Add(new Person() { Name = "Alejandro Gonzalez ", Age = 23, Address = new
Address() { City = "Madrid" } });
source.Add(new Person() { Name = "John Smith", Age = 31, Address = new
Address() { City = "London" } });
source.Add(new Person() { Name = "Emily Jakinson", Age = 42, Address = new
Address() { City = "New York" } });
source.Add(new Person() { Name = "Amelia Johnson", Age = 19, Address = new
Address() { City = "Bath" } });
source.Add(new Person() { Name = "Jack Connor", Age = 28, Address = new
Address() { City = "Oxford" } });
source.Add(new Person() { Name = "Thomas Ford", Age = 36, Address = new
Address() { City = "Atlanta" } });
source.Add(new Person() { Name = "James Williams", Age = 25, Address = new
Address() { City = "Houston" } });
source.Add(new Person() { Name = "Nikole Smith", Age = 38, Address = new
Address() { City = "Chicago" } });

this.Persons = source;

880
Telerik UI for Xamarin

}
}
 

Finally, use the following snippet to declare a RadDataGrid in XAML:

XAML
<telerikDataGrid:RadDataGrid Grid.Row="1" x:Name="grid"
ItemsSource="{Binding Persons}"
AutoGenerateColumns="False"
UserEditMode="Cell">
<telerikDataGrid:RadDataGrid.Columns>
<telerikDataGrid:DataGridTextColumn x:Name="nameColumn" PropertyName="Name"/>
<telerikDataGrid:DataGridNumericalColumn PropertyName="Age"/>
<telerikDataGrid:DataGridTextColumn PropertyName="Address.City"
HeaderText="City"/>
</telerikDataGrid:RadDataGrid.Columns>
</telerikDataGrid:RadDataGrid>
 

Where the telerikGrid namespace is the following:

xml
xmlns:telerikGrid="clr-namespace:Telerik.XamarinForms.DataGrid;assembly=Telerik.Xamari
nForms.DataGrid"
 

Here is how tha DataGrid looks:

881
Telerik UI for Xamarin

An example how to apply nested properties to RadDataGrid control can be found in the
DataGrid/NestedProperty folder of the SDK Samples Browser application.
 

See Also
 Picker Column
 Template Column
 Text Column

882
Telerik UI for Xamarin

Selection
RadDataGrid exposes a selection feature - users can select a cell or a row by tapping on it. To
cancel the selection, they can simply tap on the cell or a row again. The control provides single and
multiple selection.

This article explains the basic properties and methods that RadDataGrid provides for working with
selection.

Important Properties
RadDataGrid supports different selection modes that you can modify through the SelectionUnit and
SelectedItems properties. Before you can set the SelectionMode, you must choose which Unit can be
selected.

SelectionUnit
The SelectionUnit property (type of Telerik.XamarinForms.DataGrid.DataGridSelectionUnit) allows
you to control which Unit can be selected:

 Row: The unit to select is a grid row (by default).


 Cell: The unit to select is a cell within a grid row.

To define a Cell when using a selection, you can use the DataGridCellInfo class that holds all
the information about the Cell. To define a Row when using a selection, you can use your
data object.
 
The example below shows how to set SelectionUnit in XAML and code-behind:

XAML
<telerikDataGrid:RadDataGrid x:Name="dataGrid"
SelectionUnit="Cell" />
 

C#
var dataGrid = new RadDataGrid();
dataGrid.SelectionUnit = Telerik.XamarinForms.DataGrid.DataGridSelectionUnit.Cell;
 

SelectionMode
The SelectionMode property (type of Telerik.XamarinForms.DataGrid.DataGridSelectionMode)
provides the following modes:

 Single: Single unit may be selected(by default).


 Multiple: Multiple units may be selected.

883
Telerik UI for Xamarin

 None: No selection is allowed.

The example below shows how to set SelectionMode in XAML and code-behind:

XAML
<telerikDataGrid:RadDataGrid x:Name="dataGrid"
SelectionMode="Multiple" />
 

C#
var dataGrid = new RadDataGrid();
dataGrid.SelectionMode = Telerik.XamarinForms.DataGrid.DataGridSelectionMode.Multiple;
 

SelectedItems
Once you make a selection, you can get or modify the collection with the selected Items by using the
SelectedItems property:

 SelectedItems property (type of ObservableCollection<object>): Gets or Modifies an


ObservableCollection of the currently selected Items (their type depends on the applied
SelectionUnit, that is, DataGridCellInfo for Cell and Data Item for Row).

You can listen to the CollectionChanged event of the SelectedItems directly.


 

Events
 SelectionChanged: An event that is triggered whenever the SelectedItems collection is
changed. The SelectionChanged event handler receives two parameters:
 The sender argument, which is of type object, but can be cast to the RadDataGrid type.
 A DataGridSelectionChangedEventArgs object, which provides the following properties:
 RemovedItems - gets a list of the removed items from the SelectedItems collection.
 AddedItems - gets a list of the added items to the SelectedItems collection.

Methods
Additional functionalities for programmatic selecting and deselecting items are exposed by
RadDataGrid as methods. They also depend on the applied SelectionUnit.

Methods for programmatic selection when SelectionUnit is "Row":

 SelectItem(object item): Selects the specified data item and adds it in the SelectedItems
collection.
 DeselectItem(object item): Removes the selection for the specified data item and removes it
from the SelectedItems collection.

Methods for programmatic selection when SelectionUnit is "Cell":

884
Telerik UI for Xamarin

 SelectCell(DataGridCellInfo item): Selects the grid cell as defined by the specified cell info.
 DeselectCell(DataGridCellInfo item): Removes the selection for the grid cell defined by the
specified cell info.

Methods for programmatic selection of all items

 SelectAll(): Selects all the items as defined when SelectionMode is "Multiple".


 DeselectAll(): Clears the current selected items as defined by the SelectionUnit property.

Example
In order to illustrate how these methods can be used, let's have the following example:

1. Add a sample business object:

C#
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Department { get; set; }
}
 

2. Add a ViewModel with a list of "Person" objects:

C#
public class ViewModel
{
public ViewModel()
{
this.People = new ObservableCollection<Person>()
{
new Person { Name = "Kiko", Age = 23, Department = "Production" },
new Person { Name = "Jerry", Age = 23, Department = "Accounting and Finance"},
new Person { Name = "Ethan", Age = 51, Department = "Marketing" },
new Person { Name = "Isabella", Age = 25, Department = "Marketing" },
new Person { Name = "Joshua", Age = 45, Department = "Production" },
new Person { Name = "Logan", Age = 26, Department = "Production"},
new Person { Name = "Aaron", Age = 32, Department = "Production" },
new Person { Name = "Elena", Age = 37, Department = "Accounting and Finance"},
new Person { Name = "Ross", Age = 30, Department = "Marketing" },
};
}

public ObservableCollection<Person> People { get; set; }


}
 

3. Add the RadDataGrid definition:

885
Telerik UI for Xamarin

XAML
<telerikDataGrid:RadDataGrid x:Name="dataGrid"
ItemsSource="{Binding People}" />
 

4. Set the ViewModel class as a BindingContext:

C#
this.BindingContext = new ViewModel();
 

Now you use various approaches to select the first employee from the Marketing
department. Each snippet shows a possible approach:

 In the case of Row selection, use SelectItem method:

C#
var firstMarketingItem =
((ObservableCollection<Person>)this.dataGrid.ItemsSource).First(p => p.Department ==
"Marketing");
this.dataGrid.SelectItem(firstMarketingItem);
 

 For Cell selection, use SelectCell method - it takes as a parameter a DataGridCellInfo object.
DataGridCellInfo object can be easily created using the needed data item (of type Person in
our case) and setting the column corresponding to the cell you'd need to select.

C#
var firstMarketingCell =
((ObservableCollection<Person>)this.dataGrid.ItemsSource).First(p => p.Department ==
"Marketing");
this.dataGrid.SelectCell(new DataGridCellInfo(firstMarketingCell,
this.dataGrid.Columns[2]));
 

 Lastly, you call the SelectAll/DeselectAll method like this:

C#
this.dataGrid.SelectAll();
 

A sample Programmatic Selection example is available in the DataGrid => Selection


folder of the SDK Browser application.
 
You can directly explore the code in the SDKBrowser Examples repository on GitHub.

See Also
 DataGrid Sorting
 DataGrid Commands

886
Telerik UI for Xamarin

Editing
RadDataGrid provides a built-in editing functionality, which allows the app users to easily edit the
data presented in the grid. Depending on the column data type, a relevant editor allows end users to
edit content in a friendly environment. As soon as the user double-taps on a certain cell, the cell is
switched to an edit mode.

Important Properties
You would need to define the UserEditMode property of the DataGrid control in order to enable the
editing feature.

UserEditMode property is type of DataGridUserSortMode and accepts the following values:

 None: Editing is disabled (by default);


 Cell: Used to enable the editing option.

In addition, you can disable editing for concrete columns separately through the CanUserEdit
property of the DataGridColumn class. For more details on this check Columns Overview topic.

Columns' Editors
Each DataGrid column type provides different editor, so that the content could be edited in a
convenient manner according to its value type. Check below the related Xamarin.Forms control for
editing the values inside the DataGrid columns:

Column Type Editor


TextColumn Entry
NumericalColumn Entry
BooleanColumn Switch
DateColumn DatePicker
TimeColumn TimePicker
PickerColumn Picker
TemplateColumn custom editor by defining CellEditTemplate

CellEditTemplate
In case the default editors do not suit the scenario you have, you can easily create a custom editor
for each column by utilizing the CellEditTemplate property of the DataGridColumn. For detailed
information on how the CellEditTemplate can be applied, go to Columns Cell Templates.

887
Telerik UI for Xamarin

Editing Commands
RadDataGrid provides a few useful commands related to the editing functionality, such as:

 BeginEdit: Provides an entry point just before the editing begins.


 CancelEdit: Provides an entry point just before the editing is canceled.
 CommitEdit: Provides an entry point just before the editing is committed.

For detailed information on how to utilize any of the listed commands, go to Editing Commands topic.

Styling
You could change the visual appearance of each editor through the CellEditorStyle property of the
DataGridColumn. You would need to apply to CellEditorStyle a Xamarin.Forms.Style with
TargetType set to the corresponding to each column editor control.

Check below a quick snippet with CellEditorStyle applied to DataGridTextColumn:

XAML
<telerikGrid:DataGridTextColumn.CellEditorStyle>
<Style TargetType="Entry">
<Setter Property="FontSize" Value="Large"/>
<Setter Property="FontAttributes" Value="Bold"/>
</Style>
</telerikGrid:DataGridTextColumn.CellEditorStyle>
 

See Also
 Editing Commands
 Columns Cell Templates
 Columns Styling

888
Telerik UI for Xamarin

Grouping
RadDataGrid supports grouping operations either through the UI - Grouping UI or programmatically.

Programmatic Grouping
Programmatic grouping can be done by adding descriptors to the GroupDescriptors collection. There
are two types of descriptors:

 PropertyGroupDescriptor: use a property from the model as a group key.


 DelegateGroupDescriptor: create a custom group key which you can use.

All GroupDescriptors are located in the Telerik.XamarinForms.Common.Data namespace:

XAML
xmlns:telerikCommon="clr-namespace:Telerik.XamarinForms.Common.Data;assembly=Telerik.X
amarinForms.Common"
 

C#
using Telerik.XamarinForms.Common.Data;
 

Property Group Descriptor


The PropertyGroupDescriptor is used to group the data in a DataGrid by property from the class that
defines your objects.

To use the PropertyGroupDescriptor you have to set its property PropertyName.

 PropertyName (string): Gets or sets the name of the property that is used to retrieve the key
to group by.

You can easily sort the groups in ascending or descending order using the SortOrder property.
 
Let's, for example, have the following business object:

C#
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Department { get; set; }
}
 

889
Telerik UI for Xamarin

And a ViewModel class with a collection of Person objects:

C#
public class ViewModel
{
public ViewModel()
{
this.People = new ObservableCollection<Person>()
{
new Person { Name = "Kiko", Age = 23, Department = "Production" },
new Person { Name = "Jerry", Age = 23, Department = "Accounting and Finance"},
new Person { Name = "Ethan", Age = 51, Department = "Marketing" },
new Person { Name = "Isabella", Age = 25, Department = "Marketing" },
new Person { Name = "Joshua", Age = 45, Department = "Production" },
new Person { Name = "Logan", Age = 26, Department = "Production"},
new Person { Name = "Aaron", Age = 32, Department = "Production" },
new Person { Name = "Elena", Age = 37, Department = "Accounting and Finance"},
new Person { Name = "Ross", Age = 30, Department = "Marketing" },
};
}

public ObservableCollection<Person> People { get; set; }


}
 

Next snippet demonstrates how you could group the people by "Department" property through the
PropertyGroupDescriptor:

XAML
<telerikDataGrid:RadDataGrid x:Name="dataGrid"
ItemsSource="{Binding People}">
<telerikDataGrid:RadDataGrid.GroupDescriptors>
<telerikCommon:PropertyGroupDescriptor PropertyName="Department" />
</telerikDataGrid:RadDataGrid.GroupDescriptors>
</telerikDataGrid:RadDataGrid>
 

All that is left is to set the ViewModel as BindingContext of the page:

C#
this.BindingContext = new ViewModel();
 

Here is how the RadDataGrid looks when it is grouped:

890
Telerik UI for Xamarin

GroupHeaderTemplate
In addition, you can create custom GroupHeaderTemplate in order to achieve the desired look when
grouping the DataGrid. The BindingContext of the GroupHeader is a GroupHeaderContext object
and it includes the following properties:

 Descriptor: Specifies the used descriptor for the grouping;


 Group: Gets details on the group such as:
 Items: Gets the child items of the group.
 Key: Gets the specific for the group key.
 IsExpanded: Defines a value indicating whether the group is currently expanded (has its
child items visible).
 Level: Gets the zero-based level (or the depth) of the group.

The snippet below shows how the GroupHeaderTemplate is defined:

XAML
<telerikDataGrid:RadDataGrid x:Name="dataGrid"
ItemsSource="{Binding People}">

891
Telerik UI for Xamarin

<telerikDataGrid:RadDataGrid.GroupDescriptors>
<telerikCommon:PropertyGroupDescriptor PropertyName="Department"/>
</telerikDataGrid:RadDataGrid.GroupDescriptors>
<telerikDataGrid:RadDataGrid.GroupHeaderTemplate>
<DataTemplate>
<StackLayout Orientation="Horizontal"
Margin="5,0,0,0"
VerticalOptions="Center" >
<Label Text="Employees working in: "
TextColor="DarkBlue"
FontSize="Small" />
<Label Text="{Binding Group.Key}"
FontAttributes="Bold"
TextColor="DarkBlue"
FontSize="Small" />
</StackLayout>
</DataTemplate>
</telerikDataGrid:RadDataGrid.GroupHeaderTemplate>
</telerikDataGrid:RadDataGrid>
 

Check the result in the image below:

892
Telerik UI for Xamarin

Delegate Group Descriptor


The difference between the DelegateGroupDescriptor and the PropertyGroupDescriptor is that
DelegateGroupDescriptor groups data by a custom Key while the PropertyGroupDescriptor groups
by a defined Key which is a property from our model.

You have to set the following property of the DelegateGroupDescriptor:

 KeyLookup: Gets or sets the IKeyLookup instance that is used to retrieve the group key for
each data item.

You can easily sort the groups in ascending or descending order using the SortOrder property.
 
You have to create a class that implements the IKeyLookup interface which will return the Key you
want to group by. Then you need to add the DelegateGroupDescriptor to the
RadDataGrid.GroupDescriptors collection and set its KeyLookUp property.

Check below a sample IKeyLookup implementation:

893
Telerik UI for Xamarin

C#
class CustomIKeyLookup : Telerik.XamarinForms.Common.Data.IKeyLookup
{
public object GetKey(object instance)
{
var item = instance as Person;
return item?.Name[0];
}
}
 

Adding it to the GroupDescriptors collection of the RadDataGrid:

C#
this.dataGrid.GroupDescriptors.Add(new DelegateGroupDescriptor() { KeyLookup = new
CustomIKeyLookup() });
 

Here is how the RadDataGrid looks when it is grouped through a DelegateGroupDescriptor:

894
Telerik UI for Xamarin

Grouping UI
The Grouping UI is enabled by design and it allows user to group the data by column value. The
Grouping UI exposes the following property:

 UserGroupMode: Defines whether the Grouping UI is enabled/disabled. The available


options are Auto/Enabled/Disabled. The default value of the UserGroupMode is Auto.

The following property is used to enable/disable the grouping of a specific column:

 CanUserGroup (bool): Defines a value indicationg whether the user can filter the column by
ysing the Grouping UI.

A sample Grouping example can be found in the DataGrid/Grouping folder of the SDK Samples
Browser application.
 

Expand and Collapse Groups


RadDataGrid supports groups expand and collapse operations either through the UI by tapping on
the group headers or programmatically. By default, all the groups are expanded.

This help topic will provide an overview of the methods and commands used to control the
expand/collapse state of the DataGrid groups.

Get the grouped DataGrid items


To manipulate the collapsible DataGrid groups, first you will need to call its GetDataView method. In
short, GetDataView method provides a view of the ItemsSource after all the Sort, Group and Filter
operations are applied. The return type is IDataViewCollection which exposes the expand and
collapse methods described in the following sections.

C#
var dataView = this.dataGrid.GetDataView();
 

Expand and collapse all groups


In order to expand all groups, use the ExpandAll method and respectively use the CollapseAll
method - to collapse all groups.

C#
//expand all
var dataView = this.dataGrid.GetDataView();
dataView.ExpandAll();

//collapse all
var dataView = this.dataGrid.GetDataView();

895
Telerik UI for Xamarin

dataView.CollapseAll();
 

Expand and collapse a certain group


You could retrieve the first-level groups through the GetGroups method of the IDataViewCollection
object and use ExpandGroup/CollapseGroup to make a certain group to expand or collapse
respectively. You could check whether a group is expanded trough the GetIsExpanded method.

Here is quick snippet on how these methods are used:

C#
var dataView = this.dataGrid.GetDataView();
var rootGroups = dataView.GetGroups();

var isFirstExpanded = dataView.GetIsExpanded(rootGroups.First());


//expand a certain group
dataView.ExpandGroup(rootGroups.First());
//collapse a certain group
dataView.CollapseGroup(rootGroups.First());
 

Additionally, IDataViewCollection provides ExpandItem/CollapseItem methods that takes a data item


as a parameter and expand/collapse the immediate group containing this item.

C#
var lastItem = (dataGrid.ItemsSource as IEnumerable<City>).Last();
var dataView = this.dataGrid.GetDataView();
dataView.CollapseItem(lastItem);
 

See Also
 Filtering
 Sorting
 Selection

896
Telerik UI for Xamarin

Filtering
RadDataGrid supports both programmatic filtering and such applied through the UI - Filtering UI.

Programmatic Filtering
Programmatic filtering is achieved by adding different filter descriptors in the FilterDescriptor
collection of the control. The following descriptor types are supported:

 TextFilterDescriptor
 NumericalFilterDescriptor
 DateTimeFilterDescriptor
 BooleanFilterDescriptor
 CompositeFilterDescriptor
 DelegateFilterDescriptor

All FilterDescriptors are located in the Telerik.XamarinForms.Common.Data namespace:

XAML
xmlns:common="clr-namespace:Telerik.XamarinForms.Common.Data;assembly=Telerik.XamarinF
orms.Common"
 

Text Filter Descriptor


Properties:

 PropertyName: Gets or sets the name of the property that is used to retrieve the value to
filter by.
 Operator: Gets or sets the TextOperator value that defines how the Value member is
compared with each value from the items source.
 Value: Gets or sets the value used in the comparisons. This is the right operand of the
comparison.
 IsCaseSensitive: Gets or sets a value that determines whether the text comparisons will be
case-sensitive. Default value is true.

To use TextFilterDescriptor you need to add its instance to the RadDataGrid.FilterDescriptors


collection and to set its PropertyName property to associate it with the property from your custom
objects. Then through the Operator and Value properties you need to set the filter condition and the
value to compare. You can also take advantage of the IsCaseSensitive property to determine if the
text comparisons will be case-sensitive or not.

XAML
<common:TextFilterDescriptor PropertyName="Country"
Operator="StartsWith"
IsCaseSensitive="False"
Value="En"/>

897
Telerik UI for Xamarin

Numerical Filter Descriptor


Represents a Descriptor which filters by property of numerical data type. It exposes the following
properties.

 PropertyName: Gets or sets the name of the property that is used to retrieve the value to
filter by.
 Value: Gets or sets the value used in the comparisons. This is the right operand of the
comparison.
 Operator: Gets or sets the NumericalOperator value that defines the boolean logc behind the
left and right operand comparison.

XAML
<common:NumericalFilterDescriptor PropertyName="StadiumCapacity"
Operator="IsLessThan"
Value="80000"/>
 

DateTime Filter Descriptor


The DateTimeFilterDescriptor is a Descriptor which filters by property of System.DateTime data type.
It exposes the following properties:

 PropertyName: Gets or sets the name of the property that is used to retrieve the value to
filter by.
 Value: Gets or sets the value used in the comparisons. This is the right operand of the
comparison.
 Operator: Gets or sets the NumericalOperator value that defines the boolean logic behind
the left and right operand comparison.

XAML
<common:DateTimeFilterDescriptor PropertyName="Established"
Operator="IsLessThan"
Value="1900/01/01"/>
 

Boolean Filter Descriptor


The BooleanFilterDescriptor is a Descriptor which filters by property of System.Boolean data type. It
exposes the following properties:

 PropertyName: Gets or sets the name of the property that is used to retrieve the value to
filter by.
 Value: Gets or sets the value used in the comparisons. This is the right operand of the
comparison.

XAML

898
Telerik UI for Xamarin

<common:BooleanFilterDescriptor PropertyName="IsChampion"
Value="true"/>
 

Composite Filter Descriptor


The CompositeFilterDescriptor represents a special FilterDescriptorBase that stores an arbitrary
number of other Descriptors instances. The logical AND or OR operator is applied upon all
composed filters to determine the result of the PassesFilter routine.

XAML
<common:CompositeFilterDescriptor Operator="And">
<common:CompositeFilterDescriptor.Descriptors>
<common:NumericalFilterDescriptor PropertyName="StadiumCapacity"
Operator="IsGreaterThan"
Value="55000"/>
<common:NumericalFilterDescriptor PropertyName="StadiumCapacity"
Operator="IsLessThan"
Value="85000"/>
</common:CompositeFilterDescriptor.Descriptors>
</common:CompositeFilterDescriptor>
 

Delegate Filter Descriptor


The DelegateFilterDescriptor exposes the following property:

 Filter: Gets or sets the IFilter implementation used to check whether a data item passes the
filter or not.

To use a DelegateFilterDescriptor you need to create a class that implements the IFilter interface
which will return the Key you want to filter by.

Then you need to add a DelegateFilterDescriptor to the RadDataGrid.FilterDescriptors collection and


set its Filter property.

The CustomFilter implementation:

C#
class CustomFilter : IFilter
{
public bool PassesFilter(object item)
{
if ((item as Club).StadiumCapacity > 60000 && (item as Club).StadiumCapacity
<85000)
{
return true;
}
else
{

899
Telerik UI for Xamarin

return false;
}
}
}
 

Adding the DelegateFilterDescriptor to the RadDataGrid:

C#
grid.FilterDescriptors.Add(new DelegateFilterDescriptor() { Filter = new
CustomFilter()});
 

Filtering UI
The filtering component(Filtering UI) appears when clicking the options icon (OptionsButton, three
dots) on each column's header and it allows the user to easily filter data by column values.

OptionsButton opens the Filtering UI


The image below shows where the OptionsButton is placed

900
Telerik UI for Xamarin

Show/Hide OptionsButton

 IsOptionsButtonVisible (bool) property indicated whether the OptionsButton is visible.


The default value is true. The property could be set inside the
DataGridColumnHeaderStyle.

901
Telerik UI for Xamarin

Example

XAML
<telerikGrid:DataGridTextColumn.HeaderStyle>
<telerikGrid:DataGridColumnHeaderStyle BackgroundColor="LightSkyBlue"
IsOptionsButtonVisible="False"
TextColor="Black"
BorderColor="Black"
BorderThickness="2"/>
</telerikGrid:DataGridTextColumn.HeaderStyle>
 

Filtering UI
Here is how the Filtering UI looks:

902
Telerik UI for Xamarin

The Filtering UI exposes the following property:

 UserFilterMode: Defines whether the Filtering UI is enabled/disabled. The available options


are Auto/Enabled/Disabled. The default value of the UserFilterMode is Auto.

The following property is used to enable/disable the filtering of a specific column:

 CanUserFilter (bool): Defines a value indicating whether the user can filter the column by
using the Filtering UI.

The appearance of the Filtering UI can be customized by inheriting the DataGridFilterControlBase


class. For more details on this check How to customize Filtering UI article.

FilterControl Template
From R2 2020 DataGrid allows you to apply filtering to the datagrid column using the
FilterControlTemplate property.

 FilterControlTemplate(DataTemplate): Specifies the user defined template used for Filtering

903
Telerik UI for Xamarin

UI. The template must contain an instance of the


Telerik.XamarinForms.DataGrid.DataGridFilterControlBase class

Example using the TempateColumn


1. The first step is to create the custom Control which will inherit from the DataGridFilterControlBase
class:

XAML
<telerikDataGrid:DataGridFilterControlBase
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"

x:Class="SDKBrowser.Examples.DataGridControl.FilteringCategory.FilterTemplateExample.P
opulationFilter"

xmlns:telerikDataGrid="clr-namespace:Telerik.XamarinForms.DataGrid;assembly=Telerik.Xa
marinForms.DataGrid">
<StackLayout Margin="10"
Padding="10"
BackgroundColor="LightGray">
<Picker x:Name="descriptorOperatorPicker"
TextColor="Black" />
<Entry x:Name="textEntry" />
</StackLayout>
</telerikDataGrid:DataGridFilterControlBase>
 

C#
public partial class PopulationFilter : DataGridFilterControlBase
{
public PopulationFilter()
{
InitializeComponent();
}
public FilterDescriptorBase FilterDescriptor { get; set; }

public override FilterDescriptorBase BuildDescriptor()


{
TextFilterDescriptor textDescriptor = new TextFilterDescriptor();
textDescriptor.PropertyName = this.PropertyName;
textDescriptor.Value = this.textEntry.Text;
textDescriptor.Operator =
(TextOperator)this.descriptorOperatorPicker.SelectedItem;

return textDescriptor;
}

protected override void Initialize()


{

904
Telerik UI for Xamarin

this.descriptorOperatorPicker.ItemsSource = this.GetOperators();
var textFilterDescriptor = this.FilterDescriptor as TextFilterDescriptor;
if (textFilterDescriptor != null)
{
this.descriptorOperatorPicker.SelectedIndex =
(int)textFilterDescriptor.Operator;
this.textEntry.Text = textFilterDescriptor.Value.ToString();
}
else
{
this.descriptorOperatorPicker.SelectedIndex = 0;
if (!string.IsNullOrEmpty(this.textEntry.Text))
{
this.textEntry.Text = null;
}
}
}
private List<TextOperator> GetOperators()
{
var operators = new List<TextOperator>
{
TextOperator.Contains,
TextOperator.DoesNotContain,
TextOperator.StartsWith,
TextOperator.EndsWith,
};
return operators;
}
}
 

You should override the required methods as shown in the C# snippet above.

2. Use the FilterControlTemplate property to specify the already created component as a filtering
control to the template column.

XAML
<telerikDataGrid:RadDataGrid x:Name="dataGrid"
ItemsSource="{Binding GridSource}"
AutoGenerateColumns="False"
UserEditMode="Cell">
<telerikDataGrid:RadDataGrid.Columns>
<telerikDataGrid:DataGridNumericalColumn PropertyName="Population" />
<telerikDataGrid:DataGridTemplateColumn HeaderText="City">
<telerikDataGrid:DataGridTemplateColumn.CellContentTemplate>
<DataTemplate>
<Label Text="{Binding Name}"/>
</DataTemplate>
</telerikDataGrid:DataGridTemplateColumn.CellContentTemplate>
<telerikDataGrid:DataGridTemplateColumn.FilterControlTemplate>
<DataTemplate>
<local:PopulationFilter PropertyName="Name"/>
</DataTemplate>

905
Telerik UI for Xamarin

</telerikDataGrid:DataGridTemplateColumn.FilterControlTemplate>
</telerikDataGrid:DataGridTemplateColumn>
</telerikDataGrid:RadDataGrid.Columns>
</telerikDataGrid:RadDataGrid>
 

The ViewModel used in the example is declared as following:

C#
public class FilteringViewModel
{
public FilteringViewModel()
{
var source = new ObservableCollection<City>();
source.Add(new City("Vratsa", 54150));
source.Add(new City("Mexico City", 22000000));
source.Add(new City("Trieste", 204849));
source.Add(new City("Ottawa", 934243));
source.Add(new City("Caracas", 1943901));
source.Add(new City("Amsterdam", 851573));
source.Add(new City("Pittsburgh", 305704));
source.Add(new City("Athens", 664046));
source.Add(new City("Taipei", 2704974));
source.Add(new City("Marseille", 855393));
source.Add(new City("Pnom Penh", 1501725));

this.GridSource = source;

this.TextOperatorSource = Enum.GetValues(typeof(TextOperator));
this.NumericalOperatorSource = Enum.GetValues(typeof(NumericalOperator));
}

public ObservableCollection<City> GridSource { get; set; }


public IList TextOperatorSource { get; set; }
public IList NumericalOperatorSource { get; set; }
}
 

And the City custom object:

C#
public class City
{
public City(string name, int population)
{
this.Name = name;
this.Population = population;
}

public string Name { get; set; }


public int Population { get; set; }
}

906
Telerik UI for Xamarin

You can review the FilterTemplateColumn example that shows how to achieve the functionality in
the Examples/DataGrid/Filtering folder from the SDK Samples Browser application.
 

See Also
 Grouping
 Sorting
 Selection

907
Telerik UI for Xamarin

DataTable Support
With R1 2022 Release of Telerik UI for Xamarin, DataGrid fully supports binding to a DataTable.

All DataGrid features work with DataTable. You can add, remove, select, edit item(s) and update the
DataGrid's ItemsSource. In addition, all available commands and operations like filtering, sorting,
grouping, selection work when the DataGrid is bound to a DataTable.

Bind to DataTable
1. DataGrid definition:

XAML
<telerikDataGrid:RadDataGrid ItemsSource="{Binding Data}">
<telerikDataGrid:RadDataGrid.BindingContext>
<local:DataTableViewModel/>
</telerikDataGrid:RadDataGrid.BindingContext>
</telerikDataGrid:RadDataGrid>
 

2. Add the namespace:

XAML
xmlns:telerikDataGrid="clr-namespace:Telerik.XamarinForms.DataGrid;assembly=Telerik.Xa
marinForms.DataGrid"
 

3. The ViewModel used:

C#
public class DataTableViewModel : NotifyPropertyChangedBase
{
private DataTable data;

public DataTable Data


{
get { return this.data; }
set
{
this.UpdateValue(ref this.data, value);
}
}

public DataTableViewModel()
{
this.Data = this.GetData();
}

908
Telerik UI for Xamarin

private DataTable GetData()


{

DataTable country = new DataTable();


country.TableName = "Cities";
country.Columns.Add("Id", typeof(int));
country.Columns.Add("City", typeof(string));
country.Columns.Add("Population", typeof(int));
country.Columns.Add("Visited On", typeof(DateTime));
country.Columns.Add("IsVisited", typeof(bool));

country.Rows.Add(0, "Sofia", 2000000, new DateTime(2012, 10, 1), true);


country.Rows.Add(1, "New York", 8419000, null, false);
country.Rows.Add(2, "London", 8982000, new DateTime(2019, 02, 11), true);
country.Rows.Add(3, "Los Angeles", 3967000, null, false);
country.Rows.Add(3, "Budapest", 1765000, new DateTime(2013, 02, 1), true);
country.Rows.Add(3, "Tokyo", 9375104, new DateTime(2015, 09, 1), true);

return country;
}
}
 

Where the DataTable namespace is using System.Data;

A sample Bind to DataTable example can be found in the DataGrid/DataTable folder of the SDK
Samples Browser application.
 

Filtering, Sorting, Grouping


When using DataTable you can filter, group, sort the data inside the DataGrid through the UI or
programatically.

CRUD Operations with DataTable


All operations like add, remove, update data inside the DataGrid is supported when the Source is
from DataTable.

DataGrid definition:

XAML
<Grid RowDefinitions="Auto,*">
<telerikCommon:RadWrapLayout>
<Button Text="Add" Clicked="AddDataClicked"/>
<Button Text="Update 1st item" Clicked="UpdateDataClicked" />
<Button Text="Delete last item" Clicked="DeleteDataClicked"/>
</telerikCommon:RadWrapLayout>

<telerikDataGrid:RadDataGrid ItemsSource="{Binding Data}"

909
Telerik UI for Xamarin

x:Name="dataGrid"
SelectionMode="Single"
SelectionUnit="Cell"
SelectionChanged="RadDataGrid_SelectionChanged"
Grid.Row="1"/>
</Grid>
 

Add row
C#
private void AddDataClicked(object sender, EventArgs e)
{
this.viewModel.Data.Rows.Add(12, "Madrid", 3223000, null, false);
}
 

Delete row
C#
private void DeleteDataClicked(object sender, EventArgs e)
{
int rowCount = this.viewModel.Data.Rows.Count;
if (rowCount > 0)
{
this.viewModel.Data.Rows.RemoveAt(rowCount - 1);
}
}
 

Update data
C#
private void UpdateDataClicked(object sender, EventArgs e)
{
if (this.viewModel.Data.Rows.Count > 0)
{
this.viewModel.Data.Rows[0]["City"] = "Seoul";
this.viewModel.Data.Rows[0]["Population"] = 9776000;
}
}
 

SelectionChanged
C#
private void RadDataGrid_SelectionChanged(object sender,
Telerik.XamarinForms.DataGrid.DataGridSelectionChangedEventArgs e)
{
if (e.AddedItems.Count() > 0)

910
Telerik UI for Xamarin

{
var selectedItem = e.AddedItems.First() as DataGridCellInfo;
Application.Current.MainPage.DisplayAlert("You have selected",
$"{selectedItem.Value}", "OK");
}
}
 

A sample CRUD Operations example can be found in the DataGrid/DataTable folder of the SDK
Samples Browser application.
 

DataGrid Commands with DataTable


DataGrid definition:

XAML
<telerikDataGrid:RadDataGrid ItemsSource="{Binding Data}">
<telerikDataGrid:RadDataGrid.BindingContext>
<local:DataTableViewModel/>
</telerikDataGrid:RadDataGrid.BindingContext>
</telerikDataGrid:RadDataGrid>
 

CellTapUserCommand implementation:

C#
public class CellTapUserCommand : DataGridCommand
{
public CellTapUserCommand()
{
Id = DataGridCommandId.CellTap;
}
public override bool CanExecute(object parameter)
{
return true;
}
public override void Execute(object parameter)
{
var context = parameter as DataGridCellInfo;
var cellTap = $"You tapped on {context.Value} inside
{context.Column.HeaderText} column \n";
Application.Current.MainPage.DisplayAlert("CellTap Command: ", cellTap, "OK");
this.Owner.CommandService.ExecuteDefaultCommand(DataGridCommandId.CellTap,
parameter);
}
}
 

The ViewModel used:

911
Telerik UI for Xamarin

C#
public class DataTableViewModel : NotifyPropertyChangedBase
{
private DataTable data;

public DataTable Data


{
get { return this.data; }
set
{
this.UpdateValue(ref this.data, value);
}
}

public DataTableViewModel()
{
this.Data = this.GetData();
}

private DataTable GetData()


{

DataTable country = new DataTable();


country.TableName = "Cities";
country.Columns.Add("Id", typeof(int));
country.Columns.Add("City", typeof(string));
country.Columns.Add("Population", typeof(int));
country.Columns.Add("Visited On", typeof(DateTime));
country.Columns.Add("IsVisited", typeof(bool));

country.Rows.Add(0, "Sofia", 2000000, new DateTime(2012, 10, 1), true);


country.Rows.Add(1, "New York", 8419000, null, false);
country.Rows.Add(2, "London", 8982000, new DateTime(2019, 02, 11), true);
country.Rows.Add(3, "Los Angeles", 3967000, null, false);
country.Rows.Add(3, "Budapest", 1765000, new DateTime(2013, 02, 1), true);
country.Rows.Add(3, "Tokyo", 9375104, new DateTime(2015, 09, 1), true);

return country;
}
}
 

A sample Commands example can be found in the DataGrid/DataTable folder of the SDK Samples
Browser application.
 

See Also
 Filtering
 Grouping
 Selection

912
Telerik UI for Xamarin

Sorting
RadDataGrid provides you with a built-in sorting functionality, which allows the user to easily order
the view of the data the control represents. Sorting the control is possible both through the UI and
programmatically.

Programmatic Sorting
RadDataGrid provides two ways of programmatic sorting:

 by Property - using a PropertySortDescriptor


 by a Custom Key - using a DelegateSortDescriptor

Property Sort Descriptor


You can sort the data in a DataGrid by pointing a property from the class that defines your objects.
This can be achieved with a PropertySortDescriptor and setting its PropertyName property. The
descriptor exposes the following important properties:

 PropertyName: Gets or sets the name of the property that is used to retrieve the key to sort
by.
 SortOrder: Gets or sets the order of the sorting. It can be Ascending or Descending.

XAML
<telerikGrid:RadDataGrid.SortDescriptors>
<telerikCommon:PropertySortDescriptor PropertyName="Name"/>
</telerikGrid:RadDataGrid.SortDescriptors>
 

where the used namespaces are defined like this:

XAML
xmlns:telerikGrid="clr-namespace:Telerik.XamarinForms.DataGrid;assembly=Telerik.Xamari
nForms.DataGrid"
xmlns:telerikCommon="clr-namespace:Telerik.XamarinForms.Common.Data;assembly=Telerik.X
amarinForms.Common"
 

Delegate Sort Descriptor


The difference between the DelegateSortDescriptor and the PropertySortDescriptor is that
DelegateSortDescriptor sorts data by a custom Key, while the PropertySortDescriptor sorts by a
defined Key, which is a property from our model. It exposes the following properties:

 KeyLookup: Gets or sets the IKeyLookup instance that is used to retrieve the sort key for
each data item.
 SortOrder: Gets or sets the order of the sorting. It can be Ascending or Descending.

913
Telerik UI for Xamarin

To use a DelegateSortDescriptor, you need to create a class that implements the IKeyLookup
interface which will return the Key you want to sort by. Then you need to add DelegateSortDescriptor
to the RadDataGrid.SortDescriptors collection and set its KeyLookUp property.

The Custom IKeyLookup implementation

C#
public class CustomIKeyLookup : IKeyLookup
{
public object GetKey(object instance)
{
return (instance as Club).Name.Length;
}
}
 

Adding it to the GroupDescriptors collection of the RadDataGrid:

C#
this.grid.SortDescriptors.Add(new DelegateSortDescriptor() { KeyLookup = new
CustomIKeyLookup()});
 

Here is how the RadDataGrid looks when sorting is applied:

Sorting through the UI


RadDataGrid allows sorting through the UI by click/tap on the Column Header using the following

914
Telerik UI for Xamarin

property:

 UserSortMode : Defines how user input (column header tap/click) affects the current sort
state of the grid. The available options are: Auto/Multiple/None/Single. The default value of
the UserSortMode is Auto.

The following property is used to enable/disable the sorting of a specific column:

 CanUserSort (bool): Defines a value indicating whether the user can sort the data by the
values in the column.

A sample Sorting example can be found in the DataGrid/Sorting folder of the SDK Samples Browser
application.
 

See Also
 Filtering
 Grouping
 Selection

915
Telerik UI for Xamarin

Localization
RadDataGrid supports localization (the translation of application resources into localized versions for
the specific cultures or into customized resources). In order to apply the localization you need to
update the TelerikLocalizationManager.Manager by either creating a custom localization manager or
set its ResourceManager property.

Custom TelerikLocalizationManager
You should create a custom class that inherits from TelerikLocalizationManager and override the
GetString() method:

C#
public class CustomTelerikLocalizationManager : TelerikLocalizationManager
{
public override string GetString(string key)
{
if (key == "FilterText")
{
return "filtre";
}

if (key == "FilterUISectionText")
{
return "filtre par";
}

if (key == "Contains")
{
return "contient";
}

return base.GetString(key);
}
}
 

Eventually, you should set it as the TelerikLocalizationManager.Manager:

C#
TelerikLocalizationManager.Manager = new CustomTelerikLocalizationManager();

this.InitializeComponent();
 

You should set the custom manager before the InitializeComponent() method is invoked otherwise
the default values will be applied to the RadDataGrid.
 

916
Telerik UI for Xamarin

Figure 1 shows the appearance of the filtering component within the RadDataGrid after the custom
localization manager is applied.

Figure 1: Custom Localization Manager

Custom ResourceManager
The second option for applying localization is through setting a custom ResourceManager:

C#
TelerikLocalizationManager.Manager.ResourceManager = DataGridResource.ResourceManager;
this.InitializeComponent();
 

You should add different resource files according to the different languages/cultures which you
would like to use. Figure 2 shows an example of a custom resource file used for German:

Figure 2: Custom Resource File for German language

917
Telerik UI for Xamarin

The resource file ends with "de.resx" and is automatically used when the language of your device is
set to German.

Figure 3 shows the appearance of the filtering control when the localization is applied:

Figure 3: Custom Resource File for German language

You can check working localization examples in the DataGrid/Localization folder within the SDK
Browser application.

You can directly explore the code in the SDKBrowser Examples repository on GitHub.

918
Telerik UI for Xamarin

Localization Keys
Localization Key Default Value Related to
And And Filtering UI
Contains Contains Filter by option in Filtering UI
DoesNotContain Does not contain Filter by option in Filtering UI
DoesNotEqualTo Is not equal to Filter by option in Filtering UI
EndsWith Ends with Filter by option in Filtering UI
EqualsTo Is equal to Filter by option in Filtering UI
FilterText FILTER Filtering UI
FilterUISectionText Filter by: Filtering UI
FilterWatermarkText Enter Filter Criteria Filtering UI
GroupText Group Group option in Filtering UI
GroupUISectionText Group by: More options in Filtering UI
IsGreaterThan Is greater than Filter by option in Filtering UI
IsGreaterThanOrEqualTo Is greater than or equal to Filter by option in Filtering UI
IsLessThan Is less than Filter by option in Filtering UI
IsLessThanOrEqualTo Is less than or equal to Filter by option in Filtering UI
LoadOnDemandButtonText LOAD MORE Load on Demand feature
MoreText More More button in Filtering UI
OptionsSectionText Options: Filtering UI
Or Or Filtering UI
ReorderColumnsUISectionTe Visible Columns: More options in Filtering UI
xt
ResetText RESET Filtering UI
StartsWith Starts with Filter by option in Filtering UI
UngroupText Ungroup Reset grouping button in
Filtering UI

See Also
 Localization and Globalization
 Filtering
 Grouping

919
Telerik UI for Xamarin

 Customize the Filtering UI

920
Telerik UI for Xamarin

Load On Demand
In specific cases you may need to load data in the DataGrid when the control is already displayed as
this can improve the performance and save computing resources. Loading a large data set on a
mobile device has its challenges. One of the most popular approaches is using incremental data
loading in the moment the items need to be visualized.

Configuration
DataGrid offers two loading modes which are present in the LoadOnDemandMode enumeration:

 Automatic: The load-on-demand mechanism is activated when you scroll down near the last
item present in the view port.

You can control when the items will start loading more precisely by setting the
LoadOnDemandBufferItemsCount property. It indicates at what point the additional items will
start loading. For example, setting it to 20 will cause the new items to be loaded when you
have scrolled the RadDataGrid so that only 20 of the originally loaded items are left below.

 Manual: A "Load More" button is present at the bottom of the RadDataGrid. Clicking it will
load additional items based on the approach you have chosen for loading the items(through
the event, the command or the collection).

Methods to Load Data on Demand


There are three different options to load the data on demand, regardless of whether you use the
Automatic or Manual loading mode. You can choose the most convenient for you based on your
application requirements:

 Using the LoadOnDemand Collection


 Using the LoadOnDemand event
 Using the LoadMoreData Command

All three approaches for loading items on demand in ListView work with both Automatic and Manual
LoadOnDemandMode.
 

Using the LoadOnDemand Collection


In order to use this approach, you should feed the RadDataGrid with a collection of type
LoadOnDemandCollection. It is a generic type, so you need to point the type of objects it will contain.
It extends the ObservableCollection<T> class and expects a Func<CancellationToken,
IEnumerable> in the constructor.

Here is a simple setup that shows how to use the collection:

921
Telerik UI for Xamarin

1. Define a sample ViewModel class with Items property of type LoadOnDemandCollection:

C#
public class LoadOnDemandViewModel
{
public LoadOnDemandViewModel()
{
this.Items = new LoadOnDemandCollection<Person>((cancelationToken) =>
{
var list = new List<Person>();
for (int i = 0; i < 10; i++)
{
var person = new Person { Name = "LOD Person " + i, Age = i + 18, Gender = i %
2 == 0 ? Gender.Male : Gender.Female };
list.Add(person);
}
return list;
});

//set initial items


for (int i = 0; i < 20; i++)
{
var person = new Person { Name = "Person " + i, Age = i + 18, Gender = i % 2 ==
0 ? Gender.Male : Gender.Female };
this.Items.Add(person);
}
}

public LoadOnDemandCollection<Person> Items { get; set; }


}
 

2. Add the sample Person data item:

C#
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Gender Gender { get; set; }
}
 

3. Define RadDataGrid instance and bind its ItemsSource to the data in the ViewModel. Note
the approach will work with both Manual and Automatic loading modes.

XAML
<telerikGrid:RadDataGrid x:Name="dataGrid"
ItemsSource="{Binding Items}"
LoadOnDemandMode="Manual" />
 

922
Telerik UI for Xamarin

4. Set the ViewModel as BindingContext in the page constructor:

C#
this.BindingContext = new LoadOnDemandViewModel();
 

A sample LoadOnDemandCollection example is available in DataGrid -> LoadOnDemand


folder of the SDK Browser application.

You can directly explore the code in the SDK Samples Browser repository on GitHub.

Using LoadOnDemand Event


You can load new items by utilizing the LoadOnDemand event. It uses LoadOnDemandEventArgs
arguments through which you need to indicate when the data is loaded so that the event is correctly
fired afterwards.

The example below demonstrates how to use the LoadOnDemand event:

1. Define RadDataGrid instance with LoadOnDemand event assigned:

XAML
<telerikGrid:RadDataGrid x:Name="dataGrid"
LoadOnDemand="DataGrid_LoadOnDemand"
LoadOnDemandMode="Automatic"
LoadOnDemandBufferItemsCount="10" />
 

2. Set DataGrid ItemsSource in page constructor:

C#
var items = new ObservableCollection<Person>();
for (int i = 0; i < 20; i++)
{
var person = new Person { Name = "Person " + i, Age = i + 18, Gender = i % 2 == 0 ?
Gender.Male : Gender.Female };
items.Add(person);
}
this.dataGrid.ItemsSource = items;
 

3. Add the sample Person data item:

C#
public class Person
{
public string Name { get; set; }
public int Age { get; set; }

923
Telerik UI for Xamarin

public Gender Gender { get; set; }


}
 

4. Add the LoadOnDemand event handler:

C#
private void DataGrid_LoadOnDemand(object sender,
Telerik.XamarinForms.DataGrid.LoadOnDemandEventArgs e)
{
for (int i = 0; i < 15; i++)
{
((sender as RadDataGrid).ItemsSource as ObservableCollection<Person>).Add(new
Person() { Name = "Person " + i, Age = i + 18, Gender = i % 2 == 0 ? Gender.Male :
Gender.Female });
}
e.IsDataLoaded = true;
}
 

A sample LoadOnDemand Event example is available in DataGrid -> LoadOnDemandEvent


folder of the SDK Browser application.

You can directly explore the code in the SDK Samples Browser repository on GitHub.

Using LoadMoreData Command


The LoadMoreData command is another alternative which you can use which is suitable for MVVM
scenarios.

Check below an example on how to create a LoadMoreData command:

1. Add a CustomLoadMoreDataCommand class which inherits from DataGridCommand class


and set its Id to DataGridCommandId.LoadMoreData. Inside the Execute method add the
needed logic for loading the data.

C#
public class CustomLoadMoreDataCommand : DataGridCommand
{
public CustomLoadMoreDataCommand()
{
this.Id = DataGridCommandId.LoadMoreData;
}

public override bool CanExecute(object parameter)


{
return true;
}

924
Telerik UI for Xamarin

public async override void Execute(object parameter)


{
if (parameter == null)
{
return;
}

((LoadOnDemandContext)parameter).ShowLoadOnDemandLoadingIndicator();

await System.Threading.Tasks.Task.Delay(1500);
var viewModel = this.Owner.BindingContext as LoadMoreDataCommandViewModel;
if (viewModel != null)
{
for (int i = 0; i < 10; i++)
{
viewModel.Items.Add(new Person { Name = "Person " + i, Age = i + 18, Gender = i
% 2 == 0 ? Gender.Male : Gender.Female });
}
}
((LoadOnDemandContext)parameter).HideLoadOnDemandLoadingIndicator();
}
}
 

Invoking the ShowLoadOnDemandLoadingIndicator and


HideLoadOnDemandLoadingIndicators is a noteable part as without calling these methods
the BusyIndicator used for the functionality will not be visualized.
 

2. Add a sample ViewModel class in order to load initial data:

C#
public class LoadMoreDataCommandViewModel
{
public LoadMoreDataCommandViewModel()
{
this.Items = new ObservableCollection<Person>();

for (int i = 0; i < 20; i++)


{
var person = new Person { Name = "Person " + i, Age = i + 18, Gender = i % 2 ==
0 ? Gender.Male : Gender.Female };
this.Items.Add(person);
}
}

public ObservableCollection<Person> Items { get; set; }


}
 

3. Add the sample Person data item:

925
Telerik UI for Xamarin

C#
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Gender Gender { get; set; }
}
 

4. Define the RadDataGrid instance in XAML with the CustomLoadMoreDataCommand


command added to its Commands collection:

XAML
<telerikGrid:RadDataGrid x:Name="dataGrid"
ItemsSource="{Binding Items}"
LoadOnDemandMode="Automatic"
LoadOnDemandBufferItemsCount="10">
<telerikGrid:RadDataGrid.Commands>
<local:CustomLoadMoreDataCommand />
</telerikGrid:RadDataGrid.Commands>
</telerikGrid:RadDataGrid>
 

5. Set the ViewModel as BindingContext in the page constructor:

C#
this.BindingContext = new LoadMoreDataCommandViewModel();
 

A sample LoadOnDemand Event example is available in DataGrid ->


LoadMoreDataCommand folder of the SDK Browser application.

You can directly explore the code in the SDK Samples Browser repository on GitHub.

Styling
Besides the different approaches for loading the data, RadDataGrid exposes several mechanisms
related to the styling of the functionality which you can use according to the approach you have
chosen.

LoadOnDemandAutoTemplate
Setting this property will modify the appearance of the load on demand indicator when the
LoadOnDemandMode is Automatic.

Here is an example of custom DataTemplate:

926
Telerik UI for Xamarin

XAML
<DataTemplate x:Key="CustomLoadOnDemandAutoTemplate">
<Label HorizontalOptions="FillAndExpand"
VerticalOptions="CenterAndExpand"
Text="Auto Loading"
FontSize="25"
TextColor="Orange"
BackgroundColor="PaleTurquoise"
IsVisible="{Binding IsDataLoading}"/>
</DataTemplate>
 

And how you set it to the LoadOnDemandAutoTemplate property of the RadDataGrid:

XAML
<grid:RadDataGrid x:Name="dataGrid" ItemsSource="{Binding Items}"
LoadOnDemand="dataGrid_LoadOnDemand"
LoadOnDemandMode="Automatic"
LoadOnDemandAutoTemplate="{StaticResource CustomLoadOnDemandAutoTemplate}"
LoadOnDemandBufferItemsCount="{Binding Source={x:Reference slider},
Path=Value}"/>
 

Figure 1: The appearance of the row after setting the LoadOnDemandAutoTemplate

LoadOnDemandRowStyle
This property can be used to style the appearance of the row that contains the "Load More" button
when the LoadOnDemandMode is Manual.

927
Telerik UI for Xamarin

The custom style is of type DataGridLoadOnDemandRowStyle:

XAML
<telerikDataGrid:DataGridLoadOnDemandRowStyle
x:Key="CustomDataGridLoadOnDemandRowStyle"
BackgroundColor="LightYellow"
BorderColor="LightBlue"
IndicatorAnimationColor="Orange"
IndicatorAnimationType="Animation5"
HorizontalTextAlignment="Center"
VerticalTextAlignment="Center"
OverlayOpacity="0.5"
Text="Some Text"
TextFontSize="16"
TextColor="DarkGray"
TextFontFamily="Times New Roman"/>
 

And you should set it to the LoadOnDemandRowStyle property of the RadDataGrid:

XAML
<grid:RadDataGrid x:Name="dataGrid" ItemsSource="{Binding Items}"
LoadOnDemand="dataGrid_LoadOnDemand"
LoadOnDemandMode="Manual"
LoadOnDemandRowStyle="{StaticResource CustomDataGridLoadOnDemandRowStyle}"/>
 

Figure 2: The appearance of the row after setting the LoadOnDemandRowStyle

928
Telerik UI for Xamarin

LoadOnDemandRowTemplate
This property can be used to set the template of the row that contains the "Load More" button when
the LoadOnDemandMode is Manual.

Here is a custom DataTemplate:

XAML
<DataTemplate x:Key="CustomLoadOnDemandRowTemplate">
<Label Text="Load more from Template"
Margin="0,30,0,30"
HorizontalOptions="CenterAndExpand"
VerticalOptions="CenterAndExpand"
IsEnabled="{Binding IsDataLoading}">
<Label.Triggers>
<Trigger TargetType="Label"
Property="IsEnabled" Value="False">
<Setter Property="BackgroundColor" Value="LightBlue" />
</Trigger>
</Label.Triggers>
</Label>
</DataTemplate>
 

And how you set the property:

XAML
<grid:RadDataGrid x:Name="dataGrid" ItemsSource="{Binding Items}"
LoadOnDemand="dataGrid_LoadOnDemand"
LoadOnDemandMode="Manual"
LoadOnDemandRowTemplate="{StaticResource CustomLoadOnDemandRowTemplate}"/>
 

Figure 3: The appearance of the row after setting the LoadOnDemandRowTemplate

929
Telerik UI for Xamarin

See Also
 DataGrid Filtering
 DataGrid Grouping
 DataGrid Sorting

930
Telerik UI for Xamarin

Commands
The Command design-pattern is very important and widely used in the XAML and MVVM world.
RadDataGrid strictly follows these best practices and provides an intuitive and easy-to-use set of
APIs that allow different aspects of the RadDataGrid control’s behavior to be handled and/or
completely overridden.

RadDataGrid exposes a Commands collection that allows you to register custom commands with
each control’s instance through the RadDataGrid.Commands property:

 Commands: Gets the collection with all the custom commands registered with the
CommandService. Custom commands have higher priority than the built-in (default) ones.

Command Types
 DataGridCommand: All the default commands within RadDataGrid derive from the base
DataGridCommand. Think of this command as a UI-related command as it operates over the
RadDataGrid instance that owns the command.
 Id: The key that relates a command instance to a particular action/routine. This value is
used to associate a command with a known event within a RadDataGrid instance.
 Command: Gets or sets the generic ICommand implementation that may come from the
ViewModel.
 EnableDefaultCommand: Gets or sets a value indicating whether the default (built-in) UI
command associated with the specified Id will be executed. Default value is True.

DataGridCommandId Enumeration
All the predefined commands within a RadDataGrid instance are identified by a member of the
DataGridCommandId enumeration. This is actually the key that relates a command instance to a
particular action/routine within the owning grid. In order to register a custom command within a
RadDataGrid instance you may either inherit the DataGridCommand class and override its
CanExecute and Execute methods. You need to set the Id property of the new command so that it
can be properly associated with the desired action/event. Following are the members of the
DataGridCommandId enumerations:

The table below shows all commands in the RadDataGrid control and for each of the available
commands there is an object which is passed as a parameter in its Execute method.

Commands Object type


Unknown DataGridColumn
ColumnHeaderTap DataGridTextColumn
GroupHeaderTap GroupHeaderContext
GroupHeaderButtonTap GroupHeaderContext
CellTap DataGridCellInfo

931
Telerik UI for Xamarin

CellDoubleTap DataGridCellInfo
GenerateColumn GenerateColumnContext
DataBindingComplete DataBindingCompleteEventArgs
BeginEdit EditContext
CancelEdit EditContext
CommitEdit EditContext
ValidateCell ValidateCellContext
LoadMoreData LoadOnDemandContext
OptionsTap OptionsTapContext
ApplyFilter OptionsTapContext
CloseOptionsTap OptionsTapContext
ResetFilter OptionsTapContext
ApplyGrouping GroupDescriptorBase
MoreTap OptionsTapContext

See Also
 CellTap Command
 Editing Command
 Validation Command

932
Telerik UI for Xamarin

CellTap Command
The DataGrid CellTap Command handles the Tap gesture over a grid cell, that is, the intersection of
a data row and a column.

Example
Here is an example how the RadDataGrid CellTap Command works:

First, create the needed business objects, for example type Country with the following properties:

C#
public class Country
{
public Country(string name, double population)
{
this.Name = name;
this.Population = population;
}

public string Name { get; set; }


public double Population { get; set; }
}
 

Here is the simple data used as binding context:

C#
var source = new ObservableCollection<Country>();
source.Add(new Country("Mozambique", 24692000));
source.Add(new Country("Paraguay", 6725000));
source.Add(new Country("Turkmenistan", 5663000));
source.Add(new Country("Mongolia", 3027000));
source.Add(new Country("Japan", 127000000));
source.Add(new Country("Bulgaria", 7128000));
source.Add(new Country("Chad", 14450000));
source.Add(new Country("Netherlands", 17020000));

this.BindingContext = source;
 

Then handle the CellTap action as a Command. First, create a class that inherits from the
DataGridCommand and set its Id property accordingly.You would also need to override CanExecute
and Execute methods as demostrated in the example below:

C#
public class CellTapUserCommand : DataGridCommand
{

933
Telerik UI for Xamarin

public CellTapUserCommand()
{
Id = DataGridCommandId.CellTap;
}
public override bool CanExecute(object parameter)
{
return true;
}
public override void Execute(object parameter)
{
var context = parameter as DataGridCellInfo;
var cellTap = $"You tapped on {context.Value} inside
{context.Column.HeaderText} column \n";
Application.Current.MainPage.DisplayAlert("CellTap Command: ", cellTap, "OK");
this.Owner.CommandService.ExecuteDefaultCommand(DataGridCommandId.CellTap,
parameter);
}
}
 

Then add this Command to the Commands collection of the RadDataGrid instance:

C#
grid.Commands.Add(new CellTapUserCommand());
 

Define the RadDataGrid in XAML:

XAML
<grid:RadDataGrid x:Name="grid" ItemsSource="{Binding}"/>
 

SDK Samples Browser application contains an example that shows how to use the CellTap
Command. The Commands example is located in the DataGrid/Commands folder.
 

See Also
 Editing
 Validation

934
Telerik UI for Xamarin

Editing Commands
The RadDataGrid control provides the following commands for editing the data inside the column:

 BeginEdit: Provides an entry point just before the editing begins.


 CancelEdit: Provides an entry point just before the editing is canceled.
 CommitEdit: Provides an entry point just before the editing is committed.

The execution parameter of the Editing Commands is of type EditContext that exposes the following
properties:

 CellInfo: Gets the cell info associated with the operation.


 TriggerAction: Gets the SourceTriggerAction value that triggered the operation.
 Parameter: Gets an optional parameter holding additional information associated with the
operation.

BeginEdit and CommitEdit Commands Example


Here is an example how the RadDataGrid Editing Commands work:

First, create the needed business objects, for example type Data with the following properties:

C#
public class Data
{
public string Country { get; set; }

public string Capital { get; set; }


}
 

Then create a ViewModel with a collection of Data objects:

C#
public class ViewModel
{
public ObservableCollection<Data> Items { get; set; }

public ViewModel()
{
this.Items = new ObservableCollection<Data>()
{
new Data { Country = "India", Capital = "New Delhi"},
new Data { Country = "South Africa", Capital = "Cape Town"},
new Data { Country = "Nigeria", Capital = "Abuja" },
new Data { Country = "Singapore", Capital = "Singapore" }
};
}

935
Telerik UI for Xamarin

}
 

Then handle the BeginEdit action as a Command. First, create a class that inherits from the
DataGridCommand and set its Id property accordingly.You would also need to override CanExecute
and Execute methods as demostrated in the example below:

C#
public class BeginEditCommand : DataGridCommand
{
public BeginEditCommand()
{
this.Id = DataGridCommandId.BeginEdit;
}

public override void Execute(object parameter)


{
var context = (EditContext)parameter;
var cellEdit = $"BeginEdit on: {context.CellInfo.Value} via
{context.TriggerAction} \n";
Application.Current.MainPage.DisplayAlert("", "" + cellEdit, "OK");
this.Owner.CommandService.ExecuteDefaultCommand(DataGridCommandId.BeginEdit,
parameter);
}
}
 

Then handle the CommitEdit action as a Command. First, create a class that inherits from the
DataGridCommand and set its Id property accordingly.You would also need to override CanExecute
and Execute methods as demostrated in the example below:

C#
public class CommitEditCommand : DataGridCommand
{
public CommitEditCommand()
{
this.Id = DataGridCommandId.CommitEdit;
}

public override void Execute(object parameter)


{
var context = (EditContext)parameter;

Application.Current.MainPage.DisplayAlert("", "Edit Committed", "OK");


this.Owner.CommandService.ExecuteDefaultCommand(DataGridCommandId.CommitEdit,
parameter);
}
}
 

Then add this Commands to the Commands collection of the RadDataGrid instance:

936
Telerik UI for Xamarin

C#
this.BindingContext = new ViewModel();
dataGrid.Commands.Add(new BeginEditCommand());
dataGrid.Commands.Add(new CommitEditCommand());
 

Define the RadDataGrid in XAML:

XAML
<telerikDataGrid:RadDataGrid x:Name="dataGrid"
ItemsSource="{Binding Items}"
UserEditMode="Cell"/>
 

SDK Samples Browser application contains an example that shows how to use the BeginEdit
Command. The Editing example is located in the DataGrid/Commands folder.
 

See Also
 Validation
 DataGrid Styling
 Columns Styling

937
Telerik UI for Xamarin

Validation Command
The RadDataGrid control provides a validation command that has an entry point for validating cells
content. The execution parameter is of type ValidateCellContext that exposes the following
properties:

 CellInfo: Gets the cell info associated with the operation.


 Errors: Gets or sets the errors (if any) that occurred during the validation.

Example
Here is an example how the RadDataGrid ValidateCell Command works:

First, create class Data (our business object) that inherits from the INotifyDataErrorInfo and
INotifyPropertyChanged interfaces.

We are going to do the validation through the INotifyDataErrorInfo interface.


 
C#
public class Data : INotifyDataErrorInfo, INotifyPropertyChanged
{
private Dictionary<string, HashSet<object>> errors = new Dictionary<string,
HashSet<object>>();
private string country;

public string Country


{
get
{
return this.country;
}

set
{
this.country = value;

if (this.country.Length > 15)


{
this.AddError("Country", string.Format("Country too long", new DateTime()));
}
else
{
this.RemoveErrors("Country");
}

this.OnPropertyChanged("Country");
}
}

938
Telerik UI for Xamarin

public string Capital { get; set; }

public bool HasErrors


{
get
{
return this.errors.Count > 0;
}
}

public IEnumerable GetErrors(string propertyName)


{
if (string.IsNullOrEmpty(propertyName))
{
return this.errors.SelectMany(c => c.Value);
}

HashSet<object> propertyErrors;

this.errors.TryGetValue(propertyName, out propertyErrors);

return propertyErrors ?? Enumerable.Empty<object>();


}

protected virtual void AddError(string propertyName, object errorMessage)


{
HashSet<object> propertyErrors;

if (!this.errors.TryGetValue(propertyName, out propertyErrors))


{
propertyErrors = new HashSet<object>();
this.errors.Add(propertyName, propertyErrors);

propertyErrors.Add(errorMessage);

this.OnErrorsChanged(propertyName);
}
else
{
if (!propertyErrors.Contains(errorMessage))
{
propertyErrors.Add(errorMessage);
this.OnErrorsChanged(propertyName);
}
}
}

protected virtual void RemoveErrors(string propertyName = null)


{
if (string.IsNullOrEmpty(propertyName))
{
if (this.errors.Count > 0)
{
this.errors.Clear();

939
Telerik UI for Xamarin

this.OnErrorsChanged(propertyName);
}
}
else
{
if (this.errors.Remove(propertyName))
{
this.OnErrorsChanged(propertyName);
}
}
}

public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;

protected virtual void OnErrorsChanged(string propertyName)


{
if (this.ErrorsChanged != null)
{
this.ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
}
}

public event PropertyChangedEventHandler PropertyChanged;

protected void OnPropertyChanged(string name)


{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
 

Then create a ViewModel with a collection of Data objects:

C#
public class ViewModel : INotifyPropertyChanged
{
public ObservableCollection<Data> Items { get; set; }
public ViewModel()
{
this.Items = new ObservableCollection<Data>()
{
new Data { Country = "India", Capital = "New Delhi"},
new Data { Country = "South Africa", Capital = "Cape Town"},
new Data { Country = "Nigeria", Capital = "Abuja" },
new Data { Country = "Singapore", Capital = "Singapore" }
};
}

public event PropertyChangedEventHandler PropertyChanged;

940
Telerik UI for Xamarin

protected void OnPropertyChanged(string name)


{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
 

Then handle the CellTap action as a Command. First, create a class that inherits from the
DataGridCommand and set its Id property accordingly.You would also need to override CanExecute
and Execute methods as demostrated in the example below:

C#
public class ValidateCellCommand : DataGridCommand
{
Grid grid;
public ValidateCellCommand(Grid grid)
{
this.Id = DataGridCommandId.ValidateCell;
this.grid = grid;
}

public override void Execute(object parameter)


{
var context = (ValidateCellContext)parameter;
this.grid.IsVisible = context.Errors.Count > 0;
}
}
 

Then set the BindingContext to be the ViewModel and add this Command to the Commands
collection of the RadDataGrid instance:

C#
this.BindingContext = new ViewModel();
this.dataGrid.Commands.Add(new ValidateCellCommand(errorContainer));
 

Define the RadDataGrid in XAML:

XAML
<Grid Margin="0,20,0,0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid x:Name="errorContainer"

941
Telerik UI for Xamarin

IsVisible="false">
<BoxView BackgroundColor="DarkRed" />
<Label Text="country name length must be less than 15 symbols"
FontSize="15"
HorizontalOptions="CenterAndExpand"
VerticalOptions="CenterAndExpand"
HorizontalTextAlignment="Center"
TextColor="White"/>
</Grid>

<telerikDataGrid:RadDataGrid x:Name="dataGrid"
Grid.Row="1"
UserEditMode="Cell"
AutoGenerateColumns="True"
ItemsSource="{Binding Items}">
</telerikDataGrid:RadDataGrid>
</Grid>
 

SDK Samples Browser application contains an example that shows how to use the ValidateCell
Command. The Validation example is located in the DataGrid/Commands folder.
 

See Also
 CellTap Command
 Editing Command
 Columns Styling

942
Telerik UI for Xamarin

DataGrid Styling
RadDataGrid control provides the following Style properties for customizing its look & feel:

 RowBackgroundStyle: Defines the style of each row.


 AlternateRowBackgroundStyle: Defines the appearance style of an alternate row.
 GroupHeaderStyle: Defines the appearance style of the group header once the data grid is
grouped.
 SelectionStyle: Defines the appearance setting applied to the DataGrid selected row.

Styling Properties
RowBackgroundStyle, AlternateRowBackgroundStyle and SelectionStyle are from type
DataGridBorderStyle that defines the appearance setting applied to a BorderPaintable instance and
exposes the following properties: BackgroundColor, BorderColor, BorderTickness.

Here is an example how to set the RowBackgroundStyle property:

XAML
<telerikGrid:RadDataGrid.RowBackgroundStyle>
<telerikGrid:DataGridBorderStyle BackgroundColor="CadetBlue"
BorderColor="DarkOrchid"
BorderThickness="1"/>
</telerikGrid:RadDataGrid.RowBackgroundStyle>
 

An example how to set the AlternateRowBackgroundStyle is shown below:

XAML
<telerikGrid:RadDataGrid.AlternateRowBackgroundStyle>
<telerikGrid:DataGridBorderStyle BackgroundColor="LightBlue"
BorderThickness="1"
BorderColor="BlanchedAlmond"/>
</telerikGrid:RadDataGrid.AlternateRowBackgroundStyle>
 

The SelectionStyle property could be set as shown below:

XAML
<telerikGrid:RadDataGrid.SelectionStyle>
<telerikGrid:DataGridBorderStyle BackgroundColor="SeaGreen"
BorderColor="Wheat"
BorderThickness="2"/>
</telerikGrid:RadDataGrid.SelectionStyle>
 

GoupHeaderStyle property is applied once the DataGrid is grouped. The following properties can be

943
Telerik UI for Xamarin

used for customizing the grouped DataGrid:

 BackgroundColor: Defines the color that fills the area within the header of the DataGrid’s
GroupHeader.
 BorderColor: Defines the that fills the border region of the GroupHeader
 BorderThickness: Defines the thickness of the border.
 Button Font Options (ButtonFontAttributes, ButtonFontFamily, ButtonFontSize): Define the
font options of the GroupedHeader expand/collapse symbol.
 ButtonMargin: Defines the margin of the expand/collapse symbol of the GroupHeader.
 ButtonTextColor: Defines the text color of the expand/collapse symbol of the GroupHeader.
 CollapseButtonText: Defines the text for the collapse state of the GroupHeader.
 ExpandButtonText: Defines the text for the expand state of the GroupHeader.
 Text Alignment (TextMargin, VerticalTextAlignment, HorizontalTextAlignment): Define the
positioning for the text part of the GroupHeader.
 Text Font Options (TextFontattributes, TextFontFamily, TextFontSize): Define the font
options of the GroupHeaders text part.

Please note that once the group is applied to the DataGrid the GroupHeader will appear. Also, by
default the Button of the GroupHeader uses an internal symbol font family. In order to show text
when the button is expanded/collapsed instead of symbol set a font family to the ButtonFontFamily
property and set a text to the ExpandButtonText and CollapseButtonText properties. For more
details on the group feature refer here.
 
Here is an example how to apply the GoupHeaderStyle property to the RadDataGrid control:

XAML
<telerikGrid:RadDataGrid.GroupHeaderStyle>
<telerikGrid:DataGridGroupHeaderStyle BorderThickness="1"
TextColor="DarkTurquoise"
BorderColor="Brown"/>
</telerikGrid:RadDataGrid.GroupHeaderStyle>
 

Here is how the RadDataGrid looks:

944
Telerik UI for Xamarin

SDK Samples Browser application contains DataGridStyling example in the DataGrid/Styling folder.
 

See Also
 Columns Styling
 Style Selectors
 How To

945
Telerik UI for Xamarin

Columns Styling
RadDataGrid component provides styling mechanism for customizing the look of the columns and
their cells.

The styling mechanism is represented by the following properties:

 HeaderStyle (DataGridColumnHeaderStyle)
 CellContentStyle (DataGridTypedColumn)
 CellDecorationStyle (DataGridBorderStyle)
 CellEditorStyle (DataGridTypedColumn)

HeaderStyle
HeaderStyle defines the appearance of the column header. The DataGridColumnHeaderStyle
exposes properties for styling its header, filter indicator, indicator, options button, sorting indicator.

Header Styling
To style the RadDataGridColumnHeader use the following properties:

 TextColor and BackgroundColor: Define the colors of the text part/background respectively.
 BorderColor and BorderThickness: Define the style of the border around the column header.
 Font Options (TextFontAttributes, TextFontFamily, TextFontSize): Define the font options to
the text part of the ColumnHeader.
 Text Alignment (TextMargin, HorizontalTextAlignment, VerticalTextAlignment): Define the
positioning for the text part of the ColumnHeader.

FilterIndicator Styling
Use the following properties for styling the FilterIndicator of the ColumnsHeader.

 FilterIndicator Font Options (FilterIndicatorFontAttributes, FilterIndicatorFontFamily,


FilterIndicatorFontSize): Define the font options for the ColumnHeader filter symbol.
 FilterIndicatorMargin: Defines the margin of the filter symbol of the ColumnHeader.
 FilterIndicatorText: Defines the text for the filter symbol of the ColumnHeader.
 FilterIndicatorTextColor: Defines the color of the normal state of the filter symbol.

Please note that once the filter operation is applied, the filter indicator will be visible in the
ColumnHeader cell. Also, by default the FilterIndicator is using an internal symbol font family. To
show text instead of symbol, set a font family to the FilterIndicatorFontFamily property and set a text
to the FilterIndicatorText property. For more details on the filtering feature go here.
 

SortIndicator Styling

946
Telerik UI for Xamarin

The Indicator is shown once the RadDataGridColumnHeader is sorted (tapped/clicked on the


ColumnHeader cell) and can be styled with the following properties:

 IndicatorColor: Defines the color for the indicator part of the ColumnHeader.
 Indicator Font Options (IndicatorFontAttributes, IndicatoFontFamily, IndicatoFontSize):
Define the font options for the ColumnHeader indicator.
 IndicatorMargin: Defines the margin of the indicator part of the ColumnHeader.
 IndicatorText: Defines the text of the indicator part of the ColumnHeader.
 SortIndicatorAscendingText: Defines the text of the sort indicator when the sorting is
ascending.
 SortIndicatorDescendingText: Defines the text of the sort indicator when the sorting is
descending.

By default, the indicator is represented by a string symbol that could be changed using IndicatorText
and IndicatorFontFamily properties. For more details on the sorting feature check here.
 

OptionsButton Styling
The OptionsButton of the RadDataGridColumnHeader refers to the FilteringUI of the DataGrid. Using
the OptionsButton you can open the Filtering UI control.

The style of the options button can be customized using the following properties:

 OptonsButton Font Options (OptonsButtonFontAttributes, OptionsButtonFontFamily,


OptionsButtonFontSize): Define the font options for the ColumHeaders options button,
 OptionsButtonMargin: Defines the margin of the ColumnsHeader options button
 OptionsButtonText: Defines the text of the ColumnHeaders options button.
 OptionsButtonTextColor: Defines the text color of the ColumnHeaders options button.

In order to change the OptionsButton visibility you can set the IsOptionsButtonVisible bool
property. By default its value is True which means that the OptionsButton is visible by default.
 

947
Telerik UI for Xamarin

XAML
<telerikGrid:DataGridTextColumn.HeaderStyle>
<telerikGrid:DataGridColumnHeaderStyle IsOptionsButtonVisible="False"
TextColor="Black"
BorderColor="Black"
BorderThickness="2"/>
</telerikGrid:DataGridTextColumn.HeaderStyle>
 

By default the options button is represented by a string symbol that could be changed through
OptionsButtonText and OptionsButtonFontFamily properties.
 
An example how to set the HeaderStyle property is shown below:

XAML
<telerikGrid:DataGridTextColumn.HeaderStyle>
<telerikGrid:DataGridColumnHeaderStyle BackgroundColor="LightSkyBlue"
TextColor="Black"
BorderColor="Black"
BorderThickness="2"/>

948
Telerik UI for Xamarin

</telerikGrid:DataGridTextColumn.HeaderStyle>
 

CellContentStyle
CellContentStyle property defines the appearance of each cell associated with the column. The
target type of the Style object depends on the type of the column. For example, for
DataGridTextColumn it will be TextBlock type. You could go to Column Types section (Text Column,
for example) to check the TargetType of each column type. The following properties can be used to
define the style of the text cell elements:

 Font Options (FontAttributes, FontFamily, FontSize): Define the font of the cell text.
 TextColor/SelectedTextColor: Defines the color of the cells text, you could set different value
for the selected cell.
 Text Alignment (TextMargin, HorizontalTextAlignment, VerticalTextAlignment): Define the
positioning of the Text inside the cell.

The CellContentStyle does not apply for TemplateColumn. Also, the property is not applied to
the built-in colums when CellContentTemplate is used.
 
Here is an example how to set the CellContentStyle property:

XAML
<telerikGrid:DataGridTextColumn.CellContentStyle>
<telerikGrid:DataGridTextCellStyle TextColor="DarkOliveGreen"
FontSize="12"
TextMargin="2"
VerticalTextAlignment="Center"
HorizontalTextAlignment="Center"
SelectedTextColor="Brown">
</telerikGrid:DataGridTextCellStyle>
</telerikGrid:DataGridTextColumn.CellContentStyle>
 

CellDecorationStyle
To style the border of each cell associated with the column the CellDecorationStyle property is used.
CellDecorationStyle is of type DataGridBorderStyle which provides the following properties:
BackgroundColor, BorderColor, BorderTickness.

Here is an example how to set those properties on a column:

XAML
<telerikGrid:DataGridTextColumn.CellDecorationStyle>
<telerikGrid:DataGridBorderStyle BorderColor="DarkBlue"
BorderThickness="3"
BackgroundColor="LightBlue" />
</telerikGrid:DataGridTextColumn.CellDecorationStyle>
 

949
Telerik UI for Xamarin

CellEditorStyle
CellEditorStyle defines the style that will be applied to the cell editor.

Here is an example how to set this property:

XAML
<telerikGrid:DataGridTextColumn.CellEditorStyle>
<Style TargetType="Entry">
<Setter Property="FontSize" Value="Large"/>
<Setter Property="FontAttributes" Value="Bold"/>
</Style>
</telerikGrid:DataGridTextColumn.CellEditorStyle>
 

And this is how the column style looks when the properties are applied for customizing the column
are applied:

SDK Samples Browser application contains Columns Styling example in the DataGrid/Styling folder.
 

See Also
 DataGrid Styling
 Style Selectors
 How To

950
Telerik UI for Xamarin

Style Selectors
RadDataGrid component exposes conditional styling feature. It allows users to apply different Style
on a cell or per group header depending on a specific condition.

You could set different style on a specific cell from a specific column based on a custom selection
logic with the following properties:

 CellContentStyleSelector: Style the content of the cell using the text alignment options
(TextMargin, HorizontalTextAlignment, VerticalTextAlignment), font options (FontAttributes,
FontFamily, FontSize) and TextColor property
 CellDecorationStyleSelector: Style the decoration on a cell

Different style can be applied on a per group header once the RadDataGrid control is grouped using
GroupHeaderStyleSelector property.

The CellContentStyleSelector, CellDecorationStyleSelector and GroupStyleSelector use the


SelectStyle method to change the style.

Example
The following example will demonstrate how to apply the style selectors in the RadDataGrid control:

Let’s add the RadDataGrid control and set the CellContentStyleSelector to be static resource from
type MyCellContentStyleSelector, CellDecorationStyleSelector as a static resource from type
MyCellDecorationStyleSelector and GroupStyleSelector as a static resource from type
MyGroupStyleSelector.

Here is an example:

XAML
<telerikGrid:RadDataGrid x:Name="datagrid"
AutoGenerateColumns="False"
IsVisible="True"
GroupHeaderStyleSelector="{StaticResource MyGroupSelector}"
UserEditMode="Cell">
<telerikGrid:RadDataGrid.Columns>
<telerikGrid:DataGridTextColumn PropertyName="Country" />
<telerikGrid:DataGridTextColumn PropertyName="Capital"
CellContentStyleSelector="{StaticResource MyCellContentStyleSelector}"
CellDecorationStyleSelector="{StaticResource MyCellDecorationSelector}">
</telerikGrid:DataGridTextColumn>
</telerikGrid:RadDataGrid.Columns>
</telerikGrid:RadDataGrid>
 

and let’s create a simple data for the RadDataGrid control:

951
Telerik UI for Xamarin

C#
public class Data
{
public Data(string country, string capital)
{
this.Country = country;
this.Capital = capital;
}
public string Country { get; set; }
public string Capital { get; set; }
}
 

C#
var source = new ObservableCollection<Data>();
source.Add(new Data("India", "New Delhi"));
source.Add(new Data("South Africa", "Cape Town"));
source.Add(new Data("Nigeria", "Abuja"));
source.Add(new Data("Singapore", "Singapore"));
source.Add(new Data("Romania", "Bucharest"));
source.Add(new Data("Spain", "Madrid"));
source.Add(new Data("France", "Paris"));
source.Add(new Data("Japan", "Tokyo"));

datagrid.ItemsSource = source;
 

As a next step you need to add MyCellContentStyleSelector, MyCellDecorationStyleSelector and


MyGroupStyleSelector as resources in the Resource page of the app:

XAML
<local:MyGroupSelector x:Key="MyGroupSelector">
<local:MyGroupSelector.CountryTemplate1>
<telerikGrid:DataGridGroupHeaderStyle BackgroundColor="LightYellow"
TextColor="Black"/>
</local:MyGroupSelector.CountryTemplate1>
<local:MyGroupSelector.CountryTemplate2>
<telerikGrid:DataGridGroupHeaderStyle BackgroundColor="LightSkyBlue"
TextColor="Red"/>
</local:MyGroupSelector.CountryTemplate2>
</local:MyGroupSelector>

<local:MyCellContentSelector x:Key="MyCellContentStyleSelector">
<local:MyCellContentSelector.CellTemplate1>
<telerikGrid:DataGridTextCellStyle TextColor="DarkOliveGreen"/>
</local:MyCellContentSelector.CellTemplate1>
<local:MyCellContentSelector.CellTemplate2>
<telerikGrid:DataGridTextCellStyle TextColor="DarkRed"/>
</local:MyCellContentSelector.CellTemplate2>
</local:MyCellContentSelector>

<local:MyCellDecorationSelector x:Key="MyCellDecorationSelector">

952
Telerik UI for Xamarin

<local:MyCellDecorationSelector.CellTemplate1>
<telerikGrid:DataGridBorderStyle BackgroundColor="LightBlue"/>
</local:MyCellDecorationSelector.CellTemplate1>
<local:MyCellDecorationSelector.CellTemplate2>
<telerikGrid:DataGridBorderStyle BackgroundColor="CadetBlue"/>
</local:MyCellDecorationSelector.CellTemplate2>
</local:MyCellDecorationSelector>
 

Let’s create a custom class for each selector and this class derives from DataGridStyleSelector and
overrides its SelectStyle method

MyCellContentStyleSelector class implementation is as follow:

C#
class MyCellContentSelector : DataGridStyleSelector
{
public DataGridStyle CellTemplate1 { get; set; }
public DataGridStyle CellTemplate2 { get; set; }
public override DataGridStyle SelectStyle(object item, BindableObject container)
{
DataGridCellInfo cellInfo = item as DataGridCellInfo;
if (cellInfo != null)
{
if ((cellInfo.Item as Data).Capital == "Singapore")
{
return CellTemplate1;
}
else
{
return CellTemplate2;
}
}
return base.SelectStyle(item, container);
}
}
 

MyCellDecorationStyleSelector class implementation is shown below:

C#
class MyCellDecorationSelector : DataGridStyleSelector
{
public DataGridStyle CellTemplate1 { get; set; }
public DataGridStyle CellTemplate2 { get; set; }
public override DataGridStyle SelectStyle(object item, BindableObject container)
{
DataGridCellInfo cellInfo = item as DataGridCellInfo;
if (cellInfo != null)
{
if ((cellInfo.Item as Data).Capital == "Singapore")
{

953
Telerik UI for Xamarin

return CellTemplate1;
}
else
{
return CellTemplate2;
}
}
return base.SelectStyle(item, container);
}
}
 

MyGroupStyleSelector could be implemented as follow:

C#
class MyGroupSelector : DataGridStyleSelector
{
public DataGridStyle CountryTemplate1 { get; set; }
public DataGridStyle CountryTemplate2 { get; set; }
public override DataGridStyle SelectStyle(object item, BindableObject container)
{
GroupHeaderContext header = item as GroupHeaderContext;
if (header != null)
{
if (header.Group.Key == "India")
{
return CountryTemplate1;
}
else
{
return CountryTemplate2;
}
}
return null;
}
}
 

This is how the RadDataGrid control will look when CellContentStyleSelector is applied.

954
Telerik UI for Xamarin

SDK Samples Browser application contains Style Selector example in the DataGrid/Styling folder.
 

See Also
 DataGrid Styling
 Columns Styling
 How To

955
Telerik UI for Xamarin

How to Customize the Filtering UI


You are free to customize the appearance of the filtering component which appears when clicking
the options icon on each column's header. In order to create a custom filtering UI, you need to inherit
from the DataGridFilterControlBase class. This article will guide you through the process of creating
a custom control that will be used for applying the filtering. Figure 1 shows the default appearance of
the functionality

Figure 1: Default appearance of the filtering UI

1. The first step is to create the custom Control which will inherit from the DataGridFilterControlBase
class:

XAML
<grid:DataGridFilterControlBase xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"

xmlns:grid="clr-namespace:Telerik.XamarinForms.DataGrid;assembly=Telerik.XamarinForms.
DataGrid"

x:Class="SDKBrowser.Examples.DataGridControl.FilteringUICategory.CustomFilteringUIExam
ple.TemplateColumnFilteringUI">
<StackLayout Margin="10">
<Picker x:Name="descriptorOperatorPicker"
TextColor="Black"/>
<Entry x:Name="textEntry"/>
</StackLayout>

956
Telerik UI for Xamarin

</grid:DataGridFilterControlBase>
 

C#
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class TemplateColumnFilteringUI : DataGridFilterControlBase
{
public TemplateColumnFilteringUI()
{
this.InitializeComponent();
}

public FilterDescriptorBase FilterDescriptor { get; set; }

public override FilterDescriptorBase BuildDescriptor()


{
TextFilterDescriptor textDescriptor = new TextFilterDescriptor();
textDescriptor.PropertyName = this.PropertyName;
textDescriptor.Value = this.textEntry.Text;
textDescriptor.Operator =
(TextOperator)this.descriptorOperatorPicker.SelectedIndex;

return textDescriptor;
}

protected override void Initialize()


{
this.descriptorOperatorPicker.ItemsSource = this.GetOperators();
var textFilterDescriptor = this.FilterDescriptor as TextFilterDescriptor;
if (textFilterDescriptor != null)
{
this.descriptorOperatorPicker.SelectedIndex =
(int)textFilterDescriptor.Operator;
this.textEntry.Text = textFilterDescriptor.Value.ToString();
}
else
{
this.descriptorOperatorPicker.SelectedIndex = 0;
if (!string.IsNullOrEmpty(this.textEntry.Text))
{
this.textEntry.Text = null;
}
}
}

private List<string> GetOperators()


{
var operators = Enum.GetNames(typeof(TextOperator)).ToList();
return operators;
}
}
 

957
Telerik UI for Xamarin

You should override the required methods as shown in the C# snippet above.

2. Eventually, you need to set the already created component as a filtering control for the column
you need to update. This is done by creating a custom DataGridCommand:

C#
public class CustomOptionsTapCommand : DataGridCommand
{
private TemplateColumnFilteringUI filterControl;

public CustomOptionsTapCommand()
{
this.Id = DataGridCommandId.OptionsTap;
}

public override void Execute(object parameter)


{
var optionsTapContext = parameter as OptionsTapContext;
if (optionsTapContext != null)
{
if (this.filterControl == null)
{
this.filterControl = new TemplateColumnFilteringUI();
}

DataGridTypedColumn column = (DataGridTypedColumn)optionsTapContext.Column;


this.filterControl.PropertyName = column.PropertyName;
this.filterControl.FilterDescriptor = optionsTapContext.AssociatedDescriptor;
optionsTapContext.FilterControl = filterControl;
}

this.Owner.CommandService.ExecuteDefaultCommand(DataGridCommandId.OptionsTap,
optionsTapContext);
}
}
 

Figure 2 shows the appearance of the control once the custom filtering control is set.

Figure 2: Appearance of the Filtering UI after applying the custom control

958
Telerik UI for Xamarin

You can review an actual sample that shows how to achieve the functionality in the
Examples/DataGrid/FilteringUI folder from the SDK Samples Browser application.
 

See Also
 DataGrid Filtering
 DataGrid Grouping

959
Telerik UI for Xamarin

Overview
Telerik Date Picker for Xamarin allows the users to select a date. Its items are visualized inside a
popup. Date Picker control has a number of features which allows you to set a date range, date
format and fully customize the dialog appearance such as its header and footer.

Key features
 Spinner Format: Date Picker for Xamarin allows you to use standard or custom date format
string through the DatePicker.SpinnerFormat property. Depending on what format is set, the
picker visualizes spinner controls with prepopulated values to be picked. For more
information check the Date Format String article in our documentation.
 Templates: Date Picker provides templates for its header and footer. Also we have exposed
templates for the picker placeholder and display text. For additional info go to Templates
article.
 DisplayString Format: You can choose what text to be displayed when a date is selected
using the Date Picker DisplayStringFormat property. For more info on this check the Key
Features - DisplayString Format section.

960
Telerik UI for Xamarin

 Date Range: RadDate Picker allows you to define a date range when setting minimum and
maximum date values and choose a date in between. To learn more about this, visit Key
Features Date Range section.
 Flexible Styling API: Take advantage of the styling capabilities of the RadDatePicker control.
You can easily style its Spinners, the Popup and its header and footer, the text displayed
after date is selected and many more.
 Commands Support: Date Picker exposes command that allows you to clear the selected
date - Clear Command and Toggle Command that allows you to open and close the dialog.
More information about Commands support check our help article here.

Check out Date Picker for Xamarin Getting Started help article that shows how to use it in a basic
scenario.
 

See Also
 Visual Structure
 Getting Started
 Key Features
 Templates
 Styling

961
Telerik UI for Xamarin

Visual Structure
Here are described all visual elements used in the Date Picker for Xamarin.

Date Picker Structure before and after a date/time is


selected

Picker Popup Visual Structure


More information about Spinners refer to the RadSpinner help article.
 

962
Telerik UI for Xamarin

Legend
 Placeholder - the text visualized before picking a date/time. Placeholder could be customized
through the PlaceholderTemplate property.
 DisplayStringFormat - the text vislualized after a date/time is picked.
 Header - the text displayed in the popup header. It could se set a direct text through the
HeaderLabelText property or fully customize the popup header using the HeaderTemplate
property.
 SpinnerHeader - the text visualized for spinner header depending on the values to be picked.
For example if the SpinnerFormatString is d the text visualized for spinner header will be
Month Day Year.
 Spinner - displays items in a list.
 SelectionHighlight - highlisht the current selected date when the popup is open.
 Footer - the footer of the popup. By default is contains OK and Cancel Buttons. It could be
customized through the FooterTemplate property.

963
Telerik UI for Xamarin

Getting Started with Date Picker for


Xamarin
This article will guide you through the steps needed to add a basic RadDatePicker control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadDatePicker control

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to install a
separate nuget package. For RadDatePicker control you have to install the
Telerik.UI.for.Xamarin.Input nuget package. This nuget will automatically refer the
Telerik.UI.for.Xamarin.Primitives, Telerik.UI.for.Xamarin.Common, and
Telerik.UI.for.Xamarin.DataControls nuget packages.
 

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadDatePicker component:

Platform Assemblies
Portable Telerik.XamarinForms.Input
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.SkiaSharp.dll
Android Telerik.XamarinForms.Input
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.DataControls.dll

964
Telerik UI for Xamarin

Telerik.XamarinForms.SkiaSharp.dll
iOS Telerik.XamarinForms.Input
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.SkiaSharp.dll
UWP Telerik.XamarinForms.Input
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.SkiaSharp.dll

3. Adding RadDatePicker control


You could use one of the following approaches:

Drag the control from the Toolbox.

Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML or C#.

The snippet below shows a simple RadDatePicker definition:

XAML
<telerikInput:RadDatePicker />
 

In addition to this, you need to add the following namespace:


XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

C#
using Telerik.XamarinForms.Input;
 

This is the result:

965
Telerik UI for Xamarin

SDK Browser and Telerik Xamarin Samples applications contain different examples that show
RadTimePicker's main features. For detailed information on this go to Xamarin Demos Applications
topic.
 

See Also
 Supported Standard Date and Time Format Strings
 Key Features
 Templates
 Selection
 Styling

966
Telerik UI for Xamarin

Spinner Format
Date Picker for Xamarin allows you to use standard or custom date format strings through the
SpinnerFormat property. Depending on what format is set, the picker visualizes spinner controls with
prepopulated values to be picked.

 SpinnerFormat(string): Defines the string format for the spinners. The default format is "g".

Standard Date Format Strings


The available Standard Date Format Strings which can be set to the SpinnerFormat property are
described in the table below:

Supported Standard Date Format String Description


"d" Short Date Format. Invariant culture format is
MM/dd/yyyy
"G" Short Date "d" and Long Time "T"
"g" Short Date "d" and Short Time "t"
"M" Month Format Specifier
"m" Month Format specifier
"Y" Year Month Format Specifier
"y" Year Month Format Specifier

Custom Date Format Strings


The available Custom Date Format Strings which can be set to the SpinnerFormat property are
described in the table below:

Supported Custom Date Format Strings


"d"
"dd"
"M"
"MM"
"MMM"
"MMMM"
"y"
"yyy"

967
Telerik UI for Xamarin

"yyyy"
We currently do not support any standard date formats which contain long date inside them.
Standard Date Format Strings to the Date Picker control.
 

Supported Separators
When SpinnerFormat is set and the device culture is changed, the separators used for the format
string won't be changed:

Supported Format Separators


"-"
"."
","
""
":"
"/"

Examples
SpinnerFormat="MMMM dd"
XAML
<telerikInput:RadDatePicker SpinnerFormat="MMMM dd" />
 

And the result:

968
Telerik UI for Xamarin

SpinnerFormat="dd"
XAML
<telerikInput:RadDatePicker SpinnerFormat="dd" />
 

And the result:

969
Telerik UI for Xamarin

SpinnerFormat="MMM yyyy"
XAML
<telerikInput:RadDatePicker SpinnerFormat="MMM yyyy" />
 

And the result:

970
Telerik UI for Xamarin

SpinnerFormat="yyyy/dd/MMM"
XAML
<telerikInput:RadDatePicker SpinnerFormat="yyyy/dd/MMM" />
 

And the result:

971
Telerik UI for Xamarin

See Also
 Templates
 Styling
 Selection
 Commands

972
Telerik UI for Xamarin

Key Features
The purpose of this help article is to show you the key features of the Date Picker control for
Xamarin.

Date Range
Date Picker allows you to define a date range and choose a date in between through the following
properties:

 MinimumDate(DateTime): Defines a date which marks the deginning of the range of the
available dates. The default value is DateTime(2000,1,1).
 MaximumDate(DateTime): Defines a date which marks the end of the range of the available
dates to choose from. The default value is DateTime(2099, 12, 31, 23, 59, 59).

Example
XAML
<telerikInput:RadDatePicker MinimumDate="2020,1,1"
MaximumDate="2020,12,31"
DisplayStringFormat="yyy-ddd-MMM"/>
 

and use the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

Current Selected Date


 Date(DateTime?): Defines the current date selection. The default value is null.

Example
XAML
<telerikInput:RadDatePicker Date="2020,05,15"
SpinnerFormat="yyy-MMM"/>
 

and add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF

973
Telerik UI for Xamarin

orms.Input"
 

DefaultHighlightedDate
RadDateTime Picker DefaultHighlightedDate(DateTime) defines the System.DateTime which will be
used to pre-scroll each spinner when RadDatePicker.Date property is set to null.

Example
XAML
<telerikInput:RadDateTimePicker Date="{x:Null}"
DefaultHighlightedDate="2020,05,15"
SpinnerFormat="dd/MMM/yyyy"/>
 

and the namespace needed:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

DisplayString Format
 DisplayStringFormat(string): Defines the format of the string that will be visualized when the
picker dialog is closed.

The format set for DisplayStringFormat should be a valid date format.


 

Example
Here is a sample Date Picker definition:

XAML
<telerikInput:RadDatePicker DefaultHighlightedDate="2020,05,15"
DisplayStringFormat="yyyy/MMM/dd"
Placeholder="Pick a date!"
SpinnerFormat="dd/MMM/yyyy"
AreSpinnerHeadersVisible="False"/>
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"

974
Telerik UI for Xamarin

A sample Key Features example can be found in the DatePicker/Features folder of the SDK Samples
Browser application.
 

See Also
 Templates
 Styling
 Commands
 Selection

975
Telerik UI for Xamarin

Templates
If the default templates of the control do not suit your needs, you can easily define custom ones. The
available templates for customizing are:

 PlaceholderTemplate(ControlTemplate): Defines the template visualized for the placeholder.


 DisplayTemplate(ControlTemplate): Defines the template visualized when the picked
date/time is displayed.
 HeaderTemplate(ControlTemplate): Defines what will be displayed inside the dialog(popup)
header.
 FooterTemplate(ControlTemplate): Defines what will be displayed inside the dialog(popup)
footer.

PlaceholderTemplate
XAML
<ControlTemplate x:Key="Picker_PlaceholderView_ControlTemplate">
<Grid>
<Grid.GestureRecognizers>
<TapGestureRecognizer Command="{TemplateBinding ToggleCommand}" />
</Grid.GestureRecognizers>
<Label Text="{TemplateBinding Placeholder}"
Style="{TemplateBinding PlaceholderLabelStyle}"
AutomationId="PickerPlaceholderLabel"/>
</Grid>
</ControlTemplate>
 

DisplayTemplate
XAML
<ControlTemplate x:Key="Picker_DisplayView_ControlTemplate">
<Grid>
<Grid.GestureRecognizers>
<TapGestureRecognizer Command="{TemplateBinding ToggleCommand}" />
</Grid.GestureRecognizers>
<Label Text="{TemplateBinding DisplayString}"
Style="{TemplateBinding DisplayLabelStyle}"
AutomationId="PickerDisplayLabel"/>
</Grid>
</ControlTemplate>
 

HeaderTemplate
XAML

976
Telerik UI for Xamarin

<ControlTemplate x:Key="PopupView_Header_ControlTemplate">
<telerikPrimitives:RadBorder BackgroundColor="{TemplateBinding BackgroundColor}"
BorderColor="{TemplateBinding BorderColor}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="{TemplateBinding CornerRadius}">
<Label Text="{TemplateBinding HeaderLabelText}"
Style="{TemplateBinding HeaderLabelStyle}"
AutomationId="PickerPopupHeaderLabel"/>
</telerikPrimitives:RadBorder>
</ControlTemplate>
 

FooterTemplate
XAML
<ControlTemplate x:Key="PopupView_Footer_ControlTemplate">
<telerikPrimitives:RadBorder BackgroundColor="{TemplateBinding BackgroundColor}"
BorderColor="{TemplateBinding BorderColor}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="{TemplateBinding CornerRadius}">
<OnPlatform x:TypeArguments="View">
<On Platform="Android, iOS">
<StackLayout Orientation="Horizontal" Spacing="0" HorizontalOptions="End">
<Button Text="{TemplateBinding CancelButtonText}"
Style="{TemplateBinding CancelButtonStyle}"
Command="{TemplateBinding CancelCommand}"
AutomationId="PickerPopupCancelButton"/>
<Button Text="{TemplateBinding AcceptButtonText}"
Style="{TemplateBinding AcceptButtonStyle}"
Command="{TemplateBinding AcceptCommand}"
AutomationId="PickerPopupOkButton"/>
</StackLayout>
</On>
<On Platform="UWP">
<StackLayout Orientation="Horizontal" Spacing="0" HorizontalOptions="End">
<Button Text="{TemplateBinding AcceptButtonText}"
Style="{TemplateBinding AcceptButtonStyle}"
Command="{TemplateBinding AcceptCommand}"
AutomationId="PickerPopupOkButton"/>
<Button Text="{TemplateBinding CancelButtonText}"
Style="{TemplateBinding CancelButtonStyle}"
Command="{TemplateBinding CancelCommand}"
AutomationId="PickerPopupCancelButton"/>
</StackLayout>
</On>
</OnPlatform>
</telerikPrimitives:RadBorder>
</ControlTemplate>
 

and the Date Picker definition:

977
Telerik UI for Xamarin

XAML
<telerikInput:RadDatePicker MinimumDate="2020,01,1"
MaximumDate="2025,12,31"
SpinnerFormat="MMM/dd/yyyy"
PlaceholderTemplate="{StaticResource Picker_PlaceholderView_ControlTemplate}"
DisplayTemplate="{StaticResource Picker_DisplayView_ControlTemplate}">
<telerikInput:RadDatePicker.SelectorSettings>
<telerikInput:PickerPopupSelectorSettings HeaderTemplate="{StaticResource
PopupView_Header_ControlTemplate}"
HeaderLabelText="Date Picker"
FooterTemplate="{StaticResource PopupView_Footer_ControlTemplate}"/>
</telerikInput:RadDatePicker.SelectorSettings>
</telerikInput:RadDatePicker>
 

A sample Default Templates example can be found in the DatePicker/Features folder of the SDK
Samples Browser application.
 

Example How to Customize the Default Look


The snippet below shows a simple Date Picker definition:

XAML
<telerikInput:RadDatePicker MinimumDate="2020,01,1"
MaximumDate="2025,12,31"
SpinnerFormat="MMM/dd/yyyy"
PlaceholderTemplate="{StaticResource placeholderTemplate}"
DisplayTemplate="{StaticResource displayTemplate}">
<telerikInput:RadDatePicker.SelectorSettings>
<telerikInput:PickerPopupSelectorSettings HeaderTemplate="{StaticResource
headerTemplate}"
HeaderLabelText="This is the Header Template"
FooterTemplate="{StaticResource footerTemplate}"/>
</telerikInput:RadDatePicker.SelectorSettings>
</telerikInput:RadDatePicker>
 

Now lets add the templates definition to the page resources:

Custom PlaceholderTemplate
XAML
<ControlTemplate x:Key="placeholderTemplate">
<Button Text="{TemplateBinding Placeholder}"
FontAttributes="Bold"
TextColor="White"
BackgroundColor="#B73562"
HeightRequest="50" Command="{TemplateBinding ToggleCommand}" />
</ControlTemplate>

978
Telerik UI for Xamarin

Custom DisplayTemplate
XAML
<ControlTemplate x:Key="displayTemplate">
<Button Text="{TemplateBinding DisplayString}"
TextColor="White"
BackgroundColor="#7BAEFF"
HeightRequest="50"
Command="{TemplateBinding ToggleCommand}" />
</ControlTemplate>
 

Custom HeaderTemplate
XAML
<ControlTemplate x:Key="headerTemplate">
<Label Text="Date Picker"
TextColor="White"
VerticalTextAlignment="Center"
HorizontalTextAlignment="Center"
BackgroundColor="#B73562"/>
</ControlTemplate>
 

Custom FooterTemplate
XAML
<ControlTemplate x:Key="footerTemplate">
<StackLayout Orientation="Horizontal" Spacing="0"
HorizontalOptions="FillAndExpand" BackgroundColor="#B73562">
<Button Text="Cancel"
TextColor="White"
BackgroundColor="Transparent"
Command="{TemplateBinding CancelCommand}" />

979
Telerik UI for Xamarin

<Button Text="OK"
TextColor="White"
BackgroundColor="Transparent"
Command="{TemplateBinding AcceptCommand}" />
</StackLayout>
</ControlTemplate>
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

A sample Custom Templates example can be found in the DatePicker/Features folder of the SDK
Samples Browser application.
 

See Also

980
Telerik UI for Xamarin

 Suppoted Standard Date Format Strings


 Key Features
 Styling

981
Telerik UI for Xamarin

Date Picker Localization


RadDate Picker for Xamarin provides language localization. In short, you can translate the used
across the Date Picker texts to other languages, so that your app can be adapted to different
regions.

To learn in details about the localization process of Telerik UI for Xamarin components, please go
through the common Localization and Globalization topic.
 
The sections below list all the localization keys used in Date Picker for Xamarin control.

Date Picker Header Localization Key


Localization Key Default Value
DatePicker_Popup_HeaderLabelText Select Date
DatePicker_PlaceholderLabelText Select Date

Common Picker Localizations strings


Localization Key Default Value
Picker_DaySpinnerHeaderLabelText Day
Picker_MonthSpinnerHeaderLabelText Month
Picker_YearSpinnerHeaderLabelText Year
Picker_Popup_AcceptButtonText OK
Picker_Popup_CancelButtonText Cancel
Check in the image below how the localization strings are presented in Date Picker:

982
Telerik UI for Xamarin

See Also
 Localization and Globalization

983
Telerik UI for Xamarin

Selection
RadDatePicker control enables the app users to quickly and easily select a date value. This topic will
go through the provided by the DatePicker API related to date selection.

Important Properties
 Date(DateTime?): Defines the current date selection. The default value is null.

Check below a quick example of Time property usage:

XAML
<telerikInput:RadDatePicker Date="2020,05,15"
SpinnerFormat="yyy-MMM"/>
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

Methods
Date Picker for Xamarin allows you to clear the selected date through its ClearSelection method

Example
XAML
<StackLayout>
<Button Text="Clear Selection" Clicked="OnClearSelectionClicked"/>
<telerikInput:RadDatePicker x:Name="datePicker"/>
</StackLayout>
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

Call ClearSelection inside the button click event - as a result Date property will be updated to null.

C#

984
Telerik UI for Xamarin

private void OnClearSelectionClicked(object sender, EventArgs e)


{
this.datePicker.ClearSelection();
}
 

Events
RadTime Picker exposes a SelectionChanged event which is raised when the user picks a time
value.

Example
XAML
<telerikInput:RadDatePicker SelectionChanged="RadDatePicker_SelectionChanged"/>
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

and the SelectionChanged event, where the sender is the RadDatePicker control

C#
private void RadDatePicker_SelectionChanged(object sender, EventArgs e)
{
// implement your logic here
}
 

See Also
 Key Features
 Commands
 Templates

985
Telerik UI for Xamarin

Commands
DatePicker Commands
Date Picker for Xamarin exposes the following commands you can use to programmatically
manipulate displaying the popup as well as clearing the selected time:

 ToggleCommand(ICommand): Allows you to show/hide the popup used for selecting a date
value.
 ClearCommand(ICommand): Allows you to clear the displayed date.

Example for ToggleCommand and ClearCommand


XAML
<StackLayout>
<Button Text="Toggle Command" Command="{Binding Source={x:Reference datePicker},
Path=ToggleCommand}"/>
<Button Text="Clear Command" Command="{Binding Source={x:Reference datePicker},
Path=ClearCommand}"/>
<telerikInput:RadDatePicker x:Name="datePicker" />
</StackLayout>
 

also you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

PopupSelector Commands
Through the popup users can pick a date. The date value should be confirmed or rejected through
the OK and Cancel buttons placed on the popup.

DatePicker allows you to add a custom logic for the Accept and Cancel commands which are
executed when OK and Cancel buttons, respectively, are pressed.

 AcceptCommand(ICommand): Defines the command which confirms the current selection of


the picker and closes the popup. AcceptCommandParameter can be used to pass a
parameter to the command execute method.
 CancelCommand(ICommand): Defines the command which rejects the current selection of
the picker and closes the popup. CancelCommandParameter can be used to pass a
parameter to the command execute method.

The Accept and Cancel commands can be applied using the SelectorSettings property of

986
Telerik UI for Xamarin

RadDatePicker. In addition, you can pass command parameters through the


AcceptCommandParameter and CancelCommandParameter properties of the DatePicker
SelectorSettings.

Here is a quick example on how they could be set:

Example for AcceptCommand and CancelCommand


XAML
<telerikInput:RadDatePicker x:Name="datePicker">
<telerikInput:RadDatePicker.SelectorSettings>
<telerikInput:PickerPopupSelectorSettings AcceptCommand="{Binding Accept}"
AcceptCommandParameter="{Binding Date, Source={x:Reference datePicker}}"
CancelCommand="{Binding Cancel}"
CancelCommandParameter="{Binding Date, Source={x:Reference datePicker}}"/>
</telerikInput:RadDatePicker.SelectorSettings>
<telerikInput:RadDatePicker.BindingContext>
<local:ViewModel/>
</telerikInput:RadDatePicker.BindingContext>
</telerikInput:RadDatePicker>
 

and the ViewModel

C#
public class ViewModel
{
public ICommand Accept { get; set; }
public ICommand Cancel { get; set; }

public ViewModel()
{
this.Accept = new Command(this.OnAccept);
this.Cancel = new Command(this.OnCancel);
}

private void OnAccept(object param)


{
Application.Current.MainPage.DisplayAlert("Date selected", String.Format("New
Date: {0:d}", (DateTime)param), "OK");
// implement your custom logic here
}

private void OnCancel(object param)


{
var message = param != null ? String.Format("Current date: {0:d}",
(DateTime)param) : "Currently no date is selected";
Application.Current.MainPage.DisplayAlert("Date Selection Canceled", message,
"OK");
// implement your custom logic here
}
}

987
Telerik UI for Xamarin

also you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

See Also
 Key Features
 Templates
 Selection

988
Telerik UI for Xamarin

Styling
DatePicker Styling
Date Picker control for Xamarin provides the following Style properties for customizing its look:

 SpinnerStyle(of type Style with target type telerikDataControls:RadSpinner): Defines the


style applied to the spinner item and selected item.
 SpinnerHeaderStyle(of type Style with target type Xamarin.Forms.Label): Specifies the style
applied to each spinner header label.
 SelectionHighlightStyle(of type Style with target type telerikPrimitives:RadBorder): Specifies
the style applied to the border highlights the selection.
 PlaceholderLabelStyle(of type Style with target type Xamarin.Forms.Label): Specifies the
style applied to the label defined in the default PlaceholderTemplate.
 DisplayLabelStyle(of type Style with target type Xamarin.Forms.Label): Defines the style
applied to the label which is visualized when date is selected.

PickerContentView class exposes the following properties for styling the DatePicker Border and
Background Color:

 BackgroundColor(Xamarin.Forms.Color): Defines the background color of the picker.


 BorderColor(Xamarin.Forms.Color): Defines the border color of the picker.
 BorderThickness(Xamarin.Forms.Thickness): Specifies the border thickness of the picker.
Default value is new Thickness(0,0,0,1).
 CornerRadius(Xamarin.Forms.Thinckness): Specifies the corner radius of the picker.

Popup Styling
Using the SelectorSettings property (of type
Telerik.XamarinForms.Input.PickerPopupSelectorSettings) of the DatePicker you can modify the
appearance of the dialog (popup). PickerPopupSelectorSettings class exposes the following Style
properties:

 PopupViewStyle(of type Style with target type telerikInput:PickerPopupContentView):


Defines the popup view style.
 HeaderStyle(of type Style with target type telerikInput:PickerPopupHeaderView): Defines the
popup header style.
 HeaderLabelStyle(of type Style with target type Xamarin.Forms.Label): Defines the popup
header label style.
 FooterStyle(of type Style with target type telerikInput:PickerPopupFooterView): Defines the
popup footer style.
 AcceptButtonStyle(of type Style with target type Xamarin.Forms.Button): Defines the Accept
button style.
 CancelButtonStyle(of type Style with target type Xamarin.Forms.Button): Defines the Cancel
button style.

The SelectorSetting also provides the following properties for popup customization:

989
Telerik UI for Xamarin

 PopupOutsideBackgroundColor(Xamarin.Forms.Color): Defines the color outside of the


popup.
 IsPopupModal(bool): Defines a boolean value indicating if the popup should be closed when
tapped outside of the popup. By default the value of the IsPopupModal is false.
 When IsPopupModal="True" the UI behind the popup gets inactive and cannot be used
until the popup is closed.
 When IsPopupModal="False" the popup could be closed when clicking outside the
popup.
 HeaderLabelText(string): Specifies the text visualized in the popup header.
 IsHeaderVisible(bool): Specifies whether the Popup header is currently visible. By default the
valuse is True.
 IsFooterVisible(bool): Specifies whether the Popup footer is currently visible. By default the
valuse is True.
 AcceptButtonText(string): Defines the text visualized for the accept button. By default the text
is OK.
 CancelButtonText(string): Defines the text visualized for the cancel button. By default the text
is Cancel.

Namespaces
Using PopupViewStyle, HeaderStyle, FooterStyle you will need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

Using SelectionHighlightStyle you need to add the following namespace:

XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
 

Using SpinnerStyle you need to add the following namespace:

XAML
xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te
lerik.XamarinForms.DataControls"
 

Example
Here is a sample example that shows how the styling properties are applied.

A sample Date Picker definition:

XAML
<telerikInput:RadDatePicker SpinnerHeaderStyle="{StaticResource spinnerHeaderStyle}"

990
Telerik UI for Xamarin

SpinnerStyle="{StaticResource spinnerStyle}"
SelectionHighlightStyle="{StaticResource selectionHighlightStyle}"
DisplayLabelStyle="{StaticResource displayLabelStyle}"
PlaceholderLabelStyle="{StaticResource placeholderLabelStyle}"
DefaultHighlightedDate="2020,05,15"
SpinnerFormat="yyy/MMM/dd"
DisplayStringFormat="yyyy/MMM/dd">
<telerikInput:RadDatePicker.SelectorSettings>
<telerikInput:PickerPopupSelectorSettings
PopupOutsideBackgroundColor="#D9D9D9CC"
PopupViewStyle="{StaticResource popupViewStyle}"
HeaderStyle="{StaticResource headerStyle}"
HeaderLabelText="Date Picker"
HeaderLabelStyle="{StaticResource headerLabelStyle}"
FooterStyle="{StaticResource footerStyle}"
AcceptButtonStyle="{StaticResource acceptButtonStyle}"
CancelButtonStyle="{StaticResource cancelButtonStyle}"/>
</telerikInput:RadDatePicker.SelectorSettings>
</telerikInput:RadDatePicker>
 

and here are how the styles are defined in the page resources

Spinner Style
XAML
<Style TargetType="telerikDataControls:RadSpinner" x:Key="spinnerStyle">
<Setter Property="ItemStyle">
<Setter.Value>
<Style TargetType="telerikDataControls:SpinnerItemView">
<Setter Property="TextColor" Value="#4A4949"/>
</Style>
</Setter.Value>
</Setter>
<Setter Property="SelectedItemStyle">
<Setter.Value>
<Style TargetType="telerikDataControls:SpinnerItemView">
<Setter Property="TextColor" Value="Black"/>
<Setter Property="FontAttributes" Value="Bold"/>
</Style>
</Setter.Value>
</Setter>
</Style>
 

SpinnerHeader Style
XAML
<Style TargetType="Label" x:Key="spinnerHeaderStyle">
<Setter Property="TextColor" Value="Black"/>

991
Telerik UI for Xamarin

<Setter Property="FontAttributes" Value="Bold"/>


<Setter Property="HorizontalOptions" Value="FillAndExpand"/>
<Setter Property="VerticalOptions" Value="FillAndExpand"/>
<Setter Property="HorizontalTextAlignment" Value="Center"/>
<Setter Property="VerticalTextAlignment" Value="Center"/>
</Style>
 

SelectionHighlight Style
XAML
<Style TargetType="telerikPrimitives:RadBorder" x:Key="selectionHighlightStyle">
<Setter Property="BorderColor" Value="#00B5DC"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Padding" Value="0,6,0,6"/>
<Setter Property="HeightRequest" Value="40"/>
<Setter Property="VerticalOptions" Value="Center"/>
</Style>
 

PlaceholderLabel Style
XAML
<Style TargetType="Label" x:Key="placeholderLabelStyle">
<Setter Property="TextColor" Value="#4A4949"/>
<Setter Property="VerticalTextAlignment" Value="Center"/>
<Setter Property="HorizontalTextAlignment" Value="Center"/>
<Setter Property="HeightRequest" Value="50"/>
</Style>
 

DisplayLabel Style
XAML
<Style TargetType="Label" x:Key="displayLabelStyle">
<Setter Property="TextColor" Value="Black"/>
<Setter Property="VerticalTextAlignment" Value="Center"/>
<Setter Property="HorizontalTextAlignment" Value="Center"/>
<Setter Property="HeightRequest" Value="50"/>
</Style>
 

PopupView Style
XAML
<Style TargetType="telerikInput:PickerPopupContentView" x:Key="popupViewStyle">
<Setter Property="BackgroundColor" Value="White"/>
<Setter Property="WidthRequest" Value="270"/>

992
Telerik UI for Xamarin

</Style>
 

Header Style
XAML
<Style TargetType="telerikInput:PickerPopupHeaderView" x:Key="headerStyle">
<Setter Property="BackgroundColor" Value="#00B5DC"/>
<Setter Property="HeightRequest" Value="60"/>
<Setter Property="Margin" Value="0"/>
<Setter Property="Padding" Value="0"/>
<Setter Property="HorizontalOptions" Value="FillAndExpand"/>
<Setter Property="VerticalOptions" Value="FillAndExpand"/>
</Style>
 

HeaderLabel Style
XAML
<Style TargetType="Label" x:Key="headerLabelStyle">
<Setter Property="TextColor" Value="White"/>
<Setter Property="HorizontalOptions" Value="Center"/>
<Setter Property="VerticalOptions" Value="Center"/>
<Setter Property="FontSize" Value="Title"/>
</Style>
 

Footer Style
XAML
<Style TargetType="telerikInput:PickerPopupFooterView" x:Key="footerStyle">
<Setter Property="BackgroundColor" Value="Transparent"/>
</Style>
 

AcceptButton Style
XAML
<Style TargetType="Button" x:Key="acceptButtonStyle">
<Setter Property="BackgroundColor" Value="Transparent"/>
<Setter Property="Text" Value="OK"/>
<Setter Property="TextColor" Value="#00B5DC"/>
</Style>
 

CancelButton Style

993
Telerik UI for Xamarin

XAML
<Style TargetType="Button" x:Key="cancelButtonStyle">
<Setter Property="BackgroundColor" Value="Transparent"/>
<Setter Property="Text" Value="X"/>
<Setter Property="TextColor" Value="#00B5DC"/>
</Style>
 

Namespaces
In addition, add the following namespaces:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te
lerik.XamarinForms.DataControls"
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
 

This is how the Date Picker control looks when the styles described above are applied:

A sample Styling example can be found in the DatePicker/Features folder of the SDK Samples
Browser application.
 

See Also
994
Telerik UI for Xamarin

 Key Features
 Templates
 Commands
 Visual Structure

995
Telerik UI for Xamarin

Overview
Telerik Date and Time Picker for Xamarin provides an easy way to pick a date, time or date and time
depending on the used format string. Its items are visualized inside a popup. Date and Time Picker
control has a number of features which allows you to set a date range, date and time format and fully
customize the dialog appearance such as its header and footer.

Key features
 Spinner Format: Date and Time Picker for Xamarin allows you to use standard or custom
date and time format strings through the SpinnerFormatString property. Depending on what
format is set, the picker visualizes spinner controls with prepopulated values to be picked.
This feature allows you to create a date picker, time picker or combination of both. For more
information check the DateTime Format String topic in our documentation.
 Templates: Date and Time Picker provides templates for its header and footer. Also we have
exposed templates for the picker placeholder and display text. For additional info go to
Templates article.
 DisplayString Format: You can choose what text to display when a date/time was picked
through the DateTime Picker DisplayStringFormat property. For more info on this check the
Key Features - DisplayString Format section.
 Date Range: RadDateTime Picker allows you to define a particular start and end date and
choose a date in between. To learn more about this, visit Key Features Date Range section.
 Flexible Styling API: Take advantage of the styling capabilities of the RadDateTimePicker
control. You can easily style its Spinners, the Popup and its header and footer, the text

996
Telerik UI for Xamarin

displayed after date/time is picked and many more.


 Commands Support: DateTime Picker exposes commands that allow you to clear the
selected date/time - Clear Command and Toggle Command which allows you to open and
close the dialog. More information about Commands support check our help article here.

Check out RadDateTime Picker Getting Started help article that shows how to use it in a basic
scenario.
 

See Also
 Visual Structure
 Getting Started
 Key Features
 Templates
 Styling

997
Telerik UI for Xamarin

Visual Structure
Here are described all visual elements used in the Date and Time Picker for Xamarin.

DateTime Picker Structure before and after a date/time is


selected

Picker Popup Visual Structure


More information about Spinners refer to the RadSpinner help article.
 

998
Telerik UI for Xamarin

Legend
 Placeholder - the text visualized before picking a date/time. Placeholder could be customized
through the PlaceholderTemplate property.
 DisplayStringFormat - the text vislualized after a date/time is picked.
 Header - the text displayed in the popup header. It could se set a direct text through the
HeaderLabelText property or fully customize the popup header using the HeaderTemplate
property.
 SelectedDate - the date displayed when popup is open.
 SpinnerHeader - the text visualized for spinner header depending on the values to be picked.
For example if the SpinnerFormatString is d and AreSpinnerHeadersVisible="True" The text
visualized for spinner header will be Month Day Year.
 Spinner - displays items in a list.
 SelectionHighlight - highlisht the current selected date/time when the popup is open.
 Footer - the footer of the popup. By default is contains OK and Cancel Buttons. It could be
customized through the FooterTemplate property.

999
Telerik UI for Xamarin

Getting Started with Date and Time Picker


for Xamarin
This article will guide you through the steps needed to add a basic RadDateTimePicker control in
your application.

 Setting up the app


 Adding the required Telerik references
 Adding RadDateTimePicker control

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to install a
separate nuget package. For RadDateTimePicker control you have to install the
Telerik.UI.for.Xamarin.Input nuget package. This nuget will automatically refer the
Telerik.UI.for.Xamarin.Primitives, Telerik.UI.for.Xamarin.Common, and
Telerik.UI.for.Xamarin.DataControls nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadDateTimePicker component:

Platform Assemblies
Portable Telerik.XamarinForms.Input
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.SkiaSharp.dll
Android Telerik.XamarinForms.Input
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.SkiaSharp.dll

1000
Telerik UI for Xamarin

iOS Telerik.XamarinForms.Input
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.SkiaSharp.dll
UWP Telerik.XamarinForms.Input
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.SkiaSharp.dll

3. Adding RadDateTimePicker control


You could use one of the following approaches:

Drag the control from the Toolbox.

Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML or C#.

The snippet below shows a simple RadDateTimePicker definition:

XAML
<telerikInput:RadDateTimePicker />
 

In addition to this, you need to add the following namespace:


XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

C#
using Telerik.XamarinForms.Input;
 

This is the result:

1001
Telerik UI for Xamarin

SDK Browser and Telerik Xamarin Samples applications contain different examples that show
RadTimePicker's main features. For detailed information on this go to Xamarin Demos Applications
topic.
 

See Also
 Suppoted Standard Date and Time Format Strings
 Key Features
 Templates
 Styling

1002
Telerik UI for Xamarin

DateTime Picker from Beta to Official


With R2 2020 Official Release of Telerik UI for Xamarin, the RadDateTimePicker control is now
official. The following article describes the changes made in the DateTimePicker in its official
version.

API changes
The following table contains the names of the properties which were changed in the official version
of the control.

Beta Official
StartDate MinimumDate
EndDate MaximumDate
SelectedDate Date
DefaultDisplayDate DefaultHighlightedDate
SpinnerFormatString SpinnerFormat

DisplayStringFormat
When DisplayStringFormat is not set explicitly its default value is taken from SpinnerFormat. Default
value of the SpinnerFormat is "g". For more details please check the SpinnerFormat article.

Placeholder Label Text

Beta Official
Pick a value Select Date and Time

Looping
Looping of items is stopped automatically when reaching the limits imposed by MinimumDate and
MaximumDate.

Localization keys
The following table contains the names of the localzation keys which were changed in the official
version of the control:

Beta Official
Pickers_Placeholder DateTimePicker_PlaceholderLabelText

1003
Telerik UI for Xamarin

DateTimePicker_AmPmSpinnerHeaderString Picker_AmPmSpinnerHeaderLabelText
DateTimePicker_DaySpinnerHeaderString Picker_DaySpinnerHeaderLabelText
DateTimePicker_HourSpinnerHeaderString Picker_HourSpinnerHeaderLabelText
DateTimePicker_MinuteSpinnerHeaderString Picker_MinuteSpinnerHeaderLabelText
DateTimePicker_MonthSpinnerHeaderString Picker_MonthSpinnerHeaderLabelText
DateTimePicker_SecondSpinnerHeaderString Picker_SecondSpinnerHeaderLabelText
DateTimePicker_YearSpinnerHeaderString Picker_YearSpinnerHeaderLabelText
Pickers_Popup_AcceptButtonText Picker_Popup_AcceptButtonText
Pickers_Popup_RejectButtonText Picker_Popup_CancelButtonText
To accomodate these changes in your application update the property names from the beta version
to the official ones.

Visual changes
Border below the DateTime Picker text

 BorderThickness(Xamarin.Forms.Thickness): Specifies the border thickness of the picker.


Default value is new Thickness(0,0,0,1).

Header and Footer visibility


With the official version of the control IsHeaderVisible and IsFooterVisible porperties have a public
setter.

By default the header of the DateTimePicker Popup is not visible. In order to visualize the header
you need to set IsHeaderVisible property to True. The default value of HeaderLabelText is
Select Date and Time.By default the footer of the DateTimePicker Popup is visible. In order to hide
the footer you need to set IsFooterVisible to False.

OK and Cancel Buttons TextColor


The TextColor of the OK and Cancel buttons inside the popup is now Accent for the OS instead of
"#007AFF". Use PickerPopupSelectorSettings.AcceptButtonStyle and
PickerPopupSelectorSettings.CancelButtonStyle to set the color per your requirement:

XAML
<telerikInput:RadDateTimePicker>
<telerikInput:RadDateTimePicker.SelectorSettings>
<telerikInput:PickerPopupSelectorSettings>
<telerikInput:PickerPopupSelectorSettings.AcceptButtonStyle>
<Style TargetType="Button">
<Setter Property="TextColor" Value="#007AFF"/>
</Style>
</telerikInput:PickerPopupSelectorSettings.AcceptButtonStyle>

1004
Telerik UI for Xamarin

<telerikInput:PickerPopupSelectorSettings.CancelButtonStyle>
<Style TargetType="Button">
<Setter Property="TextColor" Value="#007AFF"/>
</Style>
</telerikInput:PickerPopupSelectorSettings.CancelButtonStyle>
</telerikInput:PickerPopupSelectorSettings>
</telerikInput:RadDateTimePicker.SelectorSettings>
</telerikInput:RadDateTimePicker>
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

Match UWP design guidelines for OK and Cancel buttons


The OK and Cancel buttons in WUP are swapped to match the design guidelines of the platform. To
swap them back set the PickerPopupSelectorSettings.FooterTemplate as follows:

XAML
<telerikInput:RadDateTimePicker>
<telerikInput:RadDateTimePicker.SelectorSettings>
<telerikInput:PickerPopupSelectorSettings>
<telerikInput:PickerPopupSelectorSettings.FooterTemplate>
<ControlTemplate>
<telerikPrimitives:RadBorder BackgroundColor="{TemplateBinding
BackgroundColor}"
BorderColor="{TemplateBinding BorderColor}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="{TemplateBinding CornerRadius}">
<StackLayout Orientation="Horizontal" Spacing="0" HorizontalOptions="End">
<Button Text="{TemplateBinding CancelButtonText}"
Style="{TemplateBinding CancelButtonStyle}"
Command="{TemplateBinding CancelCommand}"
AutomationId="PickerPopupCancelButton"/>
<Button Text="{TemplateBinding AcceptButtonText}"
Style="{TemplateBinding AcceptButtonStyle}"
Command="{TemplateBinding AcceptCommand}"
AutomationId="PickerPopupOkButton"/>
</StackLayout>
</telerikPrimitives:RadBorder>
</ControlTemplate>
</telerikInput:PickerPopupSelectorSettings.FooterTemplate>
</telerikInput:PickerPopupSelectorSettings>
</telerikInput:RadDateTimePicker.SelectorSettings>
</telerikInput:RadDateTimePicker>
 

In addition to this, you need to add the following namespace:

1005
Telerik UI for Xamarin

XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
 

Visible spinners header


All spinners in the RadDateTimePicker are visible by default. To hide them use
AreSpinnerHeadersVisible property.

XAML
<telerikInput:RadDateTimePicker AreSpinnerHeadersVisible="False">
 

See Also
 Templates
 Styling
 SpinnerFormat

1006
Telerik UI for Xamarin

Spinner Format
Date and Time Picker for Xamarin allows you to use standard or custom date and time format strings
through the SpinnerFormat property. Depending on what format is set, the picker visualizes spinner
controls with prepopulated values to be picked. This feature allows you to create a date picker, time
picker or combination of both.

 SpinnerFormat(string): Defines the string format for the spinners. The default format is "g".

Standard Date and Time Format Strings


The available Standard Date and Time format strings that can be set to the SpinnerFormat property
are described in the table below:

Supported Standard Date Format String Description


"d" Short Date Format. Invariant culture format is
MM/dd/yyyy
"G" Short Date "d" and Long Time "T"
"g" Short Date "d" and Short Time "t"
"M" Month Format Specifier
"m" Month Format specifier
"Y" Year Month Format Specifier
"y" Year Month Format Specifier
"T" Long Time Format Specifier
"t" Short Time Format Specifier
You can set only short Standard Date and Time Format Strings to the DateTime Picker control.
 

Custom Date and Time Format String


The available Custom Date and Time format strings that can be set to the SpinnerFormat property
are described in the table below:

Supported Custom Date Format Strings


"d"
"dd"
"M"
"MM"

1007
Telerik UI for Xamarin

"MMM"
"MMMM"
"y"
"yy"
"yyy"
"yyyy"
"H"
"HH"
"h"
"hh"
"m"
"mm"
"s"
"ss"
"t"
"tt"
You can set only short Custom Date and Time Format Strings to the DateTime Picker control.
 

Supported Separators
When SpinnerFormat is set and device culture is changed, the separators used for the format string
won't be changed:

Supported Date and Time Separators Formats


"-"
"."
"'"
""
":"
"/"

Examples
SpinnerFormat="MMMM dd"

1008
Telerik UI for Xamarin

XAML
<telerikInput:RadDateTimePicker SpinnerFormat="MMMM dd" />
 

And the result:

SpinnerFormat="dd"
XAML
<telerikInput:RadDateTimePicker SpinnerFormat="dd" />
 

And the result:

1009
Telerik UI for Xamarin

SpinnerFormat="H:mm"
XAML
<telerikInput:RadDateTimePicker SpinnerFormat="H:mm" />
 

And the result:

1010
Telerik UI for Xamarin

See Also
 Templates
 Styling
 Selection
 Commands

1011
Telerik UI for Xamarin

Key Features
The purpose of this help article is to show you the key features of the Date and Time Picker control
for Xamarin.

DateTime Picker
The snippet below shows a simple Date and Time Picker definition:

XAML
<telerikInput:RadDateTimePicker MinimumDate="2019,12,25"
MaximumDate="2020,02,14"
Placeholder="Pick date and time!"
AreSpinnerHeadersVisible="True"/>
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

Here is how the Date and Time Picker looks when Date and Time Format String is applied:

1012
Telerik UI for Xamarin

Date Range
RadDateTime Picker allows you to define a minimum date and maximum date and choose a date in
between through the following properties:

 MinimumDate(DateTime): Defines a date which marks the deginning of the range of the
available dates. The default value is DateTime(2000,1,1, 0, 0, 0).
 MaximumDate(DateTime): Defines a date which marks the end of the range of the available
dates to choose from. The default value is DateTime(2099, 12, 31, 23, 59, 59).

Current Selected Date


 Date(DateTime?): Defines the current date selection. The default value is null.

DefaultHighlightedDate
RadDateTime Picker DefaultHighlightedDate(DateTime) defines the System.DateTime which will be
used to pre-scroll each spinner when RadDateTimePicker.Date property is set to null.

Example
XAML
<telerikInput:RadDateTimePicker SelectedDate="{x:Null}"
DefaultDisplayDate="2020,02,14"
SpinnerFormatString="d"/>
 

Incremental Time Steps


By default, the time component of the DateTime Picker increments or decrements each part of its
time values by one step. You can change the default setup using the following properties:

 HourStep(int): Controls the incremental step of the hour value. Default value is 1.
 MinuteStep(int): Controls the incremental step of the minute value. Default value is 1.
 SecondStep(int): Controls the incremental step of the second value. Default value is 1.

DisplayString Format
 DisplayStringFormat(string): Defines the format of the string that will be visualized when the
picker dialog is closed.

The format set for DisplayStringFormat should be a valid datetime format.


 

Date Picker Mode

1013
Telerik UI for Xamarin

The snippet below shows a simple Date Picker definition:

XAML
<telerikInput:RadDateTimePicker MinimumDate="2019,12,25"
MaximumDate="2020,02,14"
SpinnerFormat="d"/>
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

Here is how the Date Picker looks when Date Format String is applied:

Time Picker Mode


The snippet below shows a simple Time Picker definition:

XAML
<telerikInput:RadDateTimePicker MinimumDate="2020,01,01 9:00:00"
MaximumDate="2021,02,01 18:00:00"
SpinnerFormat="T"
DisplayStringFormat="HH:mm:ss"
Placeholder="Pick a time!"

1014
Telerik UI for Xamarin

AreSpinnerHeadersVisible="True"/>
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

Here is how the Time Picker looks when Time Format String is applied:

A sample Key Features example can be found in the DateTimePicker/Features folder of the SDK
Samples Browser application.
 

See Also
 Templates
 Styling
 Commands

1015
Telerik UI for Xamarin

Templates
If the default templates of the control do not suit your needs, you can easily define custom ones. The
available templates for customizing are:

 PlaceholderTemplate(ControlTemplate): Defines the template visualized for the placeholder.


 DisplayTemplate(ControlTemplate): Defines the template visualized when the picked
date/time is displayed.
 HeaderTemplate(ControlTemplate): Defines what will be displayed inside the dialog(popup)
header.
 FooterTemplate(ControlTemplate): Defines what will be displayed inside the dialog(popup)
footer.

Example
The snippet below shows a simple RadDateTimePicker definition:

XAML
<telerikInput:RadDateTimePicker MinimumDate="2019,12,11"
MaximumDate="2020,02,14"
PlaceholderTemplate="{StaticResource placeholderTemplate}"
DisplayTemplate="{StaticResource displayTemplate}">
<telerikInput:RadDateTimePicker.SelectorSettings>
<telerikInput:PickerPopupSelectorSettings HeaderTemplate="{StaticResource
headerTemplate}"
HeaderLabelText="This is the Header Template"
FooterTemplate="{StaticResource footerTemplate}"/>
</telerikInput:RadDateTimePicker.SelectorSettings>
</telerikInput:RadDateTimePicker>
 

Now lets add the templates definition to the page resources:

PlaceholderTemplate
XAML
<ControlTemplate x:Key="placeholderTemplate">
<Label Text="{TemplateBinding Placeholder}"
FontAttributes="Bold"
TextColor="White"
BackgroundColor="#B73562"
HeightRequest="50"
VerticalTextAlignment="Center"
HorizontalTextAlignment="Center">
<Label.GestureRecognizers>
<TapGestureRecognizer Command="{TemplateBinding ToggleCommand}" />
</Label.GestureRecognizers>

1016
Telerik UI for Xamarin

</Label>
</ControlTemplate>
 

DisplayTemplate
XAML
<ControlTemplate x:Key="displayTemplate">
<Label Text="{TemplateBinding DisplayString}"
TextColor="White"
BackgroundColor="#7BAEFF"
HeightRequest="50"
VerticalTextAlignment="Center"
HorizontalTextAlignment="Center">
<Label.GestureRecognizers>
<TapGestureRecognizer Command="{TemplateBinding ToggleCommand}" />
</Label.GestureRecognizers>
</Label>
</ControlTemplate>
 

HeaderTemplate
XAML
<ControlTemplate x:Key="headerTemplate">
<Label Text="{TemplateBinding HeaderLabelText}"
TextColor="White"
VerticalTextAlignment="Center"
HorizontalTextAlignment="Center"
BackgroundColor="#B73562"/>
</ControlTemplate>
 

FooterTemplate

1017
Telerik UI for Xamarin

XAML
<ControlTemplate x:Key="footerTemplate">
<StackLayout Orientation="Horizontal" Spacing="0"
HorizontalOptions="FillAndExpand" BackgroundColor="#B73562">
<Button Text="{TemplateBinding CancelButtonText}"
TextColor="White"
BackgroundColor="Transparent"
Command="{TemplateBinding CancelCommand}" />
<Button Text="{TemplateBinding AcceptButtonText}"
TextColor="White"
BackgroundColor="Transparent"
Command="{TemplateBinding AcceptCommand}" />
</StackLayout>
</ControlTemplate>
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF

1018
Telerik UI for Xamarin

orms.Input"
 

A sample Custom Templates example can be found in the DateTimePicker/Features folder of the
SDK Samples Browser application.
 

See Also
 Suppoted Standard Date and Time Format Strings
 Key Features
 Styling

1019
Telerik UI for Xamarin

Date and Time Picker Localization


RadDateTime Picker for Xamarin provides language localization. In short, you can translate the used
across the Date and Time Picker texts to other languages, so that your app can be adapted to
different regions.

To learn in details about the localization process of Telerik UI for Xamarin components, please go
through the common Localization and Globalization topic.
 
The sections below list all the localization keys used in Date and Time Picker Spinners.

Date and Time Spinners Localization Keys


Localization Key Default Value
DateTimePicker_Popup_HeaderLabelText Select Date and Time
DateTimePicker_PlaceholderLabelText Select Date and Time

Common Picker Localizations strings


Localization Key Default Value
Picker_AmPmSpinnerHeaderLabelText AM/PM
Picker_DaySpinnerHeaderLabelText Day
Picker_HourSpinnerHeaderLabelText Hours
Picker_MinuteSpinnerHeaderLabelText Minutes
Picker_SecondSpinnerHeaderLabelText Seconds
Picker_MonthSpinnerHeaderLabelText Month
Picker_YearSpinnerHeaderLabelText Year
Picker_Popup_AcceptButtonText OK
Picker_Popup_CancelButtonText Cancel
Check in the image below how the localization strings are presented in Date and Time Picker:

1020
Telerik UI for Xamarin

Example with CustomLocalizationManager


The snippet below shows a simple RadDateTimePicker definition:

XAML
<telerikInput:RadDateTimePicker>
<telerikInput:RadDateTimePicker.SelectorSettings>
<telerikInput:PickerPopupSelectorSettings IsHeaderVisible="True"/>
</telerikInput:RadDateTimePicker.SelectorSettings>
</telerikInput:RadDateTimePicker>
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

Create a custom class that inherits from TelerikLocalizationManager and override the GetString()
method:

C#
TelerikLocalizationManager.Manager = new CustomDateTimePickerLocalizationManager();
 

1021
Telerik UI for Xamarin

Set it as the TelerikLocalizationManager.Manager:

C#
public class CustomDateTimePickerLocalizationManager : TelerikLocalizationManager
{
public override string GetString(string key)
{

if (key == "DateTimePicker_Popup_HeaderLabelText")
return "Datum und Uhrzeit Picker";
if (key == "DateTimePicker_PlaceholderLabelText")
return "Datum und Uhrzeit auswählen";
if (key == "Picker_AmPmSpinnerHeaderLabelText")
return "am/pm";
if (key == "Picker_DaySpinnerHeaderLabelText")
return "Tag";
if (key == "Picker_HourSpinnerHeaderLabelText")
return "Zeit";
if (key == "Picker_MinuteSpinnerHeaderLabelText")
return "Minute";
if (key == "Picker_SecondSpinnerHeaderLabelText")
return "Sekunde";
if (key == "Picker_MonthSpinnerHeaderLabelText ")
return "Monat";
if (key == "Picker_YearSpinnerHeaderLabelText")
return "Jahr";
if (key == "Picker_Popup_AcceptButtonText")
return "Akzeptieren";
if (key == "Picker_Popup_CancelButtonText")
return "Stornieren";

return base.GetString(key);
}
}
 

A sample Localization example can be found in the DateTimePicker/Features folder of the SDK
Samples Browser application.
 

See Also
 Localization and Globalization

1022
Telerik UI for Xamarin

Selection
RadDateTimePicker control enables the app users to quickly and easily select a date value. This
topic will go through the provided by the DateTimePicker API related to time selection.

Important Properties
 Date(DateTime?): Defines the current date selection. The default value is null.

Methods
DateTime Picker for Xamarin allows you to clear the selected date/time through its ClearSelection
method

Example
XAML
<StackLayout>
<Button Text="Clear Selection" Clicked="OnClearSelectionClicked"/>
<telerikInput:RadDateTimePicker x:Name="dateTimePicker"/>
</StackLayout>
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

Call ClearSelection inside the button click event - as a result Date property will be updated to null.

C#
private void OnClearSelectionClicked(object sender, EventArgs e)
{
this.dateTimePicker.ClearSelection();
}
 

Events
RadDateTime Picker exposes a SelectionChanged event which is raised when the user pick the
selected date/time.

Example

1023
Telerik UI for Xamarin

XAML
<telerikInput:RadDateTimePicker
SelectionChanged="RadDateTimePicker_SelectionChanged"/>
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

and the SelectionChanged event, where the sender is the RadDateTimePicker control:

C#
private void RadDateTimePicker_SelectionChanged(object sender, EventArgs e)
{
// implement your logic here
}
 

See Also
 Key Features
 Templates
 Commands

1024
Telerik UI for Xamarin

Commands
DateTimePicker Commands
DateTime Picker for Xamarin exposes the following commands you can use to programmatically
manipulate displaying the popup as well as clearing the selected time:

 ToggleCommand(ICommand): Allows you to show/hide the popup used for selecting a date
value.
 ClearCommand(ICommand): Allows you to clear the displayed date/time.

Example for ToggleCommand and ClearCommand


XAML
<StackLayout>
<Button Text="Toggle Command" Command="{Binding Source={x:Reference
dateTimePicker}, Path=ToggleCommand}"/>
<Button Text="Clear Command" Command="{Binding Source={x:Reference
dateTimePicker}, Path=ClearCommand}"/>
<telerikInput:RadDateTimePicker x:Name="dateTimePicker" />
</StackLayout>
 

also you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

PopupSelector Commands
Through the popup users can pick a date. The date/time value should be confirmed or rejected
through the OK and Cancel buttons placed on the popup.

DateTimePicker allows you to add a custom logic for the Accept and Cancel commands which are
executed when OK and Cancel buttons, respectively, are pressed.

 AcceptCommand(ICommand): Defines the command which confirms the current selection of


the picker and closes the popup. AcceptCommandParameter can be used to pass a
parameter to the command execute method.
 CancelCommand(ICommand): Defines the command which rejects the current selection of
the picker and closes the popup. CancelCommandParameter can be used to pass a
parameter to the command execute method.

The Accept and Cancel commands can be applied using the SelectorSettings property of

1025
Telerik UI for Xamarin

RadDateTimePicker. In addition, you can pass command parameters through the


AcceptCommandParameter and CancelCommandParameter properties of the DateTimePicker
SelectorSettings.

Here is a quick example on how they could be set:

Example for AcceptCommand and CancelCommand


XAML
<telerikInput:RadDateTimePicker x:Name="dateTimePicker">
<telerikInput:RadDateTimePicker.SelectorSettings>
<telerikInput:PickerPopupSelectorSettings AcceptCommand="{Binding Accept}"
AcceptCommandParameter="{Binding Date, Source={x:Reference dateTimePicker}}"
CancelCommand="{Binding Cancel}"
CancelCommandParameter="{Binding Date, Source={x:Reference dateTimePicker}}"/>
</telerikInput:RadDateTimePicker.SelectorSettings>
<telerikInput:RadDateTimePicker.BindingContext>
<local:ViewModel/>
</telerikInput:RadDateTimePicker.BindingContext>
</telerikInput:RadDateTimePicker>
 

and the ViewModel

C#
public class ViewModel
{
public ICommand Accept { get; set; }
public ICommand Cancel { get; set; }

public ViewModel()
{
this.Accept = new Command(this.OnAccept);
this.Cancel = new Command(this.OnCancel);
}

private void OnAccept(object param)


{
Application.Current.MainPage.DisplayAlert("Date selected", String.Format("New
Date: {0:g}", (DateTime)param), "OK");
// implement your custom logic here
}

private void OnCancel(object param)


{
var message = param != null ? String.Format("Current date: {0:g}",
(DateTime)param) : "Currently no date is selected";
Application.Current.MainPage.DisplayAlert("Date Selection Canceled", message,
"OK");
// implement your custom logic here
}
}

1026
Telerik UI for Xamarin

also you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

See Also
 Key Features
 Templates
 Selection

1027
Telerik UI for Xamarin

Styling
DateTimePicker Styling
Date and Time Picker control for Xamarin provides the following Style properties for customizing its
look:

 SpinnerStyle(of type Style with target type telerikDataControls:RadSpinner): Defines the


style applied to the spinner item and selected item.
 SpinnerHeaderStyle(of type Style with target type Xamarin.Forms.Label): Specifies the style
applied to the spinner header labels.
 SelectionHighlightStyle(of type Style with target type telerikPrimitives:RadBorder): Specifies
the style applied to the selection inside the popup.
 PlaceholderLabelStyle(of type Style with target type Xamarin.Forms.Label): Defines the style
applied to the placeholder label.
 DisplayLabelStyle(of type Style with target type Xamarin.Forms.Label): Defines the style
applied to the label which is visualized when date/time is selected.
 TabStripStyle(of type Style with target type telerikPrimitives:TabViewHeader)
 TabStripItemStyle(of type Style with target type telerikInput:DateTimeSelectorTabStripItem)

PickerContentView class exposes the following properties for styling the DateTimePicker Border and
Background Color:

 BackgroundColor(Xamarin.Forms.Color): Defines the background color of the picker.


 BorderColor(Xamarin.Forms.Color): Defines the border color of the picker.
 BorderThickness(Xamarin.Forms.Thickness): Specifies the border thickness of the picker.
Default value is new Thickness(0,0,0,1).
 CornerRadius(Xamarin.Forms.Thinckness): Specifies the corner radius of the picker.

Popup Styling
Using the SelectorSettings property (of type
Telerik.XamarinForms.Input.PickerPopupSelectorSettings) of the DateTimePicker you can modify
the appearance of the dialog (popup). PickerPopupSelectorSettings class exposes the following
Style properties:

 PopupViewStyle(of type Style with target type telerikInput:PickerPopupContentView):


Defines the popup view style.
 HeaderStyle(of type Style with target type telerikInput:PickerPopupHeaderView): Defines the
popup header style.
 HeaderLabelStyle(of type Style with target type Xamarin.Forms.Label): Defines the popup
header label style.
 FooterStyle(of type Style with target type telerikInput:PickerPopupFooterView): Defines the
popup footer style.
 AcceptButtonStyle(of type Style with target type Xamarin.Forms.Button): Defines the Accept
button style.
 CancelButtonStyle(of type Style with target type Xamarin.Forms.Button): Defines the Cancel

1028
Telerik UI for Xamarin

button style.

The SelectorSetting also provides the following properties for popup customization:

 PopupOutsideBackgroundColor(Xamarin.Forms.Color): Defines the color outside of the


popup.
 IsPopupModal(bool): Defines a boolean value indicating if the popup should be closed when
tapped outside of the popup. By default the value of the IsPopupModal is false.
 When IsPopupModal="True" the UI behind the popup gets inactive and cannot be used
until the popup is closed.
 When IsPopupModal="False" the popup could be closed when clicking outside the
popup.
 HeaderLabelText(string): Specifies the text visualized in the popup header.
 IsHeaderVisible(bool): Specifies whether the Popup header is currently visible. By default the
valuse is False.
 IsFooterVisible(bool): Specifies whether the Popup footer is currently visible. By default the
valuse is True.
 AcceptButtonText(string): Defines the text visualized for the accept button. By default the text
is OK.
 CancelButtonText(string): Defines the text visualized for the cancel button. By default the text
is Cancel.

Namespaces
Using TabStripItemStyle, PopupViewStyle, HeaderStyle, FooterStyle you will need to add the
following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

Using SelectionHighlightStyle, TabStripStyle you need to add the following namespace:

XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
 

Using SpinnerStyle you need to add the following namespace:

XAML
xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te
lerik.XamarinForms.DataControls"
 

Example
Here is a sample example that shows how the styling properties are applied.

1029
Telerik UI for Xamarin

A sample DateTime Picker definition:

XAML
<telerikInput:RadDateTimePicker SpinnerHeaderStyle="{StaticResource
spinnerHeaderStyle}"
SpinnerStyle="{StaticResource spinnerStyle}"
SelectionHighlightStyle="{StaticResource selectionHighlightStyle}"
SpinnerFormat="d"
AreSpinnerHeadersVisible="True"
DisplayLabelStyle="{StaticResource displayLabelStyle}"
PlaceholderLabelStyle="{StaticResource placeholderLabelStyle}">
<telerikInput:RadDateTimePicker.SelectorSettings>
<telerikInput:PickerPopupSelectorSettings
PopupOutsideBackgroundColor="#D9D9D9CC"
PopupViewStyle="{StaticResource popupViewStyle}"
HeaderStyle="{StaticResource headerStyle}"
HeaderLabelText="Date Picker"
HeaderLabelStyle="{StaticResource headerLabelStyle}"
FooterStyle="{StaticResource footerStyle}"
AcceptButtonStyle="{StaticResource acceptButtonStyle}"
CancelButtonStyle="{StaticResource cancelButtonStyle}"/>
</telerikInput:RadDateTimePicker.SelectorSettings>
</telerikInput:RadDateTimePicker>
 

and here are how the styles are defined in the page resources

Spinner Style
XAML
<Style TargetType="telerikDataControls:RadSpinner" x:Key="spinnerStyle">
<Setter Property="ItemStyle">
<Setter.Value>
<Style TargetType="telerikDataControls:SpinnerItemView">
<Setter Property="TextColor" Value="#4A4949"/>
</Style>
</Setter.Value>
</Setter>
<Setter Property="SelectedItemStyle">
<Setter.Value>
<Style TargetType="telerikDataControls:SpinnerItemView">
<Setter Property="TextColor" Value="Black"/>
<Setter Property="FontAttributes" Value="Bold"/>
</Style>
</Setter.Value>
</Setter>
</Style>
 

SpinnerHeader Style

1030
Telerik UI for Xamarin

XAML
<Style TargetType="Label" x:Key="spinnerHeaderStyle">
<Setter Property="TextColor" Value="Black"/>
<Setter Property="FontAttributes" Value="Bold"/>
<Setter Property="HorizontalOptions" Value="FillAndExpand"/>
<Setter Property="VerticalOptions" Value="FillAndExpand"/>
<Setter Property="HorizontalTextAlignment" Value="Center"/>
<Setter Property="VerticalTextAlignment" Value="Center"/>
</Style>
 

SelectionHighlight Style
XAML
<Style TargetType="telerikPrimitives:RadBorder" x:Key="selectionHighlightStyle">
<Setter Property="BackgroundColor" Value="Transparent"/>
<Setter Property="BorderColor" Value="#00B5DC"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Padding" Value="0,6,0,6"/>
<Setter Property="HeightRequest" Value="40"/>
<Setter Property="VerticalOptions" Value="Center"/>
</Style>
 

PlaceholderLabel Style
XAML
<Style TargetType="Label" x:Key="placeholderLabelStyle">
<Setter Property="TextColor" Value="#4A4949"/>
<Setter Property="VerticalTextAlignment" Value="Center"/>
<Setter Property="HorizontalTextAlignment" Value="Center"/>
<Setter Property="HeightRequest" Value="50"/>
</Style>
 

DisplayLabel Style
XAML
<Style TargetType="Label" x:Key="displayLabelStyle">
<Setter Property="TextColor" Value="Black"/>
<Setter Property="VerticalTextAlignment" Value="Center"/>
<Setter Property="HorizontalTextAlignment" Value="Center"/>
<Setter Property="HeightRequest" Value="50"/>
</Style>
 

PopupView Style

1031
Telerik UI for Xamarin

XAML
<Style TargetType="telerikInput:PickerPopupContentView" x:Key="popupViewStyle">
<Setter Property="BackgroundColor" Value="White"/>
<Setter Property="WidthRequest" Value="270"/>
</Style>
 

Header Style
XAML
<Style TargetType="telerikInput:PickerPopupHeaderView" x:Key="headerStyle">
<Setter Property="BackgroundColor" Value="#00B5DC"/>
<Setter Property="HeightRequest" Value="60"/>
<Setter Property="Margin" Value="0"/>
<Setter Property="Padding" Value="0"/>
<Setter Property="HorizontalOptions" Value="FillAndExpand"/>
<Setter Property="VerticalOptions" Value="FillAndExpand"/>
</Style>
 

HeaderLabel Style
XAML
<Style TargetType="Label" x:Key="headerLabelStyle">
<Setter Property="TextColor" Value="White"/>
<Setter Property="HorizontalOptions" Value="Center"/>
<Setter Property="VerticalOptions" Value="Center"/>
<Setter Property="FontSize" Value="Title"/>
</Style>
 

Footer Style
XAML
<Style TargetType="telerikInput:PickerPopupFooterView" x:Key="footerStyle">
<Setter Property="BackgroundColor" Value="Transparent"/>
</Style>
 

AcceptButton Style
XAML
<Style TargetType="Button" x:Key="acceptButtonStyle">
<Setter Property="BackgroundColor" Value="Transparent"/>
<Setter Property="Text" Value="OK"/>
<Setter Property="TextColor" Value="#00B5DC"/>
</Style>
 

1032
Telerik UI for Xamarin

CancelButton Style
XAML
<Style TargetType="Button" x:Key="cancelButtonStyle">
<Setter Property="BackgroundColor" Value="Transparent"/>
<Setter Property="Text" Value="X"/>
<Setter Property="TextColor" Value="#00B5DC"/>
</Style>
 

Namespaces
In addition, add the following namespaces:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te
lerik.XamarinForms.DataControls"
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
 

This is how the Date and Time Picker control looks when the styles described above are applied:

A sample Styling example can be found in the DateTimePicker/Features folder of the SDK Samples
Browser application.

1033
Telerik UI for Xamarin

See Also
 Key Features
 Custom Templates
 Commands
 Visual Structure

1034
Telerik UI for Xamarin

Overview
Telerik RadDockLayout for Xamarin is a layout that provides a mechanism for child elements to be
docked to the left, right, top or bottom edge or to occupy the center area of the layout.

Figure 1: RadDockLayout Overview

Key features
 Docking functionality: You could easily set the position of each child element inside the
layout through RadDockLayout.Dock attached property. For more details on this check here.
 Positioning a child element inside the remaining area of the layout: By default, the last
element inside the DockLayout stretches along the remaining space not occupied by the
other child elements. You can prevent this behavior by applying StretchLastChild property of
the DockLayout control. Go here for more information regarding this.

See Also
 Getting Started

1035
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadDockLayout control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadDockLayout control

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadDockLayout control you have to install the
Telerik.UI.for.Xamarin.Common nuget package.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadDockLayout component:

Platform Assemblies
Portable Telerik.XamarinForms.Common.dll
Android Telerik.Xamarin.Android.Common.dll
Telerik.XamarinForms.Common.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Common.dll
UWP Telerik.XamarinForms.Common.dll

3. Adding RadDockLayout control


You could use one of the following approaches:

Drag the control from the Toolbox.

1036
Telerik UI for Xamarin

Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML or C#.

The snippet below shows a simple RadDockLayout definition:

XAML
<telerikCommon:RadDockLayout x:Name="dockLayout">
<Grid HeightRequest="60"
BackgroundColor="#009688"
telerikCommon:RadDockLayout.Dock="Top">
<Label Margin="20" Text="Title"/>
</Grid>
<Grid HeightRequest="60"
BackgroundColor="#659BFC"
telerikCommon:RadDockLayout.Dock="Left">
<Label Margin="20" Text="Navigation" />
</Grid>
<Grid WidthRequest="120"
BackgroundColor="#1455C9"
telerikCommon:RadDockLayout.Dock="Bottom">
<Label Margin="20" Text="Bottom" />
</Grid>
<Grid HeightRequest="60"
BackgroundColor="#FCCFB0">
<Label Margin="20" Text="Content" />
</Grid>
</telerikCommon:RadDockLayout>
 

C#
var dockLayout = new RadDockLayout();

var topGrid = new Grid { HeightRequest = 60, BackgroundColor =


Color.FromHex("009688")};
topGrid.Children.Add(new Label { Margin = 20, Text = "Title" });
topGrid.SetValue(RadDockLayout.DockProperty, Dock.Top);
dockLayout.Children.Add(topGrid);

var leftGrid = new Grid { HeightRequest = 60, BackgroundColor =


Color.FromHex("659BFC")};
leftGrid.Children.Add(new Label { Margin = 20, Text = "Navigation" });
leftGrid.SetValue(RadDockLayout.DockProperty, Dock.Left);
dockLayout.Children.Add(leftGrid);

var bottomGrid = new Grid { WidthRequest = 120, BackgroundColor =


Color.FromHex("1455C9")};
bottomGrid.Children.Add(new Label { Margin = 20, Text = "Bottom" });
bottomGrid.SetValue(RadDockLayout.DockProperty, Dock.Bottom);

1037
Telerik UI for Xamarin

dockLayout.Children.Add(bottomGrid);

var lastGrid = new Grid { HeightRequest = 60, BackgroundColor =


Color.FromHex("FCCFB0")};
lastGrid.Children.Add(new Label { Margin = 20, Text = "Content" });
dockLayout.Children.Add(lastGrid);
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikCommon="clr-namespace:Telerik.XamarinForms.Common;assembly=Telerik.Xamari
nForms.Common"
 

C#
using Telerik.XamarinForms.Common;
 

This is the result:

SDK Browser and QSF applications contain different examples that show RadDockLayout's main
features. You can find the applications in the Examples and QSF folders of your local Telerik UI for
Xamarin installation.
 

See Also

1038
Telerik UI for Xamarin

 Key Features

1039
Telerik UI for Xamarin

Key Features
The purpose of this help article is to show you the key features of the RadDockLayout control.

Docking functionality
To define the docking side of a child element inside the dock layout component, use
RadDockLayout.Dock attached property which receives any of the following values:

 Left
 Top
 Right
 Bottom

The way the child elements are docked and arranged depends on their order inside the
DockLayout’s Children collection (the order they’re defined in XAML).

Following is a quick example on how you could utilize the docking functionality:

XAML
<telerikCommon:RadDockLayout x:Name="dockLayout">
<Label Text="Left" telerikCommon:RadDockLayout.Dock="Left" WidthRequest="60"
BackgroundColor="LightPink" />
<Label Text="Top" telerikCommon:RadDockLayout.Dock="Top" HeightRequest="60"
BackgroundColor="LightGreen" />
<Label Text="Right" telerikCommon:RadDockLayout.Dock="Right" WidthRequest="60"
BackgroundColor="LightBlue" />
<Label Text="Bottom" telerikCommon:RadDockLayout.Dock="Bottom" HeightRequest="60"
BackgroundColor="LightYellow" />
</telerikCommon:RadDockLayout>
 

Check the result on different platforms below:

1040
Telerik UI for Xamarin

Position a child element inside the remaining area of the


layout
By default, the last element inside the DockLayout stretches along the remaining space not occupied
by the other child elements. You can prevent this behavior by setting StretchLastChild property of
the DockLayout control to False. Check the example below how it would work when set to False:

XAML
<telerikCommon:RadDockLayout x:Name="dockLayout" StretchLastChild="False">
<Label Text="Left" telerikCommon:RadDockLayout.Dock="Left" WidthRequest="60"
BackgroundColor="LightPink" />
<Label Text="Top" telerikCommon:RadDockLayout.Dock="Top" HeightRequest="60"
BackgroundColor="LightGreen" />
<Label Text="Right" telerikCommon:RadDockLayout.Dock="Right" WidthRequest="60"
BackgroundColor="LightBlue" />
<Label Text="Bottom" telerikCommon:RadDockLayout.Dock="Bottom" HeightRequest="60"
BackgroundColor="LightYellow" />
</telerikCommon:RadDockLayout>
 

And here is how it looks:

1041
Telerik UI for Xamarin

Position multiple elements on one side


Setting the same docking side to a few child elements will arrange them according to their order
inside the DockLayout’s Children collection.

XAML
<telerikCommon:RadDockLayout x:Name="dockLayout">
<Label Text="Left 1" telerikCommon:RadDockLayout.Dock="Left" WidthRequest="60"
BackgroundColor="LightPink" />
<Label Text="Left 2" telerikCommon:RadDockLayout.Dock="Left" WidthRequest="60"
BackgroundColor="LightGreen" />
<Label Text="Left 3" telerikCommon:RadDockLayout.Dock="Left" WidthRequest="60"
BackgroundColor="LightBlue" />
<Label Text="Last Child" telerikCommon:RadDockLayout.Dock="Left" WidthRequest="60"
BackgroundColor="LightYellow" />
</telerikCommon:RadDockLayout>
 

And the result is:

1042
Telerik UI for Xamarin

See Also
 Getting Started

1043
Telerik UI for Xamarin

Overview
RadEntry is a text input control that accepts string input and provides a look and feel consistent with
the rest of the Telerik UI for Xamarin components through an innovative theming mechanism.

If you are new to RadEntry, see the Getting Started guide that demonstrates how to add the control
to your application.

Figure 1: RadEntry Overview

Key features
 Watermark: RadEntry allows you to add a hint text as a placeholder in the control. You can
use this text to guide the users what is the expected input. For more details, see the Key
Features article.
 Password functionality: You can hide the characters that users type for privacy and security
reasons. For more details, see the Key Features article.
 Keyboard support: You can add a virtual keyboard and specify its type, for example,
Numeric.
 Non-Editable (Read-Only) state: Using a single property - IsReadOnly, you can specify
whether the RadEntry control can be edited or not. Example and explanation can be found in
Key Features - Read-Only State.
 You can define the maximum number of symbols allowed in the RadEntry control. For
detailed explanation and example check the Key Features - Max Length section.
 Border styles: RadEntry gives you the option to customize the look of the border around the
input by using the BorderStyle property. For more details, see the Key Features.

1044
Telerik UI for Xamarin

See Also
 Getting Started
 Key Features
 Events

1045
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadEntry control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadEntry control

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadEntry control you have to install the Telerik.UI.for.Xamarin.Input
nuget package. This nuget will automatically refer the Telerik.UI.for.Xamarin.Primitives,
Telerik.UI.for.Xamarin.Common, and Telerik.UI.for.Xamarin.DataControls nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadEntry component:

Platform Assemblies
Portable Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll
Android Telerik.Xamarin.Android.Common.dll
Telerik.Xamarin.Android.Data.dll
Telerik.Xamarin.Android.Input.dll
Telerik.Xamarin.Android.List.dll
Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll

1046
Telerik UI for Xamarin

UWP Telerik.Core.dll
Telerik.Data.dll
Telerik.UI.Xaml.Controls.Data.UWP.dll
Telerik.UI.Xaml.Input.UWP.dll
Telerik.UI.Xaml.Primitives.UWP.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll

3. Adding RadEntry control


You could use one of the following approaches:

Drag the control from the Toolbox.

Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML or C#.

The snippet below shows a simple RadEntry definition:

XAML
<telerikInput:RadEntry x:Name="entry" WatermarkText="Enter first name"/>
 

C#
var entry = new RadEntry();
 

In addition to this you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

C#
using Telerik.XamarinForms.Input;
 

Here is the result:

1047
Telerik UI for Xamarin

The SDK Browser and QSF applications contain different examples that show RadEntry's main
features. You can find the applications in the Examples and QSF folders of your local Telerik UI for
Xamarin installation.
 

See Also
 Key Features
 Events
 Theming and Style

1048
Telerik UI for Xamarin

Key Features
The purpose of this help article is to show you the key features of the RadEntry control.

Text
The following properties are related to the Entry Text appearance and alignment:

 Text(string): Defines the Text;


 TextColor(Color): Defines the color of the visible text of the RadEntry control.
 VerticalTextAlignment(of type Xamarin.Forms.Textalignment): Specifies the vertical
alignment of the RadEntry.Text;
 HorizontalTextAlignment(of type Xamarin.Forms.Textalignment): Specifies the horizontal
alignment of the RadEntry.Text;
 Padding(Thickness): Defines the Padding of the text;

Watermark
RadEntry exposes WatermarkText(string) property used to give guidance to the end user on what
should be entered in the text input. The watermark text is displayed when the control is empty.
Additionally, you could set WatermarkTextColor(Color) to customize the look of the watermark text.

XAML
<telerikInput:RadEntry WatermarkText="First Name" WatermarkTextColor="#6EA3FF" />
 

Where:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

Password
RadEntry provides IsPassword(bool) property, which when set to True, replaces the input with
password hint character.

With Telerik UI for Xamarin version 2021.1.409.1 we have added an additional feature to the
RadEntry control - The suggestion tab that is above the keyboard is hidden when
IsPassword="True".
 
XAML
<telerikInput:RadEntry IsPassword="True" />
 

1049
Telerik UI for Xamarin

Read-Only State
With R1 2021 Service Pack, RadEntry control provides a feature which allows you to choose
whether the control will be editable or not - Read-Only state.

 IsReadOnly bool property: Specifies whether the control will be in edit mode. The default
value is False. If you want to restrict the control from editing, set the IsReadOnly to True

Example
XAML
<telerikInput:RadEntry x:Name="telerikEntry" Text="Telerik UI for Xamarin Entry
control" IsReadOnly="True"/>
 

You can find a working demo labeled Read-Only State in the Entry/Features folder of the SDK
Samples Browser application.
 

Max Length
From r1 2021 Service Pack, the Radentry control has an additional feature, you can restrict the
number of the symbols allowed to be entered in the input field.

 MaxLength (int) property: Specifies the maximum number of symbols allowed to be entered.

Example with MaxLength set to 10


XAML
<telerikInput:RadEntry x:Name="telerikEntry" WatermarkText="Enter text" MaxLength="10"
/>
 

You can find a working demo labeled Max Length in the Entry/Features folder of the SDK Samples
Browser application.
 

Keyboard
The Keyboard property of type Xamarin.Forms.Keyboard allows you to define the type of the
keyboard that will be visualized by the device.

XAML
<telerikInput:RadEntry x:Name="entry"
Keyboard="Numeric"
WatermarkText="Watermark Text" />
 

1050
Telerik UI for Xamarin

Text Selection
The following properties are related to the Entry text selection:

 CursorPosition(int) Specifies the starting position of the text selected in the entry.
 SelectionLength(int) Specifies the number of characters in the current selection in the entry
control.

The next snippet shows how both could be applied in order to preselect part of the Text of the Entry
when the control receives the focus:

XAML
<StackLayout Orientation="Horizontal">
<telerikInput:RadEntry x:Name="selectEntry" Text="select some text" />
<telerikInput:RadButton Text="Focus" Clicked="FocusButtonClicked" />
</StackLayout>
 

And the Clicked event handler:

C#
private void FocusButtonClicked(object sender, System.EventArgs e)
{
selectEntry.Focus();
selectEntry.CursorPosition = 7;
selectEntry.SelectionLength = 9;
}
 

Here is the end result:

1051
Telerik UI for Xamarin

Font Options:
RadEntry control has the following properties for defining the Font Options:

 FontAttributes
 FontFamily
 FontSize

XAML
<StackLayout>
<telerikInput:RadEntry Text="Normal Text" x:Name="entry"/>
<telerikInput:RadEntry Text="Bold Text - Large" FontAttributes="Bold"
FontSize="Large" />
<telerikInput:RadEntry Text="Italic Text - Medium" FontAttributes="Italic"
FontSize="Medium"/>
<telerikInput:RadEntry Text="Italic and Bold Text - Small" FontSize="Small"
x:Name="smallEntry"/>
<telerikInput:RadEntry Text="Micro Text" FontSize="Micro" />
</StackLayout>
 

You can find a working demo labeled Key Features in the Entry/Features folder of the SDK Samples
Browser application.
 
For a full list of the provided properties of RadEntry, check its API reference here: RadEntry
Properties.
 

1052
Telerik UI for Xamarin

See Also
 Events
 Theming and Style
 Getting Started

1053
Telerik UI for Xamarin

Events
RadEntry exposes the following events:

 TextChanged: Occurs when the text is changed. The TextChanged event handler receives a
TextChangedEventArgs argument containing data related to this event. The
TextChangedEventArgs provides the following properties:
 NewTextValue(string): which gets the new text value.
 OldTextValue(string): that gets the old text value.
 Completed: Occurs when the user finalizes the text in an entry with the return key.

Commands
RadEntry control exposes Command for its Completed event: CompletedCommand(ICommand).

Example
Here is the RadEntry definition in XAML with the TextChanged and Completed event handlers:

XAML
<StackLayout>
<telerikInput:RadEntry x:Name="entry"
Keyboard="Numeric"
WatermarkText="Watermark Text"
TextChanged="Entry_TextChanged"
Completed="Entry_Completed"/>
<Label x:Name="textChangedLabel"/>
</StackLayout>
 

Here is a sample implementation of the TexhChanged event:

C#
private void Entry_TextChanged(object sender, TextChangedEventArgs e)
{
this.textChangedLabel.Text = $"Text changed from {e.OldTextValue} to
{e.NewTextValue}";
}
 

and for the Completed event:

C#
private void Entry_Completed(object sender, EventArgs e)
{
this.textChangedLabel.Text = "User completed entering text";
}

1054
Telerik UI for Xamarin

You can find a working demo labeled Events in the Entry/Features folder of the SDK Samples
Browser application.
 

See Also
 Entry Getting Started
 Entry Theming and Style

1055
Telerik UI for Xamarin

Theming and Style


BorderStyle
The BorderStyle(of type Telerik.XamarinForms.Input.BorderStyle) property allows you to customize
the border around the Entry through the following properties:

 BorderColor(Color),
 BorderThickness(Thickness)
 CornerRadius(double)

You could define the BorderStyle in the Resources of your page as shown in the example below:

XAML
<telerikInput:BorderStyle x:Key="EntryBorderStyle" BorderThickness="1"
BorderColor="#4488F6" CornerRadius="8" />
 

And then apply that Style to the Entry instance:

XAML
<telerikInput:RadEntry x:Name="entry" WatermarkText="First Name"
BorderStyle="{StaticResource EntryBorderStyle}"/>
 

Theming
You can find a working demo labeled Theme in the Entry/Features folder of the SDK Samples
Browser application.
 

See Also
 Key Features
 Events

1056
Telerik UI for Xamarin

Overview
Telerik Expander for Xamarin helps you save screen space by presenting content in an expandable
container that can be easily expanded/collapsed by tapping on the header of the control.

Figure 1: RadExpander Overview

Key features
 Collapsed/expanded states: RadExpander provides an expandable area which can host
content of your choice. The end users could show or hide this content by interacting with the
Header of the control.
 Highly customizable Header: You have full control over the visual appearance of the Header
of the control, for more info on this check here.
 Animation while expanding/collapsing: RadExpander provides slick customizable animation
played while the expandable content is expanded/collapsed, for additional info go here.
 Border Styling: You could apply various Border color and thickness of RadExpander to make
it consistent with the design of your app.
 Theming: RadExpander comes with built-in theming support that allows you to easily build
slick interfaces with the look-and-feel of a predefined theme.

See Also
 Getting Started

1057
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadExpander control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadExpander control

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadExpander control you have to install the
Telerik.UI.for.Xamarin.Primitives nuget package. This nuget will automatically refer the
Telerik.UI.for.Xamarin.Common and Telerik.UI.for.Xamarin.SkiaSharp nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadExpander component:

Platform Assemblies
Portable Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Android Telerik.Xamarin.Android.Common.dll
Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
UWP Telerik.Core.dll
Telerik.UI.Xaml.Primitives.UWP.dll
Telerik.XamarinForms.Common.dll

1058
Telerik UI for Xamarin

Telerik.XamarinForms.Primitives.dll

3. Adding RadExpander control


You could use one of the following approaches:

Drag the control from the Toolbox.

Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML or C#.

The snippet below shows a simple RadExpander definition:

XAML
<telerikPrimitives:RadExpander x:Name="expander" HeaderText="More Options">
<telerikPrimitives:RadExpander.Content>
<StackLayout Margin="10, 20, 10, 20">
<StackLayout Orientation="Horizontal" Spacing="10">
<telerikPrimitives:RadCheckBox />
<Label Text="Make my profile private" />
</StackLayout>
<StackLayout Orientation="Horizontal" Spacing="10">
<telerikPrimitives:RadCheckBox />
<Label Text="Only show my posts to people who follow me" />
</StackLayout>
</StackLayout>
</telerikPrimitives:RadExpander.Content>
</telerikPrimitives:RadExpander>
 

C#
var expander = new RadExpander { HeaderText = "More Options" };

var stackContainer = new StackLayout { Margin = new Thickness(10, 20, 10, 20) };
var firstCheckboxStack = new StackLayout { Orientation = StackOrientation.Horizontal,
Margin = new Thickness(10) };
firstCheckboxStack.Children.Add(new RadCheckBox());
firstCheckboxStack.Children.Add(new Label { Text = "Make my profile private" });
stackContainer.Children.Add(firstCheckboxStack);

var secondCheckboxStack = new StackLayout { Orientation = StackOrientation.Horizontal,


Margin = new Thickness(10, 20, 10, 20) };
secondCheckboxStack.Children.Add(new RadCheckBox());
secondCheckboxStack.Children.Add(new Label { Text = "Only show my posts to people who
follow me" });
stackContainer.Children.Add(secondCheckboxStack);

1059
Telerik UI for Xamarin

expander.Content = stackContainer;
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
 

C#
using Telerik.XamarinForms.Primitives;
 

This is the result:

SDK Browser and QSF applications contain different examples that show RadExpander's main
features. You can find the applications in the Examples and QSF folders of your local Telerik UI for
Xamarin installation.
 

See Also
 Key Features

1060
Telerik UI for Xamarin

Key Features
The purpose of this help article is to show you the key features of the RadExpander control.

Collapsed/expanded States
RadExpander provides an expandable container which can host any content. You can show or hide
this content by interacting with the Header of the control. The default state of RadExpander is
collapsed.

You could use IsExpanded Boolean property to switch the current state of the control.

Expander Header
You could either apply HeaderText property or use the ExpanderHeader content control which
provides a set of useful properties for customizing the way the header looks. For more details refer
to ExpanderHeader control topic.

Additionally, you could place the Header at the top or at the bottom of the expandable container
through HeaderLocation property of type ExpanderHeaderLocation. The next snippet shows how the
HeaderLocation could be set to “Bottom”:

XAML
<telerikPrimitives:RadExpander x:Name="expander"
HeaderText="Read more"
HeaderLocation="Bottom">
<telerikPrimitives:RadExpander.Content>
<StackLayout Margin="10, 20, 10, 20">
<Label Text="You could place the Header at the top or at the bottom of the
expandable container." />
</StackLayout>
</telerikPrimitives:RadExpander.Content>
</telerikPrimitives:RadExpander>
 

And here is how it looks:

1061
Telerik UI for Xamarin

Animation while expanding/collapsing


To enable or disable the animation you need to use the IsAnimationEnabled property of
RadExpander. By default, the Animation is enabled.

You could also customize the duration and easing (acceleration over time) through
AnimationDuration(in ms) and AnimationEasing (of type Xamarin.Forms.Easing) properties.

Border Styling
You could apply BorderColor and BorderThickness properties of RadExpander to make it consistent
with the design of your app.

ExpanderHeader also provides means for customizing its border, you can learn more about this in
the ExpanderHeader: Border Styling article.
 
Check the example below on how the border settings could be defined:

XAML
<telerikPrimitives:RadExpander x:Name="expander"
HeaderText="Read more"
BorderColor="LightBlue"
BorderThickness="2">
<telerikPrimitives:RadExpander.Content>
<StackLayout Margin="10, 20, 10, 20">
<Label Text="You could apply BorderColor and BorderThickness properties of
RadExpander to make it consistent with the design of your app." />

1062
Telerik UI for Xamarin

</StackLayout>
</telerikPrimitives:RadExpander.Content>
</telerikPrimitives:RadExpander>
 

And the result is:

See Also
 Getting Started

1063
Telerik UI for Xamarin

ExpanderHeader control
ExpanderHeader represents the Header of the Expander control which is used to show or hide the
expandable container. ExpanderHeader provides a customizable Indicator to mark the current state
of the Expander as well as BorderColor and BorderThickness properties to style the Header per your
needs.

Indicator Options
The indicator is the little triangle that is rotated according to whether the Expander control is
expanded or collapsed. ExpanderHeader provides various options for customizing the look of the
indicator via the following properties:

 IndicatorText: The indicator is represented by a string symbol that could be changed through
IndicatorText property;
 IndicatorFontFamily: Specifies the indicator text FontFamily;
 IndicatorFontSize: Defines the indicator text font size;
 IndicatorColor: This property sets the color of the indicator;
 IndicatorLocation: This property is of type ExpandCollapseIndicatorLocation and is used to
place the indicator to the left or to the right inside the Header;
 IndicatorAnimationDuration: Specifies the duration of the rotation animation of the indicator;
 IndicatorAnimationEasing: Specifies the easing of the rotation animation of the indicator;
 IndicatorMargin: This property is of type Thickness and sets the margin applied to the
indicator;

Border Styling
You could apply BorderColor and BorderThickness properties of HeaderExpander to make it
consistent with the design of your app.

Example
Check the example below on how the Indicator options and border properties could be applied:

XAML
<telerikPrimitives:RadExpander x:Name="expander"
BorderColor="LightBlue"
BorderThickness="2">
<telerikPrimitives:RadExpander.Header>
<telerikPrimitives:ExpanderHeader
IndicatorText="&#x203A;"
IndicatorColor="Blue"
IndicatorFontFamily="Arial"
IndicatorFontSize="16"
IndicatorLocation="End"
IndicatorAnimationDuration="1000"

1064
Telerik UI for Xamarin

BorderColor="LightBlue"
BorderThickness="2">
<Label Text="More Options" />
</telerikPrimitives:ExpanderHeader>
</telerikPrimitives:RadExpander.Header>
<telerikPrimitives:RadExpander.Content>
<StackLayout Margin="10, 20, 10, 20">
<Label Text="RadExpander for Xamarin is a flexible content control that helps
you save screen space." />
</StackLayout>
</telerikPrimitives:RadExpander.Content>
</telerikPrimitives:RadExpander>
 

See Also
 Key Features

1065
Telerik UI for Xamarin

Overview
The RadGauge controls serve as instruments that indicate and give a visual display of amount, level,
or contents of something. These values are presented via indicators (needles, arrows, and others).
To give context to the indicated value (or values) the gauge uses an axis and gauge ranges. The
axis states a minimum and maximum which determine the allowed values. The gauge ranges denote
certain parts of the axis range and are usually displayed with different colors to provide additional
information. For example, in an axis range [0, 200] a Red gauge range [180, 200] can be added to
articulate that values within this range are too high.

Figure 1: RadGauge Overview

Key features
 Different display layouts: RadGauge is the code-name behind the RadRadialGauge,
RadHorizontalGauge and RadVerticalGauge controls. They give you the ability to display the
gauge scale using different layouts. Read more about the controls in the Gauge Types help

1066
Telerik UI for Xamarin

section.
 Linear axis: Linear scale distribution. Read more about the gauge's axis in the Axis article.
 Indicators: Built-in indicators (Arrow, Needle) that allow customization of the appearance,
including fill, stroke and shape. For more information check the Indicators article.
 Ranges: A collection of ranges that allows you to mark different parts of the scale. Check
here for more info.
 Animations: Smooth out of the box animations. Read more about this in the Animations
article.

See Also
 Getting Started
 Radial Gauge
 Horizontal Gauge
 Vertical Gauge

1067
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadGauge control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadGauge control
 Gauge types

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadGauge control you have to install the
Telerik.UI.for.Xamarin.DataVisualization nuget package. This nuget will automatically refer the
Telerik.UI.for.Xamarin.Common and Telerik.UI.for.Xamarin.SkiaSharp nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadGauge component:

Platform Assemblies
Portable Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataVisualization.dll
Telerik.XamarinForms.SkiaSharp.dll
Android Telerik.Xamarin.Android.Common.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataVisualization.dll
Telerik.XamarinForms.SkiaSharp.dll
iOS Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataVisualization.dll
Telerik.XamarinForms.SkiaSharp.dll
UWP Telerik.XamarinForms.Common.dll

1068
Telerik UI for Xamarin

Telerik.XamarinForms.DataVisualization.dll
Telerik.XamarinForms.SkiaSharp.dll

3. Adding RadGauge control


You could use one of the following approaches:

Drag the control from the Toolbox.

Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML or C#.

The snippet below shows a simple RadGauge definition:

XAML
<telerikGauges:RadRadialGauge x:Name="gauge">
<telerikGauges:RadRadialGauge.Axis>
<telerikGauges:GaugeLinearAxis Maximum="200"
Minimum="0"
Step="25" />
</telerikGauges:RadRadialGauge.Axis>
<telerikGauges:RadRadialGauge.Indicators>
<telerikGauges:GaugeNeedleIndicator Offset="30" Value="60" />
<telerikGauges:GaugeShapeIndicator Value="80" />
</telerikGauges:RadRadialGauge.Indicators>
<telerikGauges:RadRadialGauge.Ranges>
<telerikGauges:GaugeRangesDefinition>
<telerikGauges:GaugeRange Color="Green"
From="0"
To="150" />
<telerikGauges:GaugeGradientRange From="150" To="200">
<telerikCommon:RadGradientStop Offset="150" Color="Yellow" />
<telerikCommon:RadGradientStop Offset="200" Color="Red" />
</telerikGauges:GaugeGradientRange>
</telerikGauges:GaugeRangesDefinition>
</telerikGauges:RadRadialGauge.Ranges>
</telerikGauges:RadRadialGauge>
 

C#
RadRadialGauge gauge = new RadRadialGauge();
gauge.Axis = new GaugeLinearAxis { Minimum = 0, Maximum = 200, Step = 25 };
gauge.Indicators.Add(new GaugeNeedleIndicator { Value = 60, Offset = 30, });
gauge.Indicators.Add(new GaugeShapeIndicator { Value = 80 });
gauge.Ranges.Ranges.Add(new GaugeRange { From = 0, To = 150, Color = Color.Green });
GaugeGradientRange gradientRange = new GaugeGradientRange { From = 150, To = 200 };

1069
Telerik UI for Xamarin

gradientRange.GradientStops.Add(new RadGradientStop { Color = Color.Yellow, Offset =


150 });
gradientRange.GradientStops.Add(new RadGradientStop { Color = Color.Red, Offset = 200
});
gauge.Ranges.Ranges.Add(gradientRange);
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikCommon="clr-namespace:Telerik.XamarinForms.Common;assembly=Telerik.Xamari
nForms.Common"
xmlns:telerikGauges="clr-namespace:Telerik.XamarinForms.DataVisualization.Gauges;assem
bly=Telerik.XamarinForms.DataVisualization"
 

C#
using Telerik.XamarinForms.Common;
using Telerik.XamarinForms.DataVisualization.Gauges;
 

This is the result:

You can follow this tutorial to set up also the RadVerticalGauge and RadHorizontalGauge controls
which expose the same API.
 

Gauge types

1070
Telerik UI for Xamarin

There are 2 gauge types that you can use to display different layout - radial and linear (horizontal
and vertical). You can read more about these types at the listed articled below:

 Radial Gauge
 Horizontal Gauge
 Vertical Gauge

SDK Browser and QSF applications contain different examples that show Gauges' main features.
You can find the applications in the Examples and QSF folders of your local Telerik UI for Xamarin
installation.
 

See Also

 Axis
 Indicators
 Ranges

1071
Telerik UI for Xamarin

Radial Gauge
The RadRadialGauge control allows you to display the scale's range in a radial form.

Setting up the gauge


The following example shows a RadRadialGauge's basic set up.

XAML
<telerikGauges:RadRadialGauge x:Name="gauge">
<telerikGauges:RadRadialGauge.Axis>
<telerikGauges:GaugeLinearAxis Maximum="200"
Minimum="0"
Step="25" />
</telerikGauges:RadRadialGauge.Axis>
<telerikGauges:RadRadialGauge.Indicators>
<telerikGauges:GaugeNeedleIndicator Offset="30" Value="60" />
</telerikGauges:RadRadialGauge.Indicators>
<telerikGauges:RadRadialGauge.Ranges>
<telerikGauges:GaugeRangesDefinition>
<telerikGauges:GaugeRange Color="Green"
From="0"
To="150" />
<telerikGauges:GaugeGradientRange From="150" To="200">
<telerikCommon:RadGradientStop Offset="150" Color="Yellow" />
<telerikCommon:RadGradientStop Offset="200" Color="Red" />
</telerikGauges:GaugeGradientRange>
</telerikGauges:GaugeRangesDefinition>
</telerikGauges:RadRadialGauge.Ranges>
</telerikGauges:RadRadialGauge>
 

C#
RadRadialGauge radRadialGauge = new RadRadialGauge();
radRadialGauge.Axis = new GaugeLinearAxis() { Minimum = 0, Maximum = 200, Step = 25 };
radRadialGauge.Indicators.Add(new GaugeNeedleIndicator() { Value = 60, Offset = 30 });
GaugeRangesDefinition rangesDefinition = new GaugeRangesDefinition();
rangesDefinition.Ranges.Add(new GaugeRange() { From = 0, To = 150, Color = Color.Green
});
GaugeGradientRange gradientRange = new GaugeGradientRange() { From = 150, To = 200 };
gradientRange.GradientStops.Add(new RadGradientStop(Color.Yellow, 150));
gradientRange.GradientStops.Add(new RadGradientStop(Color.Red, 200));
rangesDefinition.Ranges.Add(gradientRange);
radRadialGauge.Ranges = rangesDefinition;
 

This is the result:

1072
Telerik UI for Xamarin

A sample Radial Gauge example can be found in the Gauge/GaugeTypes folder of the SDK Samples
Browser application.
 

Setting rotation and radius


The radial gauge allows you to define the radius of its axis. This can be done via the
AxisRadiusFactor property of RadRadialGauge. Read more about the property in the Positioning help
article.

You can also control the start angle, the sweep angle and sweep direction of the axis. This can be
done via the following properties:

 StartAngle: The start angle determines the origin position of the axis.
 SweepAngle: The sweep angle defines the size of the axis' arc. For example, if the start
angle is 90 and the sweep angle is 30, the axis will be drawn between the 90th and 120th
angle. If the sweep direction is counter-clockwise, the axis will be drawn between 60 and 90.
 SweepDirection: You can use this property to set the axis sweep direction - clockwise or
counter-clockwise.

See Also
 Horizontal Gauge
 Vertical Gauge
 Axis
 Indicators
 Ranges

1073
Telerik UI for Xamarin

Horizontal Gauge
The RadHorizontalGauge control allows you to display the scale's range in a linear form, horizontally
oriented.

Setting up the gauge


The following example shows a RadHorizontalGauge's basic set up.

XAML
<telerikGauges:RadHorizontalGauge x:Name="gauge">
<telerikGauges:RadHorizontalGauge.Axis>
<telerikGauges:GaugeLinearAxis Maximum="200"
Minimum="0"
Step="25" />
</telerikGauges:RadHorizontalGauge.Axis>
<telerikGauges:RadHorizontalGauge.Indicators>
<telerikGauges:GaugeShapeIndicator Value="90" />
</telerikGauges:RadHorizontalGauge.Indicators>
<telerikGauges:RadHorizontalGauge.Ranges>
<telerikGauges:GaugeRangesDefinition>
<telerikGauges:GaugeRange Color="Green"
From="0"
To="150" />
<telerikGauges:GaugeGradientRange From="150" To="200">
<telerikCommon:RadGradientStop Offset="150" Color="Yellow" />
<telerikCommon:RadGradientStop Offset="200" Color="Red" />
</telerikGauges:GaugeGradientRange>
</telerikGauges:GaugeRangesDefinition>
</telerikGauges:RadHorizontalGauge.Ranges>
</telerikGauges:RadHorizontalGauge>
 

C#
RadHorizontalGauge radHorizontalGauge = new RadHorizontalGauge();
radHorizontalGauge.Axis = new GaugeLinearAxis() { Minimum = 0, Maximum = 200, Step =
25 };
radHorizontalGauge.Indicators.Add(new GaugeShapeIndicator() { Value = 90 });
GaugeRangesDefinition rangesDefinition = new GaugeRangesDefinition();
rangesDefinition.Ranges.Add(new GaugeRange() { From = 0, To = 150, Color = Color.Green
});
GaugeGradientRange gradientRange = new GaugeGradientRange() { From = 150, To = 200 };
gradientRange.GradientStops.Add(new RadGradientStop(Color.Yellow, 150));
gradientRange.GradientStops.Add(new RadGradientStop(Color.Red, 200));
rangesDefinition.Ranges.Add(gradientRange);
radHorizontalGauge.Ranges = rangesDefinition;
 

Here is the result:

1074
Telerik UI for Xamarin

A sample Horizontal Gauge example can be found in the Gauge/GaugeTypes folder of the SDK
Samples Browser application.
 

See Also
 Radial Gauge
 Vertical Gauge
 Axis
 Indicators
 Ranges

1075
Telerik UI for Xamarin

Vertical Gauge
The RadVerticalGauge control allows you to display the scale's range in a linear form, vertically
oriented.

Setting up the gauge


The following example shows a RadVerticalGauge's basic set up.

XAML
<telerikGauges:RadVerticalGauge x:Name="gauge">
<telerikGauges:RadVerticalGauge.Axis>
<telerikGauges:GaugeLinearAxis Maximum="200"
Minimum="0"
Step="25" />
</telerikGauges:RadVerticalGauge.Axis>
<telerikGauges:RadVerticalGauge.Indicators>
<telerikGauges:GaugeShapeIndicator Value="90" />
</telerikGauges:RadVerticalGauge.Indicators>
<telerikGauges:RadVerticalGauge.Ranges>
<telerikGauges:GaugeRangesDefinition>
<telerikGauges:GaugeRange Color="Green"
From="0"
To="150" />
<telerikGauges:GaugeGradientRange From="150" To="200">
<telerikCommon:RadGradientStop Offset="150" Color="Yellow" />
<telerikCommon:RadGradientStop Offset="200" Color="Red" />
</telerikGauges:GaugeGradientRange>
</telerikGauges:GaugeRangesDefinition>
</telerikGauges:RadVerticalGauge.Ranges>
</telerikGauges:RadVerticalGauge>
 

C#
RadVerticalGauge radVerticalGauge = new RadVerticalGauge();
radVerticalGauge.Axis = new GaugeLinearAxis() { Minimum = 0, Maximum = 200, Step = 25
};
radVerticalGauge.Indicators.Add(new GaugeShapeIndicator() { Value = 90 });
GaugeRangesDefinition rangesDefinition = new GaugeRangesDefinition();
rangesDefinition.Ranges.Add(new GaugeRange() { From = 0, To = 150, Color = Color.Green
});
GaugeGradientRange gradientRange = new GaugeGradientRange() { From = 150, To = 200 };
gradientRange.GradientStops.Add(new RadGradientStop(Color.Yellow, 150));
gradientRange.GradientStops.Add(new RadGradientStop(Color.Red, 200));
rangesDefinition.Ranges.Add(gradientRange);
radVerticalGauge.Ranges = rangesDefinition;
 

Here is the result:

1076
Telerik UI for Xamarin

A sample Vertical Gauge example can be found in the Gauge/GaugeTypes folder of the SDK
Samples Browser application.
 

See Also
 Radial Gauge
 Horizontal Gauge
 Axis
 Indicators
 Ranges

1077
Telerik UI for Xamarin

Animations
All gauge indicators are being animated upon initial load and upon value change. The animations
are enabled by default and you have full control over them via the AnimationSettings property.

AnimationSettings property could be applied to the Gauge or separately to the indicators. By default
the property of the indicator is null and in this case the AnimationSettings property of the gauge is
taken into consideration. This allows you to control all animations by setting only one property - the
property of the gauge. If you need an indicator to be animated differently, you can set its
AnimationSettings property as it has a higher precedence than the gauge's property.

The AnimationSettings class contains the following properties:

 Duration (int): Defines the duration of the animation in milliseconds.


 Easing: Defines the easing of the animation.
 Enabled (bool): Specifies whether the animation will be enabled or not. By default the
Enabled property is true.

Example
Here is an example how to set the AnimationSettings property:

XAML
<telerikGauges:RadRadialGauge x:Name="gauge1"
Grid.Row="1"
Grid.Column="1">
<telerikGauges:RadRadialGauge.AnimationSettings>
<telerikCommon:AnimationSettings x:Name="gauge1Animations" Easing="CubicOut" />
</telerikGauges:RadRadialGauge.AnimationSettings>
<telerikGauges:RadRadialGauge.Axis>
<telerikGauges:GaugeLinearAxis Maximum="200"
Minimum="0"
Step="25" />
</telerikGauges:RadRadialGauge.Axis>
<telerikGauges:RadRadialGauge.Indicators>
<telerikGauges:GaugeShapeIndicator Value="80" />
<telerikGauges:GaugeBarIndicator Offset="30" Value="100" />
<telerikGauges:GaugeNeedleIndicator Fill="Blue"
Offset="30"
Value="120" />
</telerikGauges:RadRadialGauge.Indicators>
<telerikGauges:RadRadialGauge.Ranges>
<telerikGauges:GaugeRangesDefinition>
<telerikGauges:GaugeRange Color="Green"
From="0"
To="150" />
<telerikGauges:GaugeGradientRange From="150" To="200">
<telerikCommon:RadGradientStop Offset="150" Color="Yellow" />

1078
Telerik UI for Xamarin

<telerikCommon:RadGradientStop Offset="200" Color="Red" />


</telerikGauges:GaugeGradientRange>
</telerikGauges:GaugeRangesDefinition>
</telerikGauges:RadRadialGauge.Ranges>
</telerikGauges:RadRadialGauge>
 

Here is a gif animation that shows all animations provided in the Gauge control:

SDK Samples Browser application contains Animations example that shows how the
AnimationSettings property works. The example can be found in the Features section of the Gauge
control.
 

See Also

1079
Telerik UI for Xamarin

 Indicators
 Positioning
 Ranges

1080
Telerik UI for Xamarin

Gauge Axis
The axis is a gauge element that is used to control everything related to the display of the axis. This
includes ticks, labels, appearance and axis range.

Examples
Axis Range
Presently, the axis does not have an auto-range mechanism so it is mandatory that you set
Minimum, Maximum and Step.

XAML
<telerikGauges:GaugeLinearAxis Maximum="4"
Minimum="0"
Step="0.5" />
 

1081
Telerik UI for Xamarin

Appearance
You can control the stroke of the axis line and ticks via the Stroke property. If you need to have a
different color for the ticks you need to set the TickStroke property. Similarly, setting the
StrokeThickness affects both the axis line and ticks. If you need ticks with a different stroke
thickness you need to set the TickThickness property.

XAML
<telerikGauges:GaugeLinearAxis Maximum="4"
Minimum="0"
Step="0.5"
Stroke="#FFDD789B"
StrokeThickness="1"
TextColor="#FF4062AD"
TickStroke="#FFAAC271"
TickThickness="2" />
 

1082
Telerik UI for Xamarin

Font Style
You can control the appearance of the labels via the FontSize, FontFamily and FontAttributes
properties.

XAML
<telerikGauges:GaugeLinearAxis FontAttributes="Bold"
FontSize="30"
Maximum="4"
Minimum="0"
Step="0.5" />
 

1083
Telerik UI for Xamarin

FontFamily
Note that the FontFamily property is of type string and you need to pass the name of the font family.
Remember that the different platforms work with different fonts so you may need to use the
OnPlatform method.

XAML
<telerikGauges:GaugeLinearAxis Maximum="4"
Minimum="0"
Step="0.5">
<telerikGauges:GaugeLinearAxis.FontFamily>
<OnPlatform x:TypeArguments="x:String">
<OnPlatform.iOS>Helvetica</OnPlatform.iOS>
<OnPlatform.Android>sans-serif-light</OnPlatform.Android>
<OnPlatform.WinPhone>Comic Sans MS</OnPlatform.WinPhone>
</OnPlatform>
</telerikGauges:GaugeLinearAxis.FontFamily>
</telerikGauges:GaugeLinearAxis>
 

1084
Telerik UI for Xamarin

Label Format
You can control the numeric format of the content of the labels. The default label format is "G7".

XAML
<telerikGauges:GaugeLinearAxis LabelFormat="N2"
Maximum="4"
Minimum="0"
Step="0.5" />
 

1085
Telerik UI for Xamarin

Label And Tick Position


In the radial gauge, the gauge elements can be positioned on the inside or on the outside of the axis
line. Some of the elements, such as the ticks, can also be centered on the axis line. This is controled
by the Position property of the concrete element.

XAML
<telerikGauges:GaugeLinearAxis LabelPosition="Start"
Maximum="4"
Minimum="0"
Step="0.5"
TickPosition="Start" />
 

1086
Telerik UI for Xamarin

Offset And Length


The distance between the concrete element and the axis line is defined by an offset property (Offset,
TickOffset, LabelOffset). You can also specify the length of the ticks.

XAML
<telerikGauges:GaugeLinearAxis LabelOffset="8"
Maximum="4"
Minimum="0"
Step="0.5"
TickLength="3"
TickOffset="3" />
 

1087
Telerik UI for Xamarin

A sample Gauge Axis Customization example can be found in the Gauge/Customizations folder of
the SDK Samples Browser application.
 

See Also
 Indicators
 Positioning
 Ranges

1088
Telerik UI for Xamarin

Indicators
The gauge indicators are elements that display data related values in a different manner.

Needle Indicator
The GaugeNeedleIndicator is part of the radial gauge. It presents a single value set by the Value
property. The needle is intended to visually liken an actual gauge needle. The center of rotation of
the needle coincides with the center of the gauge and is directed towards where the value on the
gauge axis is. How far the tip of the needle gets is determined by its Position and Offset properties.

Custom Needle Indicator


You can use a custom shape for the needle by taking advantage of the Shape property. In order to
achieve the desired output you need to set up the geometry that describes the needle you want. The
gauge expects that these conditions are met when a shape geometry is set:

 The coordinates are relative values between 0 and 1.


 The rotation pivot point is (0.5, 0.5).
 The needle's orientation is from (0.5, 0.5) to (1, 0.5).

1089
Telerik UI for Xamarin

 
When the gauge draws the needle, the geometry is scaled to the size it will be displayed with. This
size is a result of the diameter of the axis arc, the needle's position and offset. It is then rotated so
that the needle points at the value. In the example below, the angle of rotation is 45 and in this case
coincides with the needle's value.

1090
Telerik UI for Xamarin

Here is an example of a custom needle shape:

1091
Telerik UI for Xamarin

XAML
<telerikCommon:RadPathGeometry x:Key="Needle3">
<telerikCommon:RadPathFigure StartPoint="0.533, 0.51">
<telerikCommon:RadLineSegment Point="1, 0.5" />
<telerikCommon:RadLineSegment Point="0.533, 0.49" />
<telerikCommon:RadArcSegment Center="0.5, 0.5"
Size="0.07, 0.07"
StartAngle="20"
SweepAngle="142" />
<telerikCommon:RadLineSegment Point="0.43, 0.488" />
<telerikCommon:RadLineSegment Point="0.43, 0.512" />
<telerikCommon:RadArcSegment Center="0.5, 0.5"
Size="0.07, 0.07"
StartAngle="200"
SweepAngle="142" />
</telerikCommon:RadPathFigure>
</telerikCommon:RadPathGeometry>
 

A sample Custom Needels example can be found in the Gauge/Customizations folder of the SDK
Samples Browser application.
 

Shape Indicator

1092
Telerik UI for Xamarin

The GaugeShapeIndicator has the following properties:

 Value: Defines a single value of the shape indicator.


 Size: Defines the size of the shape indicator.

The shape indicator is essentially a square box and is drawn so that its center coincides with the
point defined by the Position and Offset properties. The shape is rotated around its center so that the
default arrow shape always points towards the axis line.

Custom Shape Indicator


You can use a custom shape for the GaugeShapeIndicator by taking advantage of the Shape
property. In order to achieve the desired output, you need to understand how to set up the geometry
that describes the shape you want. The gauge expects that these conditions are met when a shape
geometry is set:

 The coordinates are in relative values between 0 and 1.


 The rotation pivot point is (0.5, 0.5).
 The shape's orientation is from (1, 0.5) to (0.5, 0.5).

 
When the gauge draws the shape, the geometry is scaled to the size it will be displayed with. Then it
is moved to the point defined by the Position and Offset properties. It is then rotated so that the
shape points at the axis line. In the example below, the indicator's value is 3.5 and the angle of
rotation is 35 degrees.

1093
Telerik UI for Xamarin

Here is an example of a custom shape:

XAML
<telerikCommon:RadPathGeometry x:Key="Shape1">
<telerikCommon:RadPathFigure StartPoint="0, 0.5">
<telerikCommon:RadLineSegment Point="1, 0.3" />
<telerikCommon:RadLineSegment Point="1, 0.7" />
</telerikCommon:RadPathFigure>
</telerikCommon:RadPathGeometry>
 

1094
Telerik UI for Xamarin

A sample Custom Shapes example can be found in the Gauge/Customizations folder of the SDK
Samples Browser application.
 

Bar Indicator
The GaugeBarIndicator presents a single value set by the Value property. The bar indicator is drawn
alongside the axis line (parallel to it) and is drawn from the axis origin value.

XAML
<telerikGauges:GaugeBarIndicator Fill="Green"
StartThickness="0"
Offset="15"
Value="75" />
 

In addition, the BarIndicator has the following properties:

 StartThickness(double): Specifies the start tickness of the bar indicator.


 EndThickness(double): Specifies the end thickness of the bar indicator
 StartCap(of type Telerik.XamarinForms.DataVisualization.Gauges.GaugeBarIndicatorCap
enumeration): Defines the start cap of the bar indicator.
 EndCap(of type Telerik.XamarinForms.DataVisualization.Gauges.GaugeBarIndicatorCap
enumeration): Defines the end cap of the bar indicator.The available options from
GaugeBarIndicatorCap enumeration are: Flat, Oval, ConcaveOval. The default value for start
and end caps is Flat.

1095
Telerik UI for Xamarin

Range Bar Indicator


The GaugeBarIndicator presents a value range set by the From and To properties.

XAML
<telerikGauges:GaugeRangeBarIndicator FromCap="Oval"
ToCap="Oval"
Offset="65"
From="-75"
To="75">
<telerikGauges:GaugeRangeBarIndicator.GradientStops>
<telerikCommon:RadGradientStop Offset="-75" Color="Gray" />
<telerikCommon:RadGradientStop Offset="-25" Color="Red" />
<telerikCommon:RadGradientStop Offset="25" Color="Yellow" />
<telerikCommon:RadGradientStop Offset="75" Color="Green" />
</telerikGauges:GaugeRangeBarIndicator.GradientStops>
</telerikGauges:GaugeRangeBarIndicator>
 

In addition, the RangeBarIndicator has the following properties:

 FromThickness(double): Specifies the start tickness of the range bar indicator.


 ToThickness(double): Specifies the end thickness of the range bar indicator
 FromCap(of type Telerik.XamarinForms.DataVisualization.Gauges.GaugeBarIndicatorCap
enumeration): Defines the start cap of the bar indicator.
 ToCap(of type Telerik.XamarinForms.DataVisualization.Gauges.GaugeBarIndicatorCap
enumeration): Defines the end cap of the bar indicator.The available options from
GaugeBarIndicatorCap enumeration are: Flat, Oval, ConcaveOval. The default value is Flat.

1096
Telerik UI for Xamarin

You could find example with Gauge Bar Indicators inside the Gauge/Features folder of the SDK
Samples Browser application.
 

Text Indicator
The GaugeTextIndicator gives you the possibility to present a text on a specific value.

XAML
<telerikGauges:GaugeTextIndicator HorizontalTextPlacement="Right"
Stroke="#FF4062AD"
StrokeThickness="1"
Text="indicator at 65"
TextColor="#FF4062AD"
TextMargin="4"
VerticalTextPlacement="Top"
Offset="15"
Value="65" />
 

You could find example with Gauge Text Indicators inside the Gauge/Features folder of the SDK
Samples Browser application.

1097
Telerik UI for Xamarin

See Also
 Positioning
 Ranges

1098
Telerik UI for Xamarin

Positioning
The gauge arranges most of its elements by taking into consideration the respective position
property and the respective offset property.

Some elements like the indicators have properties named Position and Offset. Other elements are
composite, like the axis that handles both ticks and labels, and this is why it requires two sets of
properties - TickPosition and TickOffset, and LabelPosition and LabelOffset.

The offset is the distance from the axis line to the element. The gauge does not have any strategy to
avoid overlapping of elements, so you will need to set adequate offset values to ensure that they are
not positioned on top of each other. In the example below, all elements are arranged so that they are
2 pixels apart and never overlap each other.

XAML
<telerikGauges:RadRadialGauge x:Name="gauge"
Margin="2"
AxisRadiusFactor="1"
StartAngle="90"
SweepAngle="360">
<telerikGauges:RadRadialGauge.Axis>
<telerikGauges:GaugeLinearAxis Maximum="100"
Minimum="0"
ShowLabels="False"
StrokeThickness="0" />
</telerikGauges:RadRadialGauge.Axis>
<telerikGauges:RadRadialGauge.Ranges>
<telerikGauges:GaugeRangesDefinition EndThickness="1"
StartThickness="1"
Offset="0">
<telerikGauges:GaugeRange Color="#FFDD789B"
From="0"
To="25" />
<telerikGauges:GaugeRange Color="#FFAAC271"
From="25"
To="50" />
<telerikGauges:GaugeRange Color="#FF4062AD"
From="50"
To="75" />
</telerikGauges:GaugeRangesDefinition>
</telerikGauges:RadRadialGauge.Ranges>
<telerikGauges:RadRadialGauge.Indicators>
<telerikGauges:GaugeBarIndicator EndCap="Oval"
EndThickness="10"
Fill="#FFDD789B"
StartThickness="10"
Offset="3"
Value="12.5" />
<telerikGauges:GaugeBarIndicator EndCap="Oval"
EndThickness="10"

1099
Telerik UI for Xamarin

Fill="#FFAAC271"
StartThickness="10"
Offset="15"
Value="37.5" />
<telerikGauges:GaugeBarIndicator EndCap="Oval"
EndThickness="10"
Fill="#FF4062AD"
StartThickness="10"
Offset="27"
Value="62.5" />
<telerikGauges:GaugeShapeIndicator Fill="#FF4062AD"
Position="Start"
Offset="39"
Value="56" />
<telerikGauges:GaugeNeedleIndicator Fill="#FFAAC271"
Offset="51"
Value="37.5" />
</telerikGauges:RadRadialGauge.Indicators>
</telerikGauges:RadRadialGauge>
 

Radial Gauge Specifics


While the offset is the absolute distance from the axis line to the element, the position of the axis line
itself is determined by the AxisRadiusFactor property, which is a relative value between 0 and 1.
When the radial gauge is arranged, it calculates the largest square box in the middle of its arrange
bounds and the gauge is laid out within this square box. The AxisRadiusFactor determines the size
of the radius of the axis arc inside this box. Setting the radius factor to 1.0 results in the axis line
occupying as much space as possible.

1100
Telerik UI for Xamarin

See Also
 Indicators
 Ranges

1101
Telerik UI for Xamarin

Ranges
The gauge ranges are elements that are usually used to give context to the indicated value (or
values). The ranges denote certain parts of the axis range and are usually displayed with different
colors to provide additional information. All ranges are arranged in an area alongside the axis line
(parallel to it). The distance from this area to the axis line is defined by the Offset property of the
GaugeRangesDefinition class. The gauge does not use any strategy to stack ranges or to avoid
overlapping of ranges, so you will need to set adequate From/To values to ensure that they are not
positioned on top of each other.

To include ranges in your gauge you need to set the Ranges property. You need to pass an object of
type GaugeRangesDefinition which has a Ranges collection. In this collection you can add
GaugeRange items when you need a solid color, or you can add GaugeGradientRange items when
you need gradient colors.

XAML
<telerikGauges:GaugeRangesDefinition>
<telerikGauges:GaugeRange Color="Green"
From="0"
To="100" />
<telerikGauges:GaugeRange Color="Yellow"
From="100"
To="150" />
<telerikGauges:GaugeGradientRange From="150" To="200">
<telerikCommon:RadGradientStop Offset="150" Color="Red" />
<telerikCommon:RadGradientStop Offset="200" Color="Black" />
</telerikGauges:GaugeGradientRange>
</telerikGauges:GaugeRangesDefinition>
 

Gradient Ranges
As demonstrated above, you can use the GaugeGradientRange to include ranges with gradient
color. To do this you can add gradient stops to the GradientStops collection of the gradient range.
Each gradient stop has a color and an offset value that determine the final appearance of the item.

1102
Telerik UI for Xamarin

The offset can either be treated as a relative value (between 0 and 1) or an absolute value (between
the axis' minimum and axis' maximum). This is defined by the IsOffsetRelative property of the
gradient range.

Here is an example when offset is relative

XAML
<telerikGauges:GaugeRangesDefinition>
<telerikGauges:GaugeGradientRange IsOffsetRelative="True"
From="-25"
To="25">
<telerikCommon:RadGradientStop Offset="0" Color="Blue" />
<telerikCommon:RadGradientStop Offset="1" Color="Red" />
</telerikGauges:GaugeGradientRange>
</telerikGauges:GaugeRangesDefinition>
 

and when the offset is absolute

XAML
<telerikGauges:GaugeRangesDefinition EndThickness="15"
StartThickness="0"
Offset="2">
<telerikGauges:GaugeGradientRange From="-25" To="25">
<telerikCommon:RadGradientStop Offset="-25" Color="Blue" />
<telerikCommon:RadGradientStop Offset="25" Color="Red" />
</telerikGauges:GaugeGradientRange>
</telerikGauges:GaugeRangesDefinition>
 

1103
Telerik UI for Xamarin

A sample Ranges example can be found in the Gauge/Featuers folder of the SDK Samples Browser
application.
 

See Also
 Indicators
 Positioning

1104
Telerik UI for Xamarin

Overview
RadImageEditor for Xamarin is a control that enables you to easily visualize and edit images in
different file formats in your mobile application. As an addition to the RadImageEditor control you can
use an UI - RadImageEditorToolbar. This UI includes all editing capabilities of the control and it
could be easily customized.

Figure 1: RadImageEditor Overview

Key features
 Importing and Exporting images: RadImageEditor allows you to import different image
formats such as JPEG, PNG, GIF, BMP and export images in JPEG, PNG format.

1105
Telerik UI for Xamarin

 Various image source options: The control could load images from a Stream, File (as
embedded resource, or image located on the device) and URI.
 Rich image editing features set: The control comes with a various editing capabilities:
 Image Transformations
 Crop
 Resize
 Rotate, etc. For more details go to Image Transformation article.
 Effects
 Hue
 Saturation
 Brightness
 Contrast and many more. For more details check the Effects article.
 Support for undo/redo: RadImageEditor has a history stack with the changes applied to the
image. This means that you can reverse and re-apply actions. Read more about this in the
History article.
 Support for Interactive Pan and Zoom: RadImageEditor provides pan and zoom functionality
that will help you interact with the image and display it in a convenient way.
 RadImageEditorToolbar (Built-in Toolbar Items): You could take advantage of a pre-defined
UI automatically wired with all toolbar items provided by the control through built-in
functionality. For more details check the ImageEditorToolbar article.
 Custom Toolbar: The RadImageEditor Toolbar can be fully customized. You could populate
the toolbar with the ToolbarItems needed for editing the image. Read more about this here.
 Custom Commands: The control provides and API for adding custom commands to the
Toolbar. Check here for more details.

See Also
 Getting Started
 RadImageEditor Toolbar
 Custom Toolbar

1106
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadImageEditor control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadImageEditor control

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadImageEditor control you have to install the
Telerik.UI.for.Xamarin.ImageEditor nuget package. This nuget will automatically refer the
Telerik.UI.for.Xamarin.Common, Telerik.UI.for.Xamarin.Primitives,
Telerik.UI.for.Xamarin.DataControls, SkiaSharp and ShiaSharp.Views.Forms nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadImageEditor component:

Platform Assemblies
Portable Telerik.XamarinForms.ImageEditor.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Android Telerik.Xamarin.Android.Common.dll
Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.ImageEditor.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.Common.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.ImageEditor.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.Common.dll

1107
Telerik UI for Xamarin

UWP Telerik.Core.dll
Telerik.UI.Xaml.Primitives.UWP.dll
Telerik.XamarinForms.ImageEditor.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
RadImageEditor is rendered via the SkiaSharp graphics library so you need to install also SkiaSharp
and SkiaSharp.Views.Forms in all projects of the Xamarin solution (portable, android, ios, etc).
 

3. Adding RadImageEditor control


You could use one of the following approaches:

Drag the control from the Toolbox.

Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML or C#.

The snippet below shows a sample RadImageEditor definition:

XAML
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<telerikImageEditor:RadImageEditor x:Name="imageEditor">
<telerikImageEditor:RadImageEditor.Source>
<OnPlatform x:TypeArguments="ImageSource" Default="cat4.jpeg">
<On Platform="UWP">Assets\cat4.jpeg</On>
</OnPlatform>
</telerikImageEditor:RadImageEditor.Source>
</telerikImageEditor:RadImageEditor>
<telerikImageEditor:RadImageEditorToolbar Grid.Row="1" ImageEditor="{x:Reference
imageEditor}" />
</Grid>
 

C#
var imageEditor = new RadImageEditor();
if(Device.RuntimePlatform == Device.UWP)
{
imageEditor.Source = "Assets/cat4.jpeg";
}
else imageEditor.Source = "cat4.jpeg";

1108
Telerik UI for Xamarin

var toolbar = new RadImageEditorToolbar();


toolbar.ImageEditor = imageEditor;

var grid = new Grid();


grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1,
GridUnitType.Star) });
grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1,
GridUnitType.Auto) });

grid.Children.Add(imageEditor, 0, 0);
grid.Children.Add(toolbar, 0, 1);

this.Content = grid;
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikImageEditor="clr-namespace:Telerik.XamarinForms.ImageEditor;assembly=Tele
rik.XamarinForms.ImageEditor"
 

C#
using Telerik.XamarinForms.ImageEditor;
 

In the example the .jpeg file is loaded from the application project. You could load images from File,
Uri, Stream, Resources, for more details check the Key Features article.

This is the result:

1109
Telerik UI for Xamarin

SDK Browser and QSF applications contain different examples that show ImageEditors's main
features. You can find the applications in the Examples and QSF folders of your local Telerik UI for
Xamarin installation.
 

See Also
 Key Features
 ImageEditor Toolbar
 Custom Toolbar

1110
Telerik UI for Xamarin

Key Features
The purpose of this help article is to show you the key features of the RadImageEditor control.

Image Source
RadImageEditor control enables you to visualize images through the following property

 Source(of type Xamarin.Forms.ImageSource): Specifies the source of the image. For more
details about the Source property check the Images in Xamarin.Forms article.

The images could be loaded from:

 File
 Uri
 Resource
 Stream

Save Images
RadImageEditor control gives you the option to save the currently edited image using the SaveAsync
method. The SaveAsync method has the following overloads:

 SaveAsync(Stream outputStream, ImageFormat imageFormat, double imageQuality)Saves


the currently edited image to the specified stream, encoding it with the given format and
quality.
 SaveAsync(Stream outputStream, ImageFormat imageFormat, double imageQuality, Size
maximumSize)Saves the currently edited image to the specified stream, encoding it with the
given format, quality and size.
 SaveAsync(Stream outputStream, ImageFormat imageFormat, double imageQuality, double
scaleFactor)Saves the currently edited image to the specified stream, encoding it with the
given format, quality and scale.

where:

 outputStream (Stream): Specifies the output stream to save the image to.
 imageFormat (ImageFormat): Specifies the image format to encode the image to. The
available options from ImageFormat enumeration are Jpeg and Png.
 imageQuality (double): Specifies the output stream to save the image to. The range is
between 1 and 0, where the value of 1 specifies the maximum possible quality, resulting in
minimum compression and the value of 0 specifies the minimum possible quality, resulting in
maximum compression.
 maximumSize (Size): Specifies the output stream to save the image to. If the original image
size is larger than the maximumSize, the SaveAsync will save the image in the submitted
maximumSize but the aspect ratio will be kept.
 scaleFactor (double): Specifies a scale factor, which can be used to reduce the size of the
final image. For example when setting values below 1 downscale the image before saving,

1111
Telerik UI for Xamarin

which reducing the final image size and values above 1 upscale the image before saving, which
increasing the final image size.

The saved image contains all currently applied changes in the ImageEditor.
 

Example
Here is how the RadImageEditor and RadImageEditorToolbar are defined:

XAML
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<telerikImageEditor:RadImageEditor x:Name="imageEditor">
<telerikImageEditor:RadImageEditor.Source>
<OnPlatform x:TypeArguments="ImageSource" Default="cat4.jpeg">
<On Platform="UWP">Assets\cat4.jpeg</On>
</OnPlatform>
</telerikImageEditor:RadImageEditor.Source>
</telerikImageEditor:RadImageEditor>
<telerikImageEditor:RadImageEditorToolbar Grid.Row="1" ImageEditor="{x:Reference
imageEditor}" AutoGenerateItems="False" ItemSpacing="5">
<telerikImageEditor:CommandToolbarItem Text="Original Size"
Tapped="OnSaveOriginalTapped" />
<telerikImageEditor:CommandToolbarItem Text="Specific Size"
Tapped="OnSaveMaxSizeTapped" />
<telerikImageEditor:CommandToolbarItem Text="Downscaled"
Tapped="OnSaveDownscaledTapped" />
</telerikImageEditor:RadImageEditorToolbar>
</Grid>
 

 Save with original size:

C#
private async void OnSaveOriginalTapped(object sender, EventArgs e)
{
var folderPath =
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
var filePath = Path.Combine(folderPath, "image.jpg");
using (var fileStream = File.Create(filePath))
{
await this.imageEditor.SaveAsync(fileStream, ImageFormat.Jpeg, 0.9);
}

await Application.Current.MainPage.DisplayAlert("", "The Image is saved with


original size", "OK");
}
 

1112
Telerik UI for Xamarin

 Save with specific size:

C#
private async void OnSaveMaxSizeTapped(object sender, EventArgs e)
{
var folderPath =
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
var filePath = Path.Combine(folderPath, "image.jpg");
var maxsize = new Size(400, 500);
using (var fileStream = File.Create(filePath))
{
await this.imageEditor.SaveAsync(fileStream, ImageFormat.Jpeg, 0.9, maxsize);
}

await Application.Current.MainPage.DisplayAlert("", "The Image is saved with Size


400:500", "OK");
}
 

 Save with downscaled size:

C#
private async void OnSaveDownscaledTapped(object sender, EventArgs e)
{
var folderPath =
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
var filePath = Path.Combine(folderPath, "image.jpg");
using (var fileStream = File.Create(filePath))
{
await this.imageEditor.SaveAsync(fileStream, ImageFormat.Jpeg, 0.9, 0.5);
}

await Application.Current.MainPage.DisplayAlert("", "The Image is downscaled to


50%", "OK");
}
 

SDK Browser application contains a sample SaveImage example. You can find it in the
ImageEditor/Features folder.
 

Zoom Level Support


 ZoomLevel(double): Specifies the current zoom level of the viewed image. The default value
is 1. A zoom level of 1 means the image is displayed with its original size.

The RadImageEditor exposes properties for applying min and max zoom values:

 MinZoomLevel(double): Specifies the minimum zoom level of the image. The default value is
0.1. Setting the ZoomLevel property is coerced between MinZoomLevel and MaxZoomLevel.
 MaxZoomLevel(double): Specifies the maximum zoom level of the image. The default value

1113
Telerik UI for Xamarin

is 10. Setting the ZoomLevel property is coerced between MinZoomLevel and MaxZoomLevel.

SDK Browser application contains a sample ZoomLevel example. You can find it in the
ImageEditor/Features folder.
 

Example
Here is an example how to use the RadImageEditor Min and Max Zoom Level:

XAML
<telerikImageEditor:RadImageEditor x:Name="imageEditor"
MinZoomLevel="0.5"
MaxZoomLevel="20">
<telerikImageEditor:RadImageEditor.Source>
<OnPlatform x:TypeArguments="ImageSource" Default="cat4.jpeg">
<On Platform="UWP">Assets\cat4.jpeg</On>
</OnPlatform>
</telerikImageEditor:RadImageEditor.Source>
</telerikImageEditor:RadImageEditor>
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikImageEditor="clr-namespace:Telerik.XamarinForms.ImageEditor;assembly=Tele
rik.XamarinForms.ImageEditor"
 

See Also
 ImageEditor Toolbar
 Custom Toolbar

1114
Telerik UI for Xamarin

ImageEditor Toolbar
The RadImageEditor control comes with various editing capabilities and with the help of the
ImageEditorToolbar you can provide to the users easy and quick way to edit their images. The
default toolbar include items for all the available image editing options, alternatively you could
customize the shown editing options according to your needs.

By default the RadImageEditorToolbar Items are auto-populated. You could change this by setting
the RadImageEditorToolbar boolean AutoGenerateItems to False. In this case you will need to
manually define the available editing options, for more details check Custom Toolbar article.

In order to attach the ImageEditor control to the RadImageEditorToolbar control you need to set the
ImageEditor(from type RadImageEditor) property. All toolbar items execute their actions against the
specified image editor.

When the ImageEditorToolbarItems can not be fitted in the device screen, OverflowButton is shown
in the toolbar. You could customize it through the following properties:

 IsMultiLine(bool): Defines a value indicating whether the display nested levels of toolbar
items on multiple lines. When set to true, nested levels of toolbar items are displayed on
separate lines in the toolbar. When set to false, nested levels of toolbar items are displayed
on a single line in the toolbar, whith the option to navigate back and forward between the
different levels. By default is false.
 OverflowButtonText(String): Specifies the text of the overflow button.
 OverflowButtonTextColor(Color): Specifies the text color of the overflow button, which is
displayed when there are more buttons than currently visible.
 OverflowButtonFontFamily(String): Specifies the font family of the overflow button, which is
displayed when there are more buttons than currently visible.
 OverflowButtonTemplate(DataTemplate): Specifies the template of the overflow button,
which is displayed when there are more buttons than currently visible.

Example
Here is an example how to use the default RadImageEditor Toolbar and its properties:

Use the following snippet to define the RadImageEditor and RadImageEditor Toolbar:

XAML
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<telerikImageEditor:RadImageEditor x:Name="imageEditor">
<telerikImageEditor:RadImageEditor.Source>
<OnPlatform x:TypeArguments="ImageSource" Default="cat4.jpeg">
<On Platform="UWP">Assets\cat4.jpeg</On>
</OnPlatform>

1115
Telerik UI for Xamarin

</telerikImageEditor:RadImageEditor.Source>
</telerikImageEditor:RadImageEditor>
<telerikImageEditor:RadImageEditorToolbar Grid.Row="1" ImageEditor="{x:Reference
imageEditor}" />
</Grid>
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikImageEditor="clr-namespace:Telerik.XamarinForms.ImageEditor;assembly=Tele
rik.XamarinForms.ImageEditor"
 

This is the result:

This is the result when IsMultiLine = "True":

See Also
 Custom Toolbar
 Effects
 Image Transformations
 Toolbar Styling

1116
Telerik UI for Xamarin

ImageEditor Custom Toolbar


The RadImageEditor Toolbar can be fully customized. You could populate the toolbar with the
ToolbarItems needed for editing the image.

Toolbar Items
When you customize the toolbar you could include the following editing capabilities:

 For Image Transformations you could use the Toolbar Items listed above:
 CropToolbarItem
 ResizeToolbarItem
 RotateLeftToolbarItem
 RotateRightToolbarItem
 FlipHorizontalToolbarItem
 FlipVerticalToolbarItem

To group the transformations you could use the common ToolbarItem: TransformsToolbarItem. For
more details please check the Image Transformations article.
 

 For applying Effects to the image use the following Toolbar Items:
 HueToolbarItem
 SaturationToolbarItem
 BrightnessToolbarItem
 ContrastToolbarItem
 BlurToolbarItem
 SharpenToolbarItem

To group the effects you could use the common ToolbarItem: EffectsToolbarItem. For more details
please check the Effects article.
 

 For reversing and re-applying actions use the following items:


 UndoToolbarItem
 RedoToolbarItem
 ResetToolbarItem

For more details please check the History article.


 

 For navigating back to the different levels/toolbar items use the BackToolbarITem.
 When ImageEditroToolbar.IsMultiLine is False - nested levels of toolbar items are
displayed on a single line in the toolbar. If you customize the toolbar item the option to
navigate back to the different levels is using the BackToolbarItem.
 For applying Commands use the CommandToolbarItem which allows executing an arbitrary
user-defined command from the toolbar. It exposes the following properties:

1117
Telerik UI for Xamarin

 Command(ICommand): Specifies the command to execute.


 CommandParameter(object): Specifies a parameter to be passed to the command upon
execution.

Example
Here is an example how to customize the RadImageEditor Toolbar

Use the following snippet to define the RadImageEditor and RadImageEditor Toolbar:

XAML
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<telerikImageEditor:RadImageEditor x:Name="imageEditor">
<telerikImageEditor:RadImageEditor.Source>
<OnPlatform x:TypeArguments="ImageSource" Default="cat4.jpeg">
<On Platform="UWP">Assets\cat4.jpeg</On>
</OnPlatform>
</telerikImageEditor:RadImageEditor.Source>
</telerikImageEditor:RadImageEditor>
<telerikImageEditor:RadImageEditorToolbar Grid.Row="1" ImageEditor="{x:Reference
imageEditor}" AutoGenerateItems="False">
<telerikImageEditor:EffectsToolbarItem AutoGenerateItems="False">
<telerikImageEditor:BackToolbarItem/>
<telerikImageEditor:ContrastToolbarItem AutoGenerateItems="False">
<telerikImageEditor:CancelToolbarItem HorizontalOptions="Start" />
<telerikImageEditor:TemplateToolbarItem>
<telerikImageEditor:TemplateToolbarItem.Template>
<DataTemplate>
<Slider Maximum="2" Minimum="0" Value="{Binding Value}" />
</DataTemplate>
</telerikImageEditor:TemplateToolbarItem.Template>
</telerikImageEditor:TemplateToolbarItem>
<telerikImageEditor:ApplyToolbarItem HorizontalOptions="End" />
</telerikImageEditor:ContrastToolbarItem>
</telerikImageEditor:EffectsToolbarItem>
<telerikImageEditor:CropToolbarItem/>
<telerikImageEditor:RotateLeftToolbarItem/>
<telerikImageEditor:RotateRightToolbarItem/>
<telerikImageEditor:UndoToolbarItem/>
<telerikImageEditor:RedoToolbarItem/>
</telerikImageEditor:RadImageEditorToolbar>
</Grid>
 

In addition to this, you need to add the following namespace:

XAML

1118
Telerik UI for Xamarin

xmlns:telerikImageEditor="clr-namespace:Telerik.XamarinForms.ImageEditor;assembly=Tele
rik.XamarinForms.ImageEditor"
 

This is the result:

See Also
 Image Transformations
 Effects
 History
 ToolbarItems Styling

1119
Telerik UI for Xamarin

Image Transformations

The RadImageEditor Toolbar allows you to transform the image through the following Transforms
Toolbar Items:

 CropToolbarItem: Activates the crop tool in the image editor that allows you to crop the
image.
 ResizeToolbarItem: Activates the resize tool in the image editor that allows you to resize the
image.
 RotateLeftToolbarItem: Executes an action on the image editor to rotate the image 90
degrees to the left (counter clockwise direction).
 RotateRightToolbarItem: Executes an action on the image editor to rotate the image 90
degrees to the right (clockwise direction).
 FlipHorizontalToolbarItem: Executes an action on the image editor to flip the image
horizontally.
 FlipVerticalToolbarItem: Executes an action on the image editor to flip the image vertically.

To group the transformations you could use the common ToolbarItem: TransformsToolbarItem. By
default when the TransformsToolbarItem is set to the ImageEditorToolbarItem, the value of the
AutoGenerateItems is true. In case you want to customize the TransformsToolbarItem you should
set the AutoGenerateItems to false.
 
You could apply the following properties for each Transform Toolbar Item

 ApplyToolbarItem: Applies the changes from the currently active tool and deactivates it.
 CancelToolbarItem: Cancels the changes from the currently active tool and deactivates it.
 TemplateToolbarItem: Allows displaying an arbitrary content in the toolbar via a
DataTemplate. The BindingContext of the created content is set to the currently active tool in
the image editor. This allows direct data binding of the components from the template to the
properties of the tool. The TemplateToolbarItem exposes the following property:
 Template(DataTemplate): Specifies the DataTemplate of the content to be displayed.

1120
Telerik UI for Xamarin

Example
Example when AutoGenerateItems="True"

XAML
<telerikImageEditor:RadImageEditorToolbar Grid.Row="1" ImageEditor="{x:Reference
imageEditor}" AutoGenerateItems="False">
<telerikImageEditor:EffectsToolbarItem AutoGenerateItems="True"/>
</telerikImageEditor:RadImageEditorToolbar>
 

Example when AutoGenerateItems="False".

XAML
<telerikImageEditor:RadImageEditorToolbar Grid.Row="1" ImageEditor="{x:Reference
imageEditor}" AutoGenerateItems="False">
<telerikImageEditor:TransformsToolbarItem AutoGenerateItems="False">
<telerikImageEditor:CropToolbarItem AutoGenerateItems="False"
HorizontalOptions="Start">
<telerikImageEditor:TemplateToolbarItem HorizontalOptions="Start">
<telerikImageEditor:TemplateToolbarItem.Template>
<DataTemplate>
<Label Text="Crop"/>
</DataTemplate>
</telerikImageEditor:TemplateToolbarItem.Template>
</telerikImageEditor:TemplateToolbarItem>
<telerikImageEditor:CancelToolbarItem HorizontalOptions="Center"/>
<telerikImageEditor:ApplyToolbarItem HorizontalOptions="End"/>
</telerikImageEditor:CropToolbarItem>
</telerikImageEditor:TransformsToolbarItem>
</telerikImageEditor:RadImageEditorToolbar>
 

Visual Structure of the EffectsToolbarItem when AutoGenerateItems = "False"

1121
Telerik UI for Xamarin

See Also
 Effects
 History

1122
Telerik UI for Xamarin

Crop
The RadImageEditor CropToolbarItem has properties which help you specify the geometry of the
crop selection and the desired aspect ratio. The available options by default are:

 Free, Original, Square, Circle, 3:2, 4:3, 16:9

Custom Crop Toolbar


You could easily customize the crop definitions when setting AutoGenerateItems="False" to the
RadImageEditorToolbar.

Crop Definitions

 AspectRatio: Specifies the aspect ratio of the crop selection.


 Geometry: Specifies the geometry of the crop selection.
 Text: Specifies the text visualized inside the crop tool.

XAML
<telerikImageEditor:RadImageEditorToolbar Grid.Row="1" ImageEditor="{x:Reference
imageEditor}" AutoGenerateItems="False">
<telerikImageEditor:CropToolbarItem>
<telerikImageEditor:CropToolbarItem.CropDefinitions>
<telerikImageEditor:CropDefinition AspectRatio="Free" Text="Free"/>

1123
Telerik UI for Xamarin

<telerikImageEditor:CropDefinition Text="Circle" AspectRatio="1:1">


<telerikImageEditor:CropDefinition.Geometry>
<telerikCommon:RadEllipseGeometry Center="0.5,0.5" Radius="0.5,0.5"/>
</telerikImageEditor:CropDefinition.Geometry>
</telerikImageEditor:CropDefinition>
</telerikImageEditor:CropToolbarItem.CropDefinitions>
</telerikImageEditor:CropToolbarItem>
</telerikImageEditor:RadImageEditorToolbar>
 

Crop Tool

 AspectRatio (Telerik.XamarinForms.ImageEditor.AspectRatio): Represents the aspect ratio


expressed as the ratio between the width and height of an image. The specific values are:
 Free: Special value, indicating the aspect ratio should not be constrained.
 Original: Special value, indicating the aspect ratio should match the original image.
 Square: Special value, indicating the width and height of the image should be equal.

When set custom values for the AspectRatio the separator must be ":", for example: "7:2", "6:2".
 
XAML
<telerikImageEditor:CropDefinition AspectRatio="7:2" Text="7:2"/>
 

If no aspect ratio is specified explicitly, the crop tool uses the default Free. When a custom aspect
ratio is specified, the crop operation is performed with that ratio.
 

 Geometry (RadGeometry): Specifies the geometry of the crop selection. The available
geometries are:
 RadRectangleGeometry: Represents a rectangle geometry.
 RadLineGeometry: Represents a line geometry.
 RadEllipseGeometry: Represents an ellipse geometry.
 RadPathGeometry: Represents a complex path geometry composed of one or more path
figures. In order to create a specific geometry, you need to set a RadPathGeometry
object to CropDefinition Geometry property. The RadPathGeometry object exposes a
Figures property which is a collection of RadPathFigures. Each of the RadPathFigure
objects is composed of one or several segments:
 RadArcSegment
 RadArcToSegment
 RadLineSegment
 RadConicSegment
 RadCubicSegment
 RadQuadraticSegment

More information about the RadPathGeomerty can be found in the RadPathGeometry article.

If no geometry is specified explicitly, the crop tool uses the default RadRectangleGeometry. When a
custom geometry is specified, the crop operation is performed with that geometry.
 

1124
Telerik UI for Xamarin

Example
The snippet below shows a sample RadImageEditor and RadImageEditorToolbar definitions, where
the CropToolbar is defined as follow:

XAML
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<telerikImageEditor:RadImageEditor x:Name="imageEditor">
<telerikImageEditor:RadImageEditor.Source>
<OnPlatform x:TypeArguments="ImageSource" Default="custom_toolbar.png">
<On Platform="UWP">Assets\custom_toolbar.png</On>
</OnPlatform>
</telerikImageEditor:RadImageEditor.Source>
</telerikImageEditor:RadImageEditor>
<telerikImageEditor:RadImageEditorToolbar Grid.Row="1" ImageEditor="{x:Reference
imageEditor}" AutoGenerateItems="False">
<telerikImageEditor:CropToolbarItem>
<telerikImageEditor:CropToolbarItem.CropDefinitions>
<telerikImageEditor:CropDefinition AspectRatio="Free" Text="Free"/>
<telerikImageEditor:CropDefinition AspectRatio="Original" Text="Original"/>
<telerikImageEditor:CropDefinition Text="Circle" AspectRatio="1:1">
<telerikImageEditor:CropDefinition.Geometry>
<telerikCommon:RadEllipseGeometry Center="0.5,0.5" Radius="0.5,0.5"/>
</telerikImageEditor:CropDefinition.Geometry>
</telerikImageEditor:CropDefinition>
<telerikImageEditor:CropDefinition Text="Rhombus">
<telerikImageEditor:CropDefinition.Geometry>
<telerikCommon:RadPathGeometry>
<telerikCommon:RadPathFigure StartPoint="0.5, 0.0">
<telerikCommon:RadLineSegment Point="1.0, 0.5" />
<telerikCommon:RadLineSegment Point="0.5, 1.0" />
<telerikCommon:RadLineSegment Point="0.0, 0.5" />
<telerikCommon:RadLineSegment Point="0.5, 0.0" />
</telerikCommon:RadPathFigure>
</telerikCommon:RadPathGeometry>
</telerikImageEditor:CropDefinition.Geometry>
</telerikImageEditor:CropDefinition>
</telerikImageEditor:CropToolbarItem.CropDefinitions>
</telerikImageEditor:CropToolbarItem>
</telerikImageEditor:RadImageEditorToolbar>
</Grid>
 

In addition, you need to add the following namespaces:

XAML
xmlns:telerikImageEditor="clr-namespace:Telerik.XamarinForms.ImageEditor;assembly=Tele
rik.XamarinForms.ImageEditor"

1125
Telerik UI for Xamarin

xmlns:telerikCommon="clr-namespace:Telerik.XamarinForms.Common;assembly=Telerik.Xamari
nForms.Common"
 

SDK Browser application contains a sample Custom Crop Toolbar example. You can find it in the
ImageEditor/Features folder.
 

See Also
 Effects
 History

1126
Telerik UI for Xamarin

Effects

The RadImageEditor Toolbar allows you apply Effects to the image using the following Toolbar
Items:

 HueToolbarItem: Activates the hue adjustment tool in the image editor. The hue adjustment
rotates the color in the hue scale by a certain angle. The HueToolbarItem exposes the
following properties:
 Minimum(double): Specifies the minimum value of the hue factor, when using an
auto-generated slider content. The default value is 0.
 Maximum(double): Specifies the maximum value of the hue factor, when using an
auto-generated slider content. Its default value is 1.
 SaturationToolbarItem: Activates the saturation adjustment tool in the image editor. The
saturation factor of 0 means no saturation (black-and-white image), while the value of 1
means full saturation (the original color of the image). Values above 1 mean oversaturation
(overexposed colors of the original image).
 Minimum(double): Specifies the minimum value of the saturation factor, when using an
auto-generated slider content. The default value is 0.
 Maximum(double): Specifies the maximum value of the saturation factor, when using an
auto-generated slider content. The default value is 3.
 BrightnessToolbarItem: Activates the brightness adjustment tool in the image editor. The
value of 0 means no change in brightness. Positive values increase the brightness, where
the value of 1 gives the maximum brightness (completely white image). Negative values
decrease the brightness, where the value of -1 gives no brightness (completely black image).
 Minimum(double): Specifies the minimum value of the brightness factor, when using an
auto-generated slider content. The default value is -1.
 Maximum(double): Specifies the maximum value of the brightness factor, when using an
auto-generated slider content. The default value is 1.
 ContrastToolbarItem: Activates the contrast adjustment tool in the image editor. The value of
0 means no contrast (completely gray image), while the value of 1 means full contrast
(original color of the image). Values above 1 gives increased contrast of the image.
 Minimum(double): Specifies the minimum value of the contrast factor, when using an
auto-generated slider content. The default value is 0.
 Maximum(double): Specifies the maximum value of the contrast factor, when using an
auto-generated slider content. The default value is 3.
 BlurToolbarItem: Activates the blur tool in the image editor. The strength of the effect is
determined by the radius of the filter. For each pixel, all neighboring pixels within the given
radius affect the color of the final pixel.

1127
Telerik UI for Xamarin

 Minimum(double): Specifies the minimum radius of the filter, when using an


auto-generated slider content. The default value is 0.
 Maximum(double): Specifies the maximum radius of the filter, when using an
auto-generated slider content. The default value is 3.
 SharpenToolbarItem: Activates the sharpen tool in the image editor. The strength of the
effect is determined by the radius of the filter. For each pixel, all neighboring pixels within the
given radius affect the color of the final pixel.
 Minimum(double): Specifies the minimum radius of the filter, when using an
auto-generated slider content. The default value is 0.
 Maximum(double): Specifies the maximum radius of the filter, when using an
auto-generated slider content. The default value is 3.

To group the effects you could use the common ToolbarItem: EffectsToolbarItem. By default when
the EffectsToolbarItem is set to the ImageEditorToolbarItem, the value of the AutoGenerateItems is
true. In case you want to customize the EffectsToolbarItem you should set the AutoGenerateItems to
false.
 
You could apply the following properties to each Effect

 ApplyToolbarItem: Applies the changes from the currently active tool and deactivates it.
 CancelToolbarItem: Cancels the changes from the currently active tool and deactivates it.
 TemplateToolbarItem: Allows displaying an arbitrary content in the toolbar via a
DataTemplate. The BindingContext of the created content is set to the currently active tool in
the image editor. This allows direct data binding of the components from the template to the
properties of the tool. The TemplateToolbarItem exposes the following property:
 Template(DataTemplate): Specifies the DataTemplate of the content to be displayed.

Example
Example when AutoGenerateItems="True"

XAML
<telerikImageEditor:RadImageEditorToolbar Grid.Row="1" ImageEditor="{x:Reference
imageEditor}" AutoGenerateItems="False">
<telerikImageEditor:EffectsToolbarItem AutoGenerateItems="True"/>
</telerikImageEditor:RadImageEditorToolbar>
 

Example when AutoGenerateItems="False"

1128
Telerik UI for Xamarin

XAML
<telerikImageEditor:RadImageEditorToolbar Grid.Row="1" ImageEditor="{x:Reference
imageEditor}" AutoGenerateItems="False">
<telerikImageEditor:EffectsToolbarItem AutoGenerateItems="False">
<telerikImageEditor:ContrastToolbarItem AutoGenerateItems="False">
<telerikImageEditor:CancelToolbarItem HorizontalOptions="Start" />
<telerikImageEditor:TemplateToolbarItem>
<telerikImageEditor:TemplateToolbarItem.Template>
<DataTemplate>
<Slider Maximum="2" Minimum="0" Value="{Binding Value}" />
</DataTemplate>
</telerikImageEditor:TemplateToolbarItem.Template>
</telerikImageEditor:TemplateToolbarItem>
<telerikImageEditor:ApplyToolbarItem HorizontalOptions="End" />
</telerikImageEditor:ContrastToolbarItem>
</telerikImageEditor:EffectsToolbarItem>
</telerikImageEditor:RadImageEditorToolbar>
 

Visual Structure of the EffectsToolbarItem when AutoGenerateItems = "False"

See Also
 Image Transformations
 History

1129
Telerik UI for Xamarin

History

The RadImageEditor Toolbar provides the following Toolbar Items for reversing and re-applying
actions:

 UndoToolbarItem: Undoes the last executed action on the image editor.


 RedoToolbarItem: Redoes the last executed action on the image editor.
 ResetToolbarItem: Undoes all executed actions on the image editor. This effectively resets
the image to its initial state.

You could apply the following properties for the toolbar items above:

 ApplyToolbarItem: Applies the changes from the currently active tool and deactivates it.
 CancelToolbarItem: Cancels the changes from the currently active tool and deactivates it.
 TemplateToolbarItem: Allows displaying an arbitrary content in the toolbar via a
DataTemplate. The BindingContext of the created content is set to the currently active tool in
the image editor. This allows direct data binding of the components from the template to the
properties of the tool. The TemplateToolbarItem exposes the following property:
 Template(DataTemplate): Specifies the DataTemplate of the content to be displayed.

Example
XAML
<telerikImageEditor:RadImageEditorToolbar Grid.Row="1" ImageEditor="{x:Reference
imageEditor}" AutoGenerateItems="False">
<telerikImageEditor:UndoToolbarItem/>
<telerikImageEditor:RedoToolbarItem/>
<telerikImageEditor:ResetToolbarItem/>
</telerikImageEditor:RadImageEditorToolbar>
 

See Also
 Image Transformations
 Effects

1130
Telerik UI for Xamarin

Localization
RadImageEditor for Xamarin provides language localization. In short, you can translate the used
across the ImageEditor Toolbar Items texts to other languages, so that your app can be adapted to
different regions.

To learn in details about the localization process of Telerik UI for Xamarin components, please go
through the common Localization and Globalization topic.
 

Common Image Editor Localization strings


Localization Key Default Value
ImageEditor_Blur Blur
ImageEditor_Brightness Brightness
ImageEditor_Contrast Contrast
ImageEditor_Crop Crop
ImageEditor_CropCircle Circle
ImageEditor_CropFree Free
ImageEditor_CropOriginal Original
ImageEditor_CropSquare Square
ImageEditor_Hue Hue
ImageEditor_Resize Resize
ImageEditor_Saturation Saturation
ImageEditor_Sharpen Sharpen

See Also
 Localization and Globalization

1131
Telerik UI for Xamarin

Commands
This article explains the commands provided in ImageEditor and ImageEditorToolbar.

ImageEditor Commands
From R1 2022 Release RadImageEditor provides commands for programatically editing the image
without the usage of the ImageEditorToolbar. The available commands are:

 CropCommand(ICommand): crop the image.The CropCommandContext object is passed as a


parameter to the CropCommand. The CropCommandContext has the following properties:
 Geometry(of type Telerik.XamarinForems.Common.RadGeometry): specifies the
geomerty of the crop selection.
 Bounds(of type Rectangle): used to gets the current crop bounding rectangle.
 CropInteractiveCommand(ICommand): initiates the crop action.
 ResizeCommand: for image resizing.The ResizeCommandContext object is passed as a
parameter to the ResizeCommand. The ResizeCommandContext has the following property:
 Size(of typeXamarin.Forms.Size): specifies the size which will be used to resize the
image.
 RotateLeftCommand(ICommand): for image rotation 90 degree to the left.
 RotateRightCommand: for image rotation 90 degree to the right.
 BlurCommand: applies blur to the imageThe BlurCommandContext object is passed as a
parameter to the BlurCommand. The BlurCommandContext has the following property:
 Blur(int): specifies the blur value.
 BrightnessCommand(ICommand) changes the brightness of the image.The
BrightnessCommandContext object is passed as a parameter to the
BrightnessCommand. The BrightnessCommandContext has the following property:
 Brightness(double): specifies the brightness value.
 ContrastCommand(ICommand): changes the image contrast.The
ContrastCommandContext object is passed as a parameter to the ContrastCommand. The
ContrastCommandContext has the following property:
 Contrast(double): specifies the contrast value.
 HueCommand(ICommand): changes the image hue.The HueCommandContext object is
passed as a parameter to the HueCommand. The HueCommandContext has the following
property:
 Hue(double): specifies the hue value.
 SaturationCommand(ICommand): changes the image saturation.The
SaturationCommandContext object is passed as a parameter to the
SaturationCommand. The SaturationCommandContext has the following property:
 Saturation(double): specifies the saturation value.
 SharpenCommand(ICommand): changes the image sharpness.The
SaturationCommandContext object is passed as a parameter to the SharpenCommand.
The SharpenCommandContext has the following property:
 Sharpen(int): specifies the sharpen value.
 FlipHorizontalCommand(ICommand): flips the image horizontally.
 FlipVerticalCommand(ICommand): flips the image vertically.

1132
Telerik UI for Xamarin

Commands which cancel/apply the changes made in interactive commands:

 CancelInteractiveCommand- cancels the changes done in interactive command such as


Telerik.XamarinForms.ImageEditor.RadImageEditor.CropInteractiveCommand.
 ApplyInteractiveCommand- applies the changes done in interactive command such as
Telerik.XamarinForms.ImageEditor.RadImageEditor.CropInteractiveCommand.

When using the CropInteractiveCommand you can apply the crop changes using
ApplyInteractiveCommand and cancel the changes using CancelInteractiveCommand.

Example
ImageEditor definition in XAML:

XAML
<telerikImageEditor:RadImageEditor x:Name="imageEditor" Grid.Row="1">
<telerikImageEditor:RadImageEditor.Source>
<OnPlatform x:TypeArguments="ImageSource" Default="cat4.jpeg">
<On Platform="UWP">Assets\cat4.jpeg</On>
</OnPlatform>
</telerikImageEditor:RadImageEditor.Source>
</telerikImageEditor:RadImageEditor>
</Grid>
 

InteractiveCropCommand with Apply and Cancel commands

FlipHorizontal and FlipVerical commands

XAML
<Button Grid.Row="3" Text="Flip –" Command="{Binding FlipHorizontalCommand,
Source={x:Reference imageEditor}}"/>
<Button Grid.Row="3" Grid.Column="1" Text="Flip |" Command="{Binding
FlipVerticalCommand, Source={x:Reference imageEditor}}" />
 

RotateLeft and RotateRight commands

XAML
<Button Grid.Row="3" Grid.Column="2" Text="Rotate &lt;" Command="{Binding
RotateLeftCommand, Source={x:Reference imageEditor}}" />
<Button Grid.Row="3" Grid.Column="3" Text="Rotate &gt;" Command="{Binding
RotateRightCommand, Source={x:Reference imageEditor}}" />
 

BrightnessCommand

XAML
<Button Text="Brightness" Grid.ColumnSpan="2" Command="{Binding BrightnessCommand,
Source={x:Reference imageEditor}}">

1133
Telerik UI for Xamarin

<Button.CommandParameter>
<telerikImageEditorCommands:BrightnessCommandContext Brightness="{Binding
Value, Source={x:Reference brightness}}" />
</Button.CommandParameter>
</Button>
<Slider Grid.Column="2" Grid.ColumnSpan="2" Minimum="-0.5" Maximum="0.5"
x:Name="brightness"/>
 

HueCommand

XAML
<Button Text="Hue" Grid.Row="1" Grid.ColumnSpan="2" Command="{Binding HueCommand,
Source={x:Reference imageEditor}}">
<Button.CommandParameter>
<telerikImageEditorCommands:HueCommandContext Hue="{Binding Value,
Source={x:Reference hue}}" />
</Button.CommandParameter>
</Button>
<Slider Grid.Row="1" Grid.Column="2" Grid.ColumnSpan="2" Minimum="-0.4" Maximum="0.4"
x:Name="hue" />
 

1134
Telerik UI for Xamarin

Sample Commands example can be found inside the SDKBrowser app/ImageEditor/Fetures folder.
 

ImageEditor Toolbar Commands


RadImageEditorToolbar provides a ToolbarItem for creating a command.

 CommandToolbarItem: Allows executing an arbitrary user-defined command from the


toolbar. The CommandToolbarItem has the following properties:
 Command(ICommand): Specifies the command to execute.
 CommandParameter(object): Specifies a parameter to be passed to the command
upon execution.

You could use the CommandToolbarItem when the ImageEditorToolbar AutoGenerateItems property
is set to "False".
 

Example

1135
Telerik UI for Xamarin

Here is an example how the CommandToolbarItem could be used

XAML
<telerikImageEditor:RadImageEditorToolbar Grid.Row="1" ImageEditor="{x:Reference
imageEditor}" AutoGenerateItems="False">
<telerikImageEditor:CommandToolbarItem Text="Save" Tapped="OnSaveTapped" />
</telerikImageEditor:RadImageEditorToolbar>
 

On the Tapped event we are going to save the image on the device:

C#
private async void OnSaveTapped(object sender, EventArgs e)
{
var folderPath =
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
var filePath = Path.Combine(folderPath, "image.jpg");

using (var fileStream = File.Create(filePath))


{
await this.imageEditor.SaveAsync(fileStream, ImageFormat.Jpeg, 0.9);
}

Application.Current.MainPage.DisplayAlert("Success!", "The Image is saved", "OK");


}
 

See Also
 Custom Toolbar
 Effects
 Image Transformations
 Toolbar Styling

1136
Telerik UI for Xamarin

ImageEditor Toolbar Styling


The RadImageEditor Toolbar could be styled through the Style property. You will need to declare the
Style in the ResourceDictionary of the page and set for its TargetType property to be of type
telerikImageEditor:ImageEditorToolbarItem.

In order to apply the style to all toolbar items you should set the Style.ApplyToDerivedTypes property
to True.
 
You could style the Toolbar using the following properties:

 ItemSpacing(double): Specifies the extra spacing between items horizontal direction. The
default value is 4.
 TextColor: Defines the color of all Toolbar items.
 SelectedColor: Defines the color of the selected Toolbar item.
 BackgroundColor: Defines the background color of all Toolbar items.
 Font Options (FontSize, FontFamily, FontAttributes): Defines the font options that are applied
to all ImageEditorToolbar Items.

When the Toolbar Items are more than the device screen size can fit the OverflowButton is shown. It
could be stylied through the following properties:

 OverflowButtonText(String): Specifies the text of the overflow button.


 OverflowButtonTextColor(Color): Specifies the text color of the overflow button, which is
displayed when there are more buttons than currently visible.
 OverflowButtonFontFamily(String): Specifies the font family of the overflow button, which is
displayed when there are more buttons than currently visible.
 OverflowButtonTemplate(DataTemplate): Specifies the template of the overflow button,
which is displayed when there are more buttons than currently visible.

Example
Here is an example how to style the RadImageEditor Toolbar.

The snippet below shows how the ImageEditor and the ImageEditorToolbar are defined:

XAML
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<telerikImageEditor:RadImageEditor x:Name="imageEditor">
<telerikImageEditor:RadImageEditor.Source>
<OnPlatform x:TypeArguments="ImageSource" Default="cat4.jpeg">
<On Platform="UWP">Assets\cat4.jpeg</On>
</OnPlatform>
</telerikImageEditor:RadImageEditor.Source>

1137
Telerik UI for Xamarin

</telerikImageEditor:RadImageEditor>
<telerikImageEditor:RadImageEditorToolbar Grid.Row="1" ImageEditor="{x:Reference
imageEditor}" />
</Grid>
 

Then add the Style in the Resources of the page :

XAML
<ResourceDictionary>
<Style TargetType="{x:Type telerikImageEditor:ImageEditorToolbarItem}"
ApplyToDerivedTypes="True">
<Setter Property="TextColor" Value="Black" />
<Setter Property="FontSize" Value="14" />
<Setter Property="SelectedColor" Value="White" />
</Style>
</ResourceDictionary>
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikImageEditor="clr-namespace:Telerik.XamarinForms.ImageEditor;assembly=Tele
rik.XamarinForms.ImageEditor"
 

This is the result:

1138
Telerik UI for Xamarin

See Also
 Custom Toolbar
 Effects
 Image Transformations

1139
Telerik UI for Xamarin

ImageEditor ToolbarItems Styling


The RadImageEditor Toolbar Items could be styled when the Custom Toolbar is created. For more
details how to apply custom Toolbar please check the RadImageEditor Custom Toolbar article.

The following properties could be used for styling each item from the RadImageEditorToolbar:

 Text(String): Specifies the text for the concrete toolbar item.


 TextColor(Color): Defines the text color for the concrete toolbar item.
 SelectedColor(Color): Defines the tex color when the toolbar item is selected.
 Font Options (FontSize, FontFamily, FontAttributes): Defines the font options that are applied
to the concrete ImageEditorToolbar Item.

Example
Here is an example how to style the Custom RadImageEditorToolbar.

The snippet below shows how style the Custom ImageEditorToolbar:

XAML
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<telerikImageEditor:RadImageEditor x:Name="imageEditor">
<telerikImageEditor:RadImageEditor.Source>
<OnPlatform x:TypeArguments="ImageSource" Default="cat4.jpeg">
<On Platform="UWP">Assets\cat4.jpeg</On>
</OnPlatform>
</telerikImageEditor:RadImageEditor.Source>
</telerikImageEditor:RadImageEditor>
<telerikImageEditor:RadImageEditorToolbar Grid.Row="1" ImageEditor="{x:Reference
imageEditor}" AutoGenerateItems="False">
<telerikImageEditor:EffectsToolbarItem AutoGenerateItems="False" Text="Effects"
TextColor="Black" SelectedColor="White">
<telerikImageEditor:ContrastToolbarItem AutoGenerateItems="False"
TextColor="Blue">
<telerikImageEditor:CancelToolbarItem HorizontalOptions="Start"
TextColor="Blue" />
<telerikImageEditor:TemplateToolbarItem TextColor="Blue">
<telerikImageEditor:TemplateToolbarItem.Template>
<DataTemplate>
<Slider Maximum="2" Minimum="0" Value="{Binding Value}" />
</DataTemplate>
</telerikImageEditor:TemplateToolbarItem.Template>
</telerikImageEditor:TemplateToolbarItem>
<telerikImageEditor:ApplyToolbarItem HorizontalOptions="End" TextColor="Blue"/>
</telerikImageEditor:ContrastToolbarItem>

1140
Telerik UI for Xamarin

<telerikImageEditor:BrightnessToolbarItem Text="Brightness"
TextColor="LightSeaGreen" SelectedColor="Black"/>
</telerikImageEditor:EffectsToolbarItem>
</telerikImageEditor:RadImageEditorToolbar>
</Grid>
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikImageEditor="clr-namespace:Telerik.XamarinForms.ImageEditor;assembly=Tele
rik.XamarinForms.ImageEditor"
 

This is the result:

See Also
 Custom Toolbar
 Effects
 Image Transformations

1141
Telerik UI for Xamarin

Overview
Telerik List Picker for Xamarin allows you to select an item from a list of items. This list is visualized
inside a popup. List Picker provides the ability to loop its items infinitely while scrolling. Also you can
fully customize the dialog appearance, style the list items and define templates for the items and for
the selected one.

Key features
 Looping: List Picker for Xamarin provides the ability to loop its items infinitely while scrolling.
For more information in this go to Looping article in our documentation.
 Templates: RadList Picker allows you to define a template for the list items and the selected
one through the ItemTemplate and SelectedItemTemplate properties. To learn more about
this, visit Templates article.
 DisplayString Format: You can choose what text to display when an item from the list was
picked through the Picker DisplayStringFormat property. For more info on this check the Key
Features - Display String section.
 Flexible Styling API: Take advantage of the styling capabilities of RadList Picker by using its
Style properties such as ItemStyle, SelectedItemStyle, etc. You can easily style its Spinners,
the Popup and its header and footer. For more details check the Styling article.
 Commands Support: RadPickerBase class exposes commands that allow you to clear the

1142
Telerik UI for Xamarin

selected item - Clear Command and Toggle Command which allows you to open and close the
dialog. For more information about Commands support check our help article here.

Check out RadList Picker Getting Started help article that shows how to use it in a basic scenario.
 

See Also
 Visual Structure
 Getting Started
 Looping
 Templates
 Styling

1143
Telerik UI for Xamarin

Visual Structure
Here are described all visual elements used in the List Picker for Xamarin.

List Picker Structure before and after an item is selected

List Picker Popup Visual Structure

1144
Telerik UI for Xamarin

Legend
 Placeholder - the text visualized before picking an item from the list of items. Placeholder
could be customized through the PlaceholderTemplate property.
 DisplayStringFormat - the text vislualized after an item from the list of items is picked.
 Header - the text displayed in the popup header. It could se set a direct text through the
HeaderLabelText property or fully customize the popup header using the HeaderTemplate
property
 ItemTemplate - Defines the template used for displaying the list of items. For more
information review Templates article.
 SelectedItemTemplate - Specifies the template used for visualizing the selected item from
the list. For more information review Templates article.
 Footer - the footer of the popup. By default is contains OK and Cancel Buttons. It could be
customized through the FooterTemplate property. For more information review Templates
article.

1145
Telerik UI for Xamarin

Getting Started with List Picker for Xamarin


This article will guide you through the steps needed to add a basic RadListPicker control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadListPicker control

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget packages following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadListPicker control you have to install the
Telerik.UI.for.Xamarin.Input nuget package. This nuget will automatically refer the
Telerik.UI.for.Xamarin.Primitives, Telerik.UI.for.Xamarin.Common and
Telerik.UI.for.Xamarin.DataControls nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadListPicker component:

Platform Assemblies
Portable Telerik.XamarinForms.Input
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.SkiaSharp.dll
Android Telerik.XamarinForms.Input
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.SkiaSharp.dll
iOS Telerik.XamarinForms.Input
Telerik.XamarinForms.Common.dll

1146
Telerik UI for Xamarin

Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.SkiaSharp.dll
UWP Telerik.XamarinForms.Input
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.SkiaSharp.dll

3. Adding RadListPicker control


You could use one of the following approaches:

Drag the control from the Toolbox.

Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML or C#.

The snippet below shows a simple RadListPicker definition:

XAML
<telerikInput:RadListPicker Placeholder="Pick a name!"
ItemsSource="{Binding Items}"
DisplayMemberPath="FullName">
<telerikInput:RadListPicker.BindingContext>
<local:ViewModel/>
</telerikInput:RadListPicker.BindingContext>
<telerikInput:RadListPicker.ItemTemplate>
<DataTemplate>
<Label Text="{Binding Name}"
HorizontalTextAlignment="Center"
VerticalTextAlignment="Center"/>
</DataTemplate>
</telerikInput:RadListPicker.ItemTemplate>
</telerikInput:RadListPicker>
 

C#
this.BindingContext = new ViewModel();
var listPicker = new RadListPicker()
{
Placeholder = "Pick a name!",
ItemTemplate = new DataTemplate(() =>
{
var label = new Label

1147
Telerik UI for Xamarin

{
VerticalTextAlignment = TextAlignment.Center,
HorizontalTextAlignment = TextAlignment.Center
};
label.SetBinding(Label.TextProperty, new Binding(nameof(Person.Name)));

return label;
}),
DisplayMemberPath = "FullName"
};
listPicker.SetBinding(RadListPicker.ItemsSourceProperty, new Binding("Items"));
 

here is a sample definition of the ViewModel:

C#
public class ViewModel
{
public ViewModel()
{
this.Items = new ObservableCollection<Person>()
{
new Person("Freda","Curtis"),
new Person("Jeffery","Francis"),
new Person("Ema","Lawson"),
new Person("Niki","Samaniego"),
new Person("Jenny","Santos"),
new Person("Eric","Wheeler"),
new Person("Emmett","Fuller"),
new Person("Brian","Johnas"),
};
}

public ObservableCollection<Person> Items { get; set; }


}
 

and the Business model:

C#
public class Person
{
public Person(string name, string lastName)
{
this.Name = name;
this.LastName = lastName;
}

public string Name { get; set; }

public string LastName { get; set; }

1148
Telerik UI for Xamarin

public string FullName


{
get
{
return $"{this.Name} {this.LastName}";
}
}
}
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

C#
using Telerik.XamarinForms.Input;
 

This is the result:

SDK Browser and QSF applications contain different examples that show RadListPicker's main
features. You can find the applications in the Examples and QSF folders of your local Telerik UI for
Xamarin installation.
 

1149
Telerik UI for Xamarin

See Also
 Looping
 Templates
 Styling
 Visual Structure

1150
Telerik UI for Xamarin

List Picker from Beta to Official


With R2 2020 Official Release of Telerik UI for Xamarin, the RadListPicker control is now official.
The following article describes the changes made in the List Picker in its official version.

API changes
Placeholder Label Text

Beta Official
Pick a value Select Item

Localization keys
The following table contains the names of the localzation keys which were changed in the official
version of the control:

Beta Official
Pickers_Placeholder DateTimePicker_PlaceholderLabelText
Pickers_Popup_AcceptButtonText Picker_Popup_AcceptButtonText
Pickers_Popup_RejectButtonText Picker_Popup_CancelButtonText

Visual changes
Border below the List Picker text

 BorderThickness(Xamarin.Forms.Thickness): Specifies the border thickness of the picker.


Default value is new Thickness(0,0,0,1).

Header and Footer visibility


With the official version of the control IsHeaderVisible and IsFooterVisible porperties have a public
setter.

By default the header of the ListPicker Popup is visible. In order to hide the header you need to set
IsHeaderVisible property to False. The default value of HeaderLabelText is Select Item.By
default the footer of the ListPikcer Popup is visible. In order to hide the footer you need to set
IsFooterVisible to False.

See Also
 Templates

1151
Telerik UI for Xamarin

 Styling

1152
Telerik UI for Xamarin

Looping in List Picker for Xamarin


List Picker for Xamarin provides looping functionality which allows you to loop the list of items after
reaching the last item.

You can achieve this by setting ListPicker IsLooping(bool) property to true.

Example
The snippet below shows a simple RadListPicker definition:

XAML
<telerikInput:RadListPicker Placeholder="Pick a City Name!"
IsLooping="True"
ItemLength="40"
ItemSpacing="3"
ItemsSource="{Binding Items}"
DisplayMemberPath="Name">
<telerikInput:RadListPicker.BindingContext>
<local:ViewModel/>
</telerikInput:RadListPicker.BindingContext>
<telerikInput:RadListPicker.ItemTemplate>
<DataTemplate>
<Label Text="{Binding Name}"
HorizontalTextAlignment="Center"
VerticalTextAlignment="Center"/>
</DataTemplate>
</telerikInput:RadListPicker.ItemTemplate>
</telerikInput:RadListPicker>
 

A sample business model:

C#
public class City
{
public string Name { get; set; }
public int Population { get; set; }
}
 

and a ViewModel:

C#
public class ViewModel
{
public ViewModel()
{

1153
Telerik UI for Xamarin

this.Items = new ObservableCollection<City>


{
new City { Name = "Tokyo", Population = 13929286 },
new City { Name = "New York", Population = 8623000 },
new City { Name = "London", Population = 8908081 },
new City { Name = "Madrid", Population = 3223334 },
new City { Name = "Los Angeles", Population = 4000000},
new City { Name = "Paris", Population = 2141000 },
new City { Name = "Beijing", Population = 21540000 },
new City { Name = "Singapore", Population = 5612000 },
new City { Name = "New Delhi", Population = 18980000 },
new City { Name = "Bangkok", Population = 8305218 },
new City { Name = "Berlin", Population = 3748000 },
};
}

public ObservableCollection<City> Items { get; set; }


}
 

This is how the Looping functionality looks:

1154
Telerik UI for Xamarin

A sample Looping example can be found in the ListPicker/Looping folder of the SDK Samples
Browser application.
 

See Also
 Templates

1155
Telerik UI for Xamarin

 Styling
 Selection
 Commands

1156
Telerik UI for Xamarin

Templates
List Picker for Xamarin provides the following templates:

 ItemTemplate(DataTemplate): Defines the template used for displaying the list of items.
 SelectedItemTemplate(DataTemplate): Specifies the template used for visualizing the
selected item from the list.

In addition to this you can define the following templates provided from the RadPickerBase class:

 PlaceholderTemplate(ControlTemplate): Defines the template visualized for the placeholder.


 DisplayTemplate(ControlTemplate): Defines the template visualized when an item from the
list is selected.

And using RadPickerBase.SelectorSettings property(of type


Telerik.XamarinForms.Input.PickerPopupSelectorSettings) you can define the following templates:

 HeaderTemplate(ControlTemplate): Defines what will be displayed inside the dialog(popup)


header.
 FooterTemplate(ControlTemplate): Defines what will be displayed inside the dialog(popup)
footer.

This is the Visual Srtucture of the List Picker Templates:

1157
Telerik UI for Xamarin

In addition the List Picker for Xamarin provides the following properties:

 ItemsSource(IList): Specifies the collection used to generate the content of the list picker.
 ItemLength(double): Defines the length of the items inside the list.
 ItemSpacing(double): Defines the spacing between the items inside the list.
 SelectedItem(object): Specifies the selected item of the list picker
 DisplayMemberPath(string): Defines the path of the property which is to be displayed as
DisplayString.

Example
Here is a sample List Picker definition:

XAML
<telerikInput:RadListPicker PlaceholderTemplate="{StaticResource placeholderTemplate}"
ItemTemplate="{StaticResource itemTemplate}"
SelectedItemTemplate="{StaticResource selectedItemTemplate}"
ItemLength="40"
ItemSpacing="4"

1158
Telerik UI for Xamarin

ItemsSource="{Binding Items}"
DisplayMemberPath="Name"
x:Name="listPicker">
<telerikInput:RadListPicker.BindingContext>
<local:ViewModel/>
</telerikInput:RadListPicker.BindingContext>
<telerikInput:RadListPicker.SelectorSettings>
<telerikInput:PickerPopupSelectorSettings HeaderTemplate="{StaticResource
headerTemplate}"
FooterTemplate="{StaticResource footerTemplate}"/>
</telerikInput:RadListPicker.SelectorSettings>
</telerikInput:RadListPicker>
 

and the templates definition in the page resources:

Item Template
XAML
<DataTemplate x:Key="itemTemplate">
<Label Text="{Binding Population}"
BackgroundColor="LightYellow"
HorizontalTextAlignment="Center"
VerticalTextAlignment="Center"/>
</DataTemplate>
 

SelectedItem Template
XAML
<DataTemplate x:Key="selectedItemTemplate">
<Label Text="{Binding Name}"
BackgroundColor="LightBlue"
HorizontalTextAlignment="Center"
VerticalTextAlignment="Center"/>
</DataTemplate>
 

Placeholder Template
XAML
<ControlTemplate x:Key="placeholderTemplate">
<Label Text="Tap to open list picker"
FontAttributes="Bold"
TextColor="White"
BackgroundColor="#B73562"
HeightRequest="50"
VerticalTextAlignment="Center"
HorizontalTextAlignment="Center">

1159
Telerik UI for Xamarin

<Label.GestureRecognizers>
<TapGestureRecognizer Command="{TemplateBinding ToggleCommand}" />
</Label.GestureRecognizers>
</Label>
</ControlTemplate>
 

DisplayTemplate
XAML
<telerikInput:RadListPicker ItemsSource="{Binding Items}"
DisplayMemberPath="Name">
<telerikInput:RadListPicker.DisplayTemplate>
<ControlTemplate>
<StackLayout>
<Label Text="This is the DisplayTemplate of the ListPicker" FontSize="10"/>
<Label Text="{TemplateBinding DisplayString}" TextColor="Black" FontSize="15"
Grid.Row="1" VerticalTextAlignment="Center"/>
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Command="{TemplateBinding ToggleCommand}" />
</StackLayout.GestureRecognizers>
</StackLayout>
</ControlTemplate>
</telerikInput:RadListPicker.DisplayTemplate>
</telerikInput:RadListPicker>
 

Header Template
XAML
<ControlTemplate x:Key="headerTemplate">
<Label Text="Select city:"
TextColor="White"
FontSize="16"
VerticalTextAlignment="Center"
HorizontalTextAlignment="Center"
BackgroundColor="#B73562"/>
</ControlTemplate>
 

Footer Template
XAML
<ControlTemplate x:Key="footerTemplate">
<StackLayout Orientation="Horizontal" Spacing="0"
HorizontalOptions="FillAndExpand" BackgroundColor="#B73562">
<Button Text="Cancel"
TextColor="White"
BackgroundColor="Transparent"

1160
Telerik UI for Xamarin

Command="{TemplateBinding CancelCommand}" />


<Button Text="OK"
TextColor="White"
BackgroundColor="Transparent"
Command="{TemplateBinding AcceptCommand}" />
</StackLayout>
</ControlTemplate>
 

and a sample business model:

C#
public class City
{
public string Name { get; set; }
public int Population { get; set; }
}
 

and the ViewModel:

C#
public class ViewModel
{
public ViewModel()
{
this.Items = new ObservableCollection<City>
{
new City { Name = "Tokyo", Population = 13929286 },
new City { Name = "New York", Population = 8623000 },
new City { Name = "London", Population = 8908081 },
new City { Name = "Madrid", Population = 3223334 },
new City { Name = "Los Angeles", Population = 4000000},
new City { Name = "Paris", Population = 2141000 },
new City { Name = "Beijing", Population = 21540000 },
new City { Name = "Singapore", Population = 5612000 },
new City { Name = "New Delhi", Population = 18980000 },
new City { Name = "Bangkok", Population = 8305218 },
new City { Name = "Berlin", Population = 3748000 },
};
}

public ObservableCollection<City> Items { get; set; }


}
 

also you will need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

1161
Telerik UI for Xamarin

This is the result:

A sample Templates example can be found in the ListPicker/Features folder of the SDK Samples
Browser application.
 

See Also
 Styling

1162
Telerik UI for Xamarin

List Picker Localization


RadDateTime Picker for Xamarin provides language localization. In short, you can translate the used
across the List Picker texts to other languages, so that your app can be adapted to different regions.

To learn in details about the localization process of Telerik UI for Xamarin components, please go
through the common Localization and Globalization topic.
 

ListPicker Localization Key


Localization Key Default Value
ListPicker_Popup_HeaderLabelText Select Item
ListPicker_PlaceholderLabelText Select Item

Common Picker Localizations strings


Localization Key Default Value
Picker_Popup_AcceptButtonText OK
Picker_Popup_CancelButtonText Cancel
Check in the image below how the common localization strings are presented in List Picker:

1163
Telerik UI for Xamarin

See Also
 Localization and Globalization

1164
Telerik UI for Xamarin

Selection
ListPicker for Xamarin enables the app users to quickly and easily select an item from a list of items.
This topic will go through the provided by the ListPicker API related to item selection.

Important Properties
 SelectedItem(object): Specifies the selected item of the list picker.

Methods
List Picker for Xamarin allows you to clear the selected date/time through its ClearSelection method

Example
XAML
<StackLayout>
<Button Text="Clear Selection" Clicked="OnClearSelectionClicked"/>
<telerikInput:RadListPicker x:Name="listPicker"
Placeholder="Pick a name!"
ItemsSource="{Binding Items}"
DisplayMemberPath="FullName">
<telerikInput:RadListPicker.BindingContext>
<local:ViewModel/>
</telerikInput:RadListPicker.BindingContext>
<telerikInput:RadListPicker.ItemTemplate>
<DataTemplate>
<Label Text="{Binding Name}"
HorizontalTextAlignment="Center"
VerticalTextAlignment="Center"/>
</DataTemplate>
</telerikInput:RadListPicker.ItemTemplate>
</telerikInput:RadListPicker>
</StackLayout>
 

and we can clear the selection inside the button click event:

C#
private void OnClearSelectionClicked(object sender, EventArgs e)
{
this.listPicker.ClearSelection();
}
 

a sample ViewModel:

1165
Telerik UI for Xamarin

C#
public class ViewModel
{
public ViewModel()
{
this.Items = new ObservableCollection<Person>()
{
new Person("Freda","Curtis"),
new Person("Jeffery","Francis"),
new Person("Ema","Lawson"),
new Person("Niki","Samaniego"),
new Person("Jenny","Santos"),
new Person("Eric","Wheeler"),
new Person("Emmett","Fuller"),
new Person("Brian","Johnas"),
};
}

public ObservableCollection<Person> Items { get; set; }


}
 

and the Business model:

C#
public class Person
{
public Person(string name, string lastName)
{
this.Name = name;
this.LastName = lastName;
}

public string Name { get; set; }

public string LastName { get; set; }

public string FullName


{
get
{
return $"{this.Name} {this.LastName}";
}
}
}
 

also you will need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"

1166
Telerik UI for Xamarin

Events
List Picker for Xamarin exposes a SelectionChanged event which is raised when the user confirms
the selected item.

Example
XAML
<telerikInput:RadListPicker Placeholder="Pick a name!"
ItemsSource="{Binding Items}"
SelectionChanged="RadListPicker_SelectionChanged"
DisplayMemberPath="FullName">
<telerikInput:RadListPicker.BindingContext>
<local:ViewModel/>
</telerikInput:RadListPicker.BindingContext>
<telerikInput:RadListPicker.ItemTemplate>
<DataTemplate>
<Label Text="{Binding Name}"
HorizontalTextAlignment="Center"
VerticalTextAlignment="Center"/>
</DataTemplate>
</telerikInput:RadListPicker.ItemTemplate>
</telerikInput:RadListPicker>
 

and the SelectionChanged event, where sender is the RadListPicker control:

C#
private void RadListPicker_SelectionChanged(object sender, System.EventArgs e)
{
// implement your logic here
}
 

a sample ViewModel:

C#
public class ViewModel
{
public ViewModel()
{
this.Items = new ObservableCollection<Person>()
{
new Person("Freda","Curtis"),
new Person("Jeffery","Francis"),
new Person("Ema","Lawson"),
new Person("Niki","Samaniego"),
new Person("Jenny","Santos"),

1167
Telerik UI for Xamarin

new Person("Eric","Wheeler"),
new Person("Emmett","Fuller"),
new Person("Brian","Johnas"),
};
}

public ObservableCollection<Person> Items { get; set; }


}
 

and the Business model:

C#
public class Person
{
public Person(string name, string lastName)
{
this.Name = name;
this.LastName = lastName;
}

public string Name { get; set; }

public string LastName { get; set; }

public string FullName


{
get
{
return $"{this.Name} {this.LastName}";
}
}
}
 

where the sender is the RadListPicker control.

also you will need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

See Also
 Commands

1168
Telerik UI for Xamarin

Commands
ListPicker Commands
List Picker for Xamarin exposes the following commands you can use to programmatically
manipulate displaying the popup as well as clearing the selected item:

 ToggleCommand(ICommand): Allows you to show/hide the popup used for selecting an item
from a list of items.
 ClearCommand(ICommand): Allows you to clear the displayed item.

PopupSelector Commands
Through the popup users can pick an item. The date value should be confirmed or rejected through
the OK and Cancel buttons placed on the popup.

ListPicker allows you to add a custom logic for the Accept and Cancel commands which are
executed when OK and Cancel buttons, respectively, are pressed.

 AcceptCommand(ICommand): Defines the command which confirms the current selection of


the picker and closes the popup. AcceptCommandParameter can be used to pass a
parameter to the command execute method.
 CancelCommand(ICommand): Defines the command which rejects the current selection of
the picker and closes the popup. CancelCommandParameter can be used to pass a
parameter to the command execute method.

The Accept and Cancel commands can be applied using the SelectorSettings property of
RadListPicker. In addition, you can pass command parameters through the
AcceptCommandParameter and CancelCommandParameter properties of the ListPicker
SelectorSettings.

Example
Here is the List Picker definition:

XAML
<StackLayout>
<Button Text="Toggle Command" Command="{Binding Source={x:Reference listPicker},
Path=ToggleCommand}"/>
<Button Text="Clear Command" Command="{Binding Source={x:Reference listPicker},
Path=ClearCommand}"/>
<telerikInput:RadListPicker Placeholder="Pick a name!"
x:Name="listPicker"
ItemsSource="{Binding Items}"
DisplayMemberPath="FullName">
<telerikInput:RadListPicker.SelectorSettings>
<telerikInput:PickerPopupSelectorSettings AcceptCommand="{Binding Accept}"

1169
Telerik UI for Xamarin

AcceptCommandParameter="{Binding SelectedItem, Source={x:Reference


listPicker}}"
CancelCommand="{Binding Cancel}"
CancelCommandParameter="{Binding SelectedItem, Source={x:Reference
listPicker}}" />
</telerikInput:RadListPicker.SelectorSettings>
<telerikInput:RadListPicker.BindingContext>
<local:ViewModel/>
</telerikInput:RadListPicker.BindingContext>
</telerikInput:RadListPicker>
</StackLayout>
 

a sample ViewModel:

C#
public class ViewModel
{
public ICommand Accept { get; set; }
public ICommand Cancel { get; set; }

public ObservableCollection<Person> Items { get; set; }


public ViewModel()
{
this.Items = new ObservableCollection<Person>()
{
new Person("Freda","Curtis"),
new Person("Jeffery","Francis"),
new Person("Ema","Lawson"),
new Person("Niki","Samaniego"),
new Person("Jenny","Santos"),
new Person("Eric","Wheeler"),
new Person("Emmett","Fuller"),
new Person("Brian","Johnas"),
};

this.Accept = new Command(this.OnAccept);


this.Cancel = new Command(this.OnCancel);
}

private void OnAccept(object param)


{
Application.Current.MainPage.DisplayAlert("Item selected", "New Item: " +
(param as Person).FullName, "OK");
// implement your custom logic here
}

private void OnCancel(object param)


{
var message = param != null ? "Current item" + (param as Person).FullName :
"Currently no item is selected";
Application.Current.MainPage.DisplayAlert("Item Selection Canceled", message,
"OK");

1170
Telerik UI for Xamarin

// implement your custom logic here


}
}
 

and the Business model:

C#
public class Person
{
public Person(string name, string lastName)
{
this.Name = name;
this.LastName = lastName;
}

public string Name { get; set; }

public string LastName { get; set; }

public string FullName


{
get
{
return $"{this.Name} {this.LastName}";
}
}
}
 

also you will need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

See Also
 Selection
 Templates

1171
Telerik UI for Xamarin

Styling
ListPicker Styling
List Picker for Xamarin provides the followind Style properties for customizing its look:

 ItemStyle(of type Style with target type telerikDataControls:SpinnerItemView): Defines the


style applied to the list of items.
 SelectedItemStyle(of type Style with target type telerikDataControls:SpinnerItemView):
Defines the style applied to the seledted item.
 SelectionHighlightStyle(of type Style with target type telerikPrimitives:RadBorder): Specifies
the style applied to the border where the current selection is.
 PlaceholderLabelStyle(of type Style with target type Label): Defines the style applied to the
placeholder label.
 DisplayLabelStyle(of type Style with target type Label): Defines the style applied to the label
which is visualized when item of the list is selected.

PickerContentView class exposes the following properties for styling the ListPicker Border and
Background Color:

 BackgroundColor(Xamarin.Forms.Color): Defines the background color of the picker.


 BorderColor(Xamarin.Forms.Color): Defines the border color of the picker.
 BorderThickness(Xamarin.Forms.Thickness): Specifies the border thickness of the picker.
Default value is new Thickness(0,0,0,1).
 CornerRadius(Xamarin.Forms.Thinckness): Specifies the corner radius of the picker.

Popup Styling
Using the SelectorSettings property (of type
Telerik.XamarinForms.Input.PickerPopupSelectorSettings) of the ListPicker you can modify the
appearance of the dialog (popup). PickerPopupSelectorSettings class exposes the following Style
properties:

 PopupViewStyle(of type Style with target type telerikInput:PickerPopupContentView):


Defines the popup view style.
 HeaderStyle(of type Style with target type telerikInput:PickerPopupHeaderView): Defines the
popup header style.
 HeaderLabelStyle(of type Style with target type Label): Defines the popup header label style.
 FooterStyle(of type Style with target type telerikInput:PickerPopupFooterView): Defines the
popup footer style.
 AcceptButtonStyle(of type Style with target type Button): Defines the Accept button style.
 CancelButtonStyle(of type Style with target type Button): Defines the Cancel button style.

The SelectorSetting also provides the following properties for popup customization:

 PopupOutsideBackgroundColor(Xamarin.Forms.Color): Defines the color outside of the


popup.

1172
Telerik UI for Xamarin

 IsPopupModal(bool): Defines a boolean value indicating if the popup should be closed when
tapped outside of the popup. By default the value of the IsPopupModal is false.
 When IsPopupModal="True" the UI behind the popup gets inactive and cannot be used
until the popup is closed.
 When IsPopupModal="False" the popup could be closed when clicking outside the
popup.
 HeaderLabelText(string): Specifies the text visualized in the popup header. The default text
is Select Item.
 IsHeaderVisible(bool): Specifies whether the Popup header is currently visible. By default the
valuse is True.
 IsFooterVisible(bool): Specifies whether the Popup footer is currently visible. By default the
valuse is True.
 AcceptButtonText(string): Defines the text visualized for the accept button. By default the text
is OK.
 CancelButtonText(string): Defines the text visualized for the cancel button. By default the text
is Cancel.

Namespaces
Using ItemStyle, SelectedItemStyle you need to add the following namespace:

XAML
xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te
lerik.XamarinForms.DataControls"
 

Using PopupViewStyle, HeaderStyle, FooterStyle add the followng namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

The SelectionHighlightStyle requires the following namespace:

XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
 

Example
Here is a sample example that shows how the styling properties are applied.

A sample List Picker definition:

XAML
<telerikInput:RadListPicker Placeholder="Pick a City Name!"
ItemsSource="{Binding Items}"

1173
Telerik UI for Xamarin

DisplayMemberPath="Name"
IsLooping="True"
DisplayStringFormat="You have picked: {0}"
DisplayLabelStyle="{StaticResource displayLabelStyle}"
ItemStyle="{StaticResource ItemStyle}"
SelectedItemStyle="{StaticResource SelectedItemStyle}"
PlaceholderLabelStyle="{StaticResource placeholderLabelStyle}">
<telerikInput:RadListPicker.BindingContext>
<local:ViewModel/>
</telerikInput:RadListPicker.BindingContext>
<telerikInput:RadListPicker.SelectorSettings>
<telerikInput:PickerPopupSelectorSettings
PopupOutsideBackgroundColor="#4A4949F"
PopupViewStyle="{StaticResource popupViewStyle}"
HeaderStyle="{StaticResource headerStyle}"
HeaderLabelText="Select city"
HeaderLabelStyle="{StaticResource headerLabelStyle}"
FooterStyle="{StaticResource footerStyle}"
AcceptButtonStyle="{StaticResource acceptButtonStyle}"
CancelButtonStyle="{StaticResource cancelButtonStyle}"/>
</telerikInput:RadListPicker.SelectorSettings>
</telerikInput:RadListPicker>
 

and here are how the styles are defined in the page resources

Item Style
XAML
<Style TargetType="telerikDataControls:SpinnerItemView" x:Key="ItemStyle">
<Setter Property="BackgroundColor" Value="#F8F8F8"/>
<Setter Property="CornerRadius" Value="0"/>
<Setter Property="TextColor" Value="#919191" />
<Setter Property="FontSize" Value="12"/>
</Style>
 

SelectedItem Style
XAML
<Style TargetType="telerikDataControls:SpinnerItemView" x:Key="SelectedItemStyle">
<Setter Property="BackgroundColor" Value="#F0F0F0"/>
<Setter Property="CornerRadius" Value="0"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="TextColor" Value="#4A4949" />
<Setter Property="FontSize" Value="16"/>
</Style>
 

PlaceholderLabel Style

1174
Telerik UI for Xamarin

XAML
<Style TargetType="Label" x:Key="placeholderLabelStyle">
<Setter Property="TextColor" Value="#4A4949"/>
<Setter Property="VerticalTextAlignment" Value="Center"/>
<Setter Property="HorizontalTextAlignment" Value="Center"/>
<Setter Property="HeightRequest" Value="50"/>
</Style>
 

DisplayLabel Style
XAML
<Style TargetType="Label" x:Key="displayLabelStyle">
<Setter Property="TextColor" Value="Black"/>
<Setter Property="VerticalTextAlignment" Value="Center"/>
<Setter Property="HorizontalTextAlignment" Value="Center"/>
<Setter Property="HeightRequest" Value="50"/>
</Style>
 

PopupView Style
XAML
<Style TargetType="telerikInput:PickerPopupContentView" x:Key="popupViewStyle">
<Setter Property="BackgroundColor" Value="White"/>
<Setter Property="WidthRequest" Value="270"/>
</Style>
 

Header Style
XAML
<Style TargetType="telerikInput:PickerPopupHeaderView" x:Key="headerStyle">
<Setter Property="BackgroundColor" Value="#1188FF"/>
<Setter Property="HeightRequest" Value="64"/>
<Setter Property="Margin" Value="0"/>
<Setter Property="Padding" Value="0"/>
<Setter Property="HorizontalOptions" Value="FillAndExpand"/>
<Setter Property="VerticalOptions" Value="FillAndExpand"/>
</Style>
 

HeaderLabel Style
XAML
<Style TargetType="Label" x:Key="headerLabelStyle">
<Setter Property="TextColor" Value="White"/>
<Setter Property="HorizontalOptions" Value="Center"/>

1175
Telerik UI for Xamarin

<Setter Property="VerticalOptions" Value="Center"/>


<Setter Property="FontSize" Value="18"/>
<Setter Property="FontAttributes" Value="Bold"/>
</Style>
 

FooterStyle
XAML
<Style TargetType="telerikInput:PickerPopupFooterView" x:Key="footerStyle">
<Setter Property="BackgroundColor" Value="Transparent"/>
<Setter Property="HeightRequest" Value="60"/>
</Style>
 

AcceptButton Style
XAML
<Style TargetType="Button" x:Key="acceptButtonStyle">
<Setter Property="BackgroundColor" Value="Transparent"/>
<Setter Property="Text" Value="OK"/>
<Setter Property="TextColor" Value="#1188FF"/>
</Style>
 

CancelButton Style
XAML
<Style TargetType="Button" x:Key="cancelButtonStyle">
<Setter Property="BackgroundColor" Value="Transparent"/>
<Setter Property="Text" Value="CANCEL"/>
<Setter Property="TextColor" Value="#1188FF"/>
</Style>
 

A sample business model:

C#
public class City
{
public string Name { get; set; }
public int Population { get; set; }
}
 

and a ViewModel:

C#

1176
Telerik UI for Xamarin

public class ViewModel


{
public ViewModel()
{
this.Items = new ObservableCollection<City>
{
new City { Name = "Tokyo", Population = 13929286 },
new City { Name = "New York", Population = 8623000 },
new City { Name = "London", Population = 8908081 },
new City { Name = "Madrid", Population = 3223334 },
new City { Name = "Los Angeles", Population = 4000000},
new City { Name = "Paris", Population = 2141000 },
new City { Name = "Beijing", Population = 21540000 },
new City { Name = "Singapore", Population = 5612000 },
new City { Name = "New Delhi", Population = 18980000 },
new City { Name = "Bangkok", Population = 8305218 },
new City { Name = "Berlin", Population = 3748000 },
};
}

public ObservableCollection<City> Items { get; set; }


}
 

also you will need to add the following namespaces:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te
lerik.XamarinForms.DataControls"
 

This is how the List Picker looks when the styling properties are applied:

1177
Telerik UI for Xamarin

A sample Styling example can be found in the ListPicker/Features folder of the SDK Samples
Browser application.
 

See Also
 Looping
 Templates

1178
Telerik UI for Xamarin

Overview
RadListView is a virtualizing list component that provides the most popular features associated with
scenarios where a list of items is used. All these features are embedded in one control with the idea
to save developer's time and provide better experience.

Figure 1: RadListView Overview

Key features
 Selection: RadListView supports both single and multiple selection, additionally items can be
selected on tap or on hold gestures. For more details check Selection article.
 Different layouts and orientation: You could choose between linear and grid layout as well as
define the scroll direction of the layout. Read more about this in the Layouts topic.
 ItemTemplateSelector: RadListView control exposes an ItemTemplateSelector property
which you can use to apply different template to each item depending on a specific condition.
Read more about it in the ItemTemplateSelector topic.
 Reorder Items: Allows end-users to reorder ListView items using drag and drop. Read more

1179
Telerik UI for Xamarin

about it in the Reorder Items topic.


 Load on demand: In addition to the built-in UI virtualization, the control supports
load-on-demand. This optimizes the initial loading of the app and the new items are loaded
before the user reaches the bottom of the ListView. Read more about this functionality in the
Load on Demand article.
 Item Swipe: The item swipe feature enables end-users to swipe an item to reveal actionable
content beneath. For more details check Cell Swipe topic.
 Grouping, sorting and filtering: You could easily visualize your items in groups, sorted and
filtered in accordance with your criteria. For detailed instructions on how to enable these
features, check Grouping, Sorting and Filtering topics.
 Customizable Items: Take advantage of the styling capabilities of RadListView by using its
Style properties such as ItemStyle, SelectedItemStyle, etc. For more details check Styling
article.

See Also
 Getting Started

1180
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadListView control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadListView control
 Populating RadListView with data

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadListView control you have to install the
Telerik.UI.for.Xamarin.DataControls nuget package. This nuget will automatically refer the
Telerik.UI.for.Xamarin.Primitives and Telerik.UI.for.Xamarin.Common nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadListView component:

Platform Assemblies
Portable Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.SkiSharp.dll
Android Telerik.Xamarin.Android.Common.dll
Telerik.Xamarin.Android.Data.dll
Telerik.Xamarin.Android.Input.dll
Telerik.Xamarin.Android.List.dll
Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.Primitives.dll

1181
Telerik UI for Xamarin

Telerik.XamarinForms.SkiSharp.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.SkiSharp.dll
UWP Telerik.Core.dll
Telerik.Data.dll
Telerik.UI.Xaml.Controls.Data.UWP.dll
Telerik.UI.Xaml.Input.UWP.dll
Telerik.UI.Xaml.Primitives.UWP.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.SkiSharp.dll

3. Adding RadListView control


You could use one of the following approaches:

Drag the control from the Toolbox.

Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML or C# .

The snippet below shows a simple RadListView definition (Do not use a StackLayout or
ScrollView parent, see the WARNING note below):

XAML
<telerikDataControls:RadListView x:Name="listView" />
 

C#
var listView = new RadListView();
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te
lerik.XamarinForms.DataControls"
 

C#

1182
Telerik UI for Xamarin

using Telerik.XamarinForms.DataControls;
 

WARNING: RadListView control provides UI virtualization, this feature requires the visual parent to
provide vertical or horizontal space. To avoid breaking UI virtualization or gesture mechanisms,
please follow these rules:

 Do not place the RadListView control inside a StackLayout


 Do not place the RadListVew inside a ScrollView
 Do not set the RadListVew to a Grid RowDefinition Height="Auto"

For additional information and solutions for these layouts, please check the Controls are not
Apppearing article.

4. Populating RadListView with data


First, lets create a simple data and view model classes:

C#
public class SourceItem
{
public SourceItem(string name)
{
this.Name = name;
}

public string Name { get; set; }


}

public class ViewModel


{
public ViewModel()
{
this.Source = new List<SourceItem> { new SourceItem("Tom"), new
SourceItem("Anna"), new SourceItem("Peter"), new SourceItem("Teodor"), new
SourceItem("Lorenzo"), new SourceItem("Andrea"), new SourceItem("Martin") };
}

public List<SourceItem> Source { get; set; }


}
 

Here is the setup of the ListView:

XAML
<telerikDataControls:RadListView x:Name="listView" ItemsSource="{Binding Source}">
<telerikDataControls:RadListView.BindingContext>
<local:ViewModel />
</telerikDataControls:RadListView.BindingContext>

1183
Telerik UI for Xamarin

<telerikDataControls:RadListView.ItemTemplate>
<DataTemplate>
<telerikListView:ListViewTemplateCell>
<telerikListView:ListViewTemplateCell.View>
<Grid>
<Label Margin="10" Text="{Binding Name}" />
</Grid>
</telerikListView:ListViewTemplateCell.View>
</telerikListView:ListViewTemplateCell>
</DataTemplate>
</telerikDataControls:RadListView.ItemTemplate>
</telerikDataControls:RadListView>
 

C#
var listView = new RadListView
{
ItemsSource = new ViewModel().Source,
ItemTemplate = new DataTemplate(() =>
{
var label = new Label { Margin = new Thickness(10) };
var content = new Grid();
content.Children.Add(label);
label.SetBinding(Label.TextProperty, new Binding(nameof(SourceItem.Name)));

return new ListViewTemplateCell


{
View = content
};
})
};
 

You have to add the following namespaces:

XAML
xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te
lerik.XamarinForms.DataControls"
xmlns:telerikListView="clr-namespace:Telerik.XamarinForms.DataControls.ListView;assemb
ly=Telerik.XamarinForms.DataControls"
 

C#
using Telerik.XamarinForms.DataControls;
using Telerik.XamarinForms.DataControls.ListView;
 

This is the result:

1184
Telerik UI for Xamarin

SDK Browser and QSF applications contain different examples that show RadListView's main
features. You can find the applications in the Examples and QSF folders of your local Telerik UI for
Xamarin installation.
 

See Also
 Cell Types
 Selection
 Grouping

1185
Telerik UI for Xamarin

ListView Cell Types


Cells in RadListView are the presentation of each data item from the control's ItemsSource. You can
choose between two types of cells, namely:

 ListViewTextCell derives from Xamarin.Forms.TextCell and displays text. It can optionally


render detail text as a second row within a list view item. This is the default cell of the
RadListView.
 ListViewTemplateCell derives from Xamarin.Forms.ViewCell and used to present complex
data sets as RadListView.ItemTemplate.

ListViewTextCell Example
This example demonstrates how to create a list view with text cells, like this:

1. Create a view model that will be the source of the list view:

C#
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
}

public class ViewModel

1186
Telerik UI for Xamarin

{
public ViewModel()
{
this.Source = new List<Book>{
new Book{ Title = "The Fault in Our Stars ", Author = "John Green"},
new Book{ Title = "Divergent", Author = "Veronica Roth"},
new Book{ Title = "Gone Girl", Author = "Gillian Flynn"},
new Book{ Title = "Clockwork Angel", Author = "Cassandra Clare"},
new Book{ Title = "The Martian", Author = "Andy Weir"},
new Book{ Title = "Ready Player One", Author = "Ernest Cline"},
new Book{ Title = "The Lost Hero", Author = "Rick Riordan"},
new Book{ Title = "All the Light We Cannot See", Author = "Anthony Doerr"},
new Book{ Title = "Cinder", Author = "Marissa Meyer"},
new Book{ Title = "Me Before You", Author = "Jojo Moyes"},
new Book{ Title = "The Night Circus", Author = "Erin Morgenstern"},
};
}

public List<Book> Source { get; set; }


}
 

1. Add the definition of the listview control:

XAML
<telerikDataControls:RadListView ItemsSource="{Binding Source}" x:Name="listView">
<telerikDataControls:RadListView.BindingContext>
<local:ViewModel />
</telerikDataControls:RadListView.BindingContext>
<telerikDataControls:RadListView.ItemTemplate>
<DataTemplate>
<telerikListView:ListViewTextCell Text="{Binding Title}" Detail="{Binding
Author}" TextColor="Black" DetailColor="Gray" />
</DataTemplate>
</telerikDataControls:RadListView.ItemTemplate>
<telerikDataControls:RadListView.LayoutDefinition>
<telerikListView:ListViewLinearLayout ItemLength="60" />
</telerikDataControls:RadListView.LayoutDefinition>
</telerikDataControls:RadListView>
 

C#
var listView = new RadListView
{
ItemsSource = new ViewModel().Source,
ItemTemplate = new DataTemplate(() =>
{
var cell = new ListViewTextCell
{
TextColor = Color.Black,
DetailColor = Color.Gray,
};

1187
Telerik UI for Xamarin

cell.SetBinding(ListViewTextCell.TextProperty, new
Binding(nameof(Book.Title)));
cell.SetBinding(ListViewTextCell.DetailProperty, new
Binding(nameof(Book.Author)));

return cell;
}),
LayoutDefinition = new ListViewLinearLayout { ItemLength = 60 },
};
 

1. Add the following namespaces:

XAML
xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te
lerik.XamarinForms.DataControls"
xmlns:telerikListView="clr-namespace:Telerik.XamarinForms.DataControls.ListView;assemb
ly=Telerik.XamarinForms.DataControls"
 

C#
using Telerik.XamarinForms.DataControls;
using Telerik.XamarinForms.DataControls.ListView;
 

1. Finally, set the list view as the content of your page.

ListViewTemplateCell Example
This example demonstrates how to create a list view with templated cells, like this:

1188
Telerik UI for Xamarin

1. Create a view model that will be the source of the list view:

C#
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
public bool IsFavourite { get; set; }
}

public class ViewModel


{
public ViewModel()
{
this.Source = new List<Book>{
new Book{ Title = "The Fault in Our Stars ", Author = "John Green"},
new Book{ Title = "Divergent", Author = "Veronica Roth"},
new Book{ Title = "Gone Girl", Author = "Gillian Flynn", IsFavourite = true},
new Book{ Title = "Clockwork Angel", Author = "Cassandra Clare"},
new Book{ Title = "The Martian", Author = "Andy Weir"},
new Book{ Title = "Ready Player One", Author = "Ernest Cline"},
new Book{ Title = "The Lost Hero", Author = "Rick Riordan", IsFavourite =
true},
new Book{ Title = "All the Light We Cannot See", Author = "Anthony Doerr"},
new Book{ Title = "Cinder", Author = "Marissa Meyer"},
new Book{ Title = "Me Before You", Author = "Jojo Moyes"},
new Book{ Title = "The Night Circus", Author = "Erin Morgenstern"},
};
}

1189
Telerik UI for Xamarin

public List<Book> Source { get; set; }


}
 

1. Define the listview control either in Xaml or in code behind.

You can define the list view in Xaml like this:

XAML
<telerikDataControls:RadListView ItemsSource="{Binding Source}" x:Name="listView">
<telerikDataControls:RadListView.BindingContext>
<local:ViewModel />
</telerikDataControls:RadListView.BindingContext>
<telerikDataControls:RadListView.ItemTemplate>
<DataTemplate>
<telerikListView:ListViewTemplateCell>
<telerikListView:ListViewTemplateCell.View>
<Grid>
<StackLayout Orientation="Horizontal" Margin="10, 10, 10, 0">
<Image IsVisible="{Binding IsFavourite}" Source="favourite.png"
HeightRequest="16" VerticalOptions="Center" />
<Label Text="{Binding Title}" FontSize="16" FontAttributes="Bold"
TextColor="Black" VerticalOptions="Center" />
</StackLayout>
<StackLayout Orientation="Horizontal" Grid.Row="1" Margin="10, 0, 10, 10">
<Label Text="by" FontSize="13" FontAttributes="Italic" TextColor="Gray" />
<Label Text="{Binding Author}" FontSize="13" FontAttributes="Italic"
TextColor="Gray" />
</StackLayout>
</Grid>
</telerikListView:ListViewTemplateCell.View>
</telerikListView:ListViewTemplateCell>
</DataTemplate>
</telerikDataControls:RadListView.ItemTemplate>
</telerikDataControls:RadListView>
 

 Define the namespace

XAML
xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te
lerik.XamarinForms.DataControls"
xmlns:telerikListView="clr-namespace:Telerik.XamarinForms.DataControls.ListView;assemb
ly=Telerik.XamarinForms.DataControls"
 

 You can define the list view in code behind:


 For clarity, let's build the template of the list view cell in a separate method:

C#
public View GetCellContent()
{

1190
Telerik UI for Xamarin

var content = new Grid();

var book = new Label


{
FontAttributes = FontAttributes.Bold,
TextColor = Color.Black,
FontSize = 16,
VerticalOptions = LayoutOptions.Center
};

book.SetBinding(Label.TextProperty, new Binding(nameof(Book.Title)));

var fav = new Image


{
Source = ImageSource.FromFile("favourite.png"),
HeightRequest = 16,
VerticalOptions = LayoutOptions.Center
};

fav.SetBinding(Image.IsVisibleProperty, new Binding(nameof(Book.IsFavourite)));

var author = new Label


{
TextColor = Color.Gray,
FontAttributes = FontAttributes.Italic,
FontSize = 13
};

author.SetBinding(Label.TextProperty, new Binding(nameof(Book.Author)));

var by = new Label


{
Text = "by",
TextColor = Color.Gray,
FontAttributes = FontAttributes.Italic,
FontSize = 13
};

var main = new StackLayout { Orientation = StackOrientation.Horizontal, Margin =


new Thickness(10, 10, 10, 0) };
main.Children.Add(fav);
main.Children.Add(book);

var detail = new StackLayout { Orientation = StackOrientation.Horizontal, Margin =


new Thickness(10, 0, 10, 10) };
detail.Children.Add(by);
detail.Children.Add(author);

content.Children.Add(main, 0, 0);
content.Children.Add(detail, 0, 1);

return content;
}
 

1191
Telerik UI for Xamarin

 Define the list view:

C#
var listView = new RadListView
{
ItemsSource = new ViewModel().Source,
ItemTemplate = new DataTemplate(() =>
{
return new ListViewTemplateCell
{
View = GetCellContent()
};
}),
};
 

1. Finally, set the list view as the content of your page.

See Also
 ListView Item TemplateSelector
 ListView Layouts
 Items Styling

1192
Telerik UI for Xamarin

ListView ItemTemplateSelector
The RadListView control exposes an ItemTemplateSelector property which you can use to apply
different template to each item depending on a specific condition.

This article will show you how you can utilize this property to achieve divergent appearance for the
different items within your Telerik ListView control.

TemplateSelector Implementation
Let's assume you have a RadListView bound to a collection of multiple DataItem objects and the
appearance of each item depends on a specific property of the business object. Below is the
DataItem class definition:

C#
public class DataItem : ViewModelBase
{
private string name;
private bool isSpecial;

public string Name


{
get
{
return this.name;
}
set
{
this.name = value;
this.OnPropertyChanged();
}
}

public bool IsSpecial


{
get
{
return this.isSpecial;
}
set
{
this.isSpecial = value;
this.OnPropertyChanged();
}
}
}
 

The first step is to declare a simple RadListView and set its ItemsSource property to point to the

1193
Telerik UI for Xamarin

collection of custom objects:

C#
public class ViewModel
{
public ViewModel()
{
this.Source = new ObservableCollection<DataItem>{
new DataItem{ Name = "Item1"},
new DataItem{ Name = "Item2"},
new DataItem{ Name = "Item3", IsSpecial = true },
new DataItem{ Name = "Item4"},
new DataItem{ Name = "Item5"},
new DataItem{ Name = "Item6"},
new DataItem{ Name = "Item7"},
new DataItem{ Name = "Item8"},
new DataItem{ Name = "Item9"},
new DataItem{ Name = "Item10", IsSpecial = true },
new DataItem{ Name = "Item11"},
new DataItem{ Name = "Item12"},
new DataItem{ Name = "Item13"},
new DataItem{ Name = "Item14", IsSpecial = true },
new DataItem{ Name = "Item15"},
new DataItem{ Name = "Item16"}
};
}

public ObservableCollection<DataItem> Source { get; private set; }


}
 

Eventually, as you need to apply different template to the item based on the value of the IsSpecial
property, you have to create a custom class that inherits from DataTemplateSelector. This class will
return different DataTemplate according to whether the value is true or false:

C#
public class CustomItemTemplateSelector : DataTemplateSelector
{
public DataTemplate Template1 { get; set; }
public DataTemplate Template2 { get; set; }

protected override DataTemplate OnSelectTemplate(object item, BindableObject


container)
{
var book = item as DataItem;
if (book.IsSpecial)
{
return this.Template2;
}

return this.Template1;
}

1194
Telerik UI for Xamarin

}
 

As a last step, you need to set this custom class as the ItemTemplateSelector property of the
RadListView and customize the templates within it:

XAML
<telerikDataControls:RadListView x:Name="listView" ItemsSource="{Binding Source}" >
<telerikDataControls:RadListView.BindingContext>
<local:ViewModel />
</telerikDataControls:RadListView.BindingContext>
<telerikDataControls:RadListView.ItemTemplateSelector>
<local:CustomItemTemplateSelector>
<local:CustomItemTemplateSelector.Template1>
<DataTemplate>
<telerikListView:ListViewTemplateCell>
<telerikListView:ListViewTemplateCell.View>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Margin="10" Text="{Binding Name}" />
<Button Grid.Column="1" Text="Mark as Special" Clicked="Button_Clicked"/>
</Grid>
</telerikListView:ListViewTemplateCell.View>
</telerikListView:ListViewTemplateCell>
</DataTemplate>
</local:CustomItemTemplateSelector.Template1>
<local:CustomItemTemplateSelector.Template2>
<DataTemplate>
<telerikListView:ListViewTemplateCell>
<telerikListView:ListViewTemplateCell.View>
<Grid BackgroundColor="Orange">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Label Text="{Binding Name}" FontSize="16" FontAttributes="Bold"
VerticalOptions="Center" Margin="10, 10, 10, 0"/>
<Label Text="Special Item" FontSize="13" FontAttributes="Italic"
TextColor="Gray" Grid.Row="1" Margin="10, 0, 10, 10" />
</Grid>
</telerikListView:ListViewTemplateCell.View>
</telerikListView:ListViewTemplateCell>
</DataTemplate>
</local:CustomItemTemplateSelector.Template2>
</local:CustomItemTemplateSelector>
</telerikDataControls:RadListView.ItemTemplateSelector>
</telerikDataControls:RadListView>
 

Running the sample will lead to the following appearance of the control:

1195
Telerik UI for Xamarin

A full example that shows the scenario is available in the SDK Samples Browser application from
your local installation.

See Also
 ListView Cells
 ListView Layouts
 Items Styling

1196
Telerik UI for Xamarin

Selection
RadListView component exposes selection feature. It allows users to select one or many items out of
the ItemsSource of the control. This feature provides both visual and programmatic feedback for the
actions of the user.

This article will show the basic properties RadListView provides for working with selection.

Selection Configuration
RadListView provides three selection modes, which allow you to manipulate the type of selection.
This is controlled by the SelectionMode property which has the following entries:

 SelectionMode (Telerik.XamarinForms.DataControls.ListView.SelectionMode):
 None - This mode doesn't allow users to select an item.
 Single - This is the default selection mode. It allows users to select only one item.
 Multiple - This mode allows users to select more than one item.

Check below how you can set SelectionMode in XAML and code-behind:

XAML
<telerikDataControls:RadListView x:Name="listView"
SelectionMode="Multiple" />
 

C#
var listView = new RadListView();
listView.SelectionMode =
Telerik.XamarinForms.DataControls.ListView.SelectionMode.Multiple;
 

You can also configure how the selection to be triggered by the end users through the
SelectionGesture property:

 SelectionGesture (Telerik.XamarinForms.DataControls.ListView.SelectionGesture):
 Tap - Users need to tap on an item to select it. This is the default SelectionGesture
value;
 Hold - Users need to tap & hold on an item to select it.

XAML
<telerikDataControls:RadListView x:Name="listView"
SelectionGesture="Hold" />
 

C#
var listView = new RadListView();
listView.SelectionGesture =

1197
Telerik UI for Xamarin

Telerik.XamarinForms.DataControls.ListView.SelectionGesture.Hold;
 

Getting Selected Items


RadListView exposes the following properties for getting the selected item or items in case of
multiple selection:

 SelectedItems (ObservableCollection<object>): Read-only collection used to get the


currently selected items;
 SelectedItem (object): Specifies the last selected item of the ListView.

Selection Events
 SelectionChanged: An event that is triggered whenever the SelectedItems collection is
changed. The SelectionChanged event handler receives two parameters:
 The sender argument which is of type object, but can be cast to the RadListView type.
 A NotifyCollectionChangedEventArgs object which provides information on the collection
changed event. For more details check NotifyCollectionChangedEventArgs Class topic.

Styling
You can customize the way selected items look by applying SelectedItemStyle property to the
RadListView instance. For detailed information on the approach go to Items Styles topic in ListView
documentation.

Example
The example below shows how to utilize RadListView selection feature - how you can set multiple
selection, apply selected item style and retrieve the selected items in a ViewModel class.

First, create a ViewModel class with two collections - one for the ItemsSource of the ListView and
one that will hold the SelectedItems. For the purpose of the example RadListView is bound to a
collection of strings:

C#
public class ViewModel : NotifyPropertyChangedBase
{
private ObservableCollection<object> _selectedNames;

public ViewModel()
{
this.Names = new ObservableCollection<string>() { "Tom", "Anna", "Peter",
"Teodor", "Lorenzo", "Andrea", "Martin" };
}

public ObservableCollection<string> Names { get; set; }


public ObservableCollection<object> SelectedNames

1198
Telerik UI for Xamarin

{
get { return this._selectedNames; }
set
{
if (this._selectedNames != value)
{
if (this._selectedNames != null)
{
this._selectedNames.CollectionChanged -= this.SelectedNamesCollectionChanged;
}

this._selectedNames = value;

if (this._selectedNames != null)
{
this._selectedNames.CollectionChanged += this.SelectedNamesCollectionChanged;
}

OnPropertyChanged("SelectedNames");

}
}
}

private void SelectedNamesCollectionChanged(object sender,


NotifyCollectionChangedEventArgs e)
{
if(this.SelectedNames.Count>0)
{
Application.Current.MainPage.DisplayAlert("Selected items:", string.Join(",",
this.SelectedNames.ToArray()), "OK");
}
}
}
 

Next, add RadListView instance to your page with selection properties applied:

XAML
<telerikDataControls:RadListView x:Name="listView"
ItemsSource="{Binding Names}"
SelectionMode="Multiple"
SelectedItems="{Binding SelectedNames}">
<telerikDataControls:RadListView.SelectedItemStyle>
<telerikListView:ListViewItemStyle BackgroundColor="#88FFF5BA"
BorderColor="#88FFF5BA" />
</telerikDataControls:RadListView.SelectedItemStyle>
</telerikDataControls:RadListView>
 

Lastly, set the ViewModel class as a BindingContext:

C#

1199
Telerik UI for Xamarin

this.BindingContext = new ViewModel();


 

Here is how the RadListView control looks like on different platforms when multiple items are
selected:

A sample Selection example is available in ListView -> Features folder of the SDK Browser
application.

You can directly explore the code in the SDKBrowser Examples repository on GitHub.

See Also
 Items Grouping
 Items Sorting
 Items Styling

1200
Telerik UI for Xamarin

Grouping
RadListView provides you with the functionality to programmatically group its data at runtime. This
can be achieved through adding groupdescriptors to the RadListView.GroupDescriptors collection.

In addition, the control supports groups expand and collapse operations either through the UI by
tapping on the group headers or programmatically. For more details on this refer to Expand and
Collapse Groups.

PropertyGroupDescriptor
You can group the data by a property value from the class that defines your items. This descriptor
exposes the following properties:

 PropertyName: Defines the string name of the property you want to group by.
 SortOrder: Defines the sort order in each group to Ascending or Descending.

Let's, for example, have the following business object:

C#
public class City
{
public string Name { get; set; }
public string Country { get; set; }
}
 

and a ViewModel with a collection of Cities:

C#
public class ViewModel
{
public ObservableCollection<City> Cities { get; set; }

public ViewModel()
{
this.Cities = new ObservableCollection<City>()
{
new City() { Name = "Barcelona", Country = "Spain"},
new City() { Name = "Madrid", Country = "Spain"},
new City() { Name = "Rome", Country = "Italy"},
new City() { Name = "Florence", Country = "Italy"},
new City() { Name = "London", Country = "England"},
new City() { Name = "Manchester", Country = "England"},
new City() { Name = "New York", Country = "USA"},
new City() { Name = "Boston", Country = "USA"}
};
}

1201
Telerik UI for Xamarin

}
 

Next snippet demonstrates how you could group the Cities by "Country" property through the
PropertyGroupDescriptor:

XAML
<telerikDataControls:RadListView x:Name="listView" ItemsSource="{Binding Cities}"
ItemTemplate="{StaticResource ListViewItemTemplate}"
GroupHeaderTemplate="{StaticResource ListViewGroupHeaderTemplate}"
GroupHeaderStyle="{StaticResource ListViewGroupHeaderStyle}">
<telerikDataControls:RadListView.GroupDescriptors>
<telerikListView:PropertyGroupDescriptor PropertyName="Country"/>
</telerikDataControls:RadListView.GroupDescriptors>
</telerikDataControls:RadListView>
 

GroupHeaderTemplate
In addition, you could create custom GroupHeaderTemplate as well as ListViewItemTemplate in
order to achieve the desired look when grouping the ListView. The BindingContext of the
GroupHeader is a complex object and it includes the following properties:

 IsExpanded: Defines a value indicating whether the group is currently expanded (has its
child items visible).
 Items: Gets the child items of the group.
 Key: Gets the specific for the group key.
 Level: Gets the zero-based level (or the depth) of the group.

The snippet below shows how the GroupHeaderTemplate is defined:

XAML
<ResourceDictionary>
<DataTemplate x:Key="ListViewItemTemplate">
<telerikListView:ListViewTemplateCell>
<telerikListView:ListViewTemplateCell.View>
<Grid Padding="16, 0, 0, 0" BackgroundColor="#F1F2F5">
<Label Text="{Binding Name}" TextColor="#6F6F70" FontSize="Small" />
</Grid>
</telerikListView:ListViewTemplateCell.View>
</telerikListView:ListViewTemplateCell>
</DataTemplate>
<DataTemplate x:Key="ListViewGroupHeaderTemplate">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Label Text="&#x25B8;" Margin="8, 12, 0, 6" TextColor="DarkGray"
FontSize="Medium">
<Label.Triggers>

1202
Telerik UI for Xamarin

<DataTrigger TargetType="Label" Binding="{Binding IsExpanded}" Value="True">


<Setter Property="Text" Value="&#x25BE;" />
</DataTrigger>
</Label.Triggers>
</Label>
<Label Margin="0, 12, 0, 6" Text="{Binding }" Grid.Column="1"
TextColor="DarkGray" FontSize="Medium" HorizontalOptions="Start" />
</Grid>
</DataTemplate>
<telerikListView:ListViewGroupStyle x:Key="ListViewGroupHeaderStyle"
BackgroundColor="Transparent" />
</ResourceDictionary>
 

All that is left is to set the ViewModel as BindingContext of the control:

C#
listView.BindingContext = new ViewModel();
 

Figure 1: ListView grouped through PropertyGroupDescriptor

DelegateGroupDescriptor
This descriptor enables you to group by a custom key (e.g. some complex expression combining two
or more properties) instead of being limited by the value of a single property. This descriptor exposes
the following properties:

 KeyExtractor: Defines the (Func<object, object) delegate which returns the property to

1203
Telerik UI for Xamarin

retrieve the group key for each data item.


 SortOrder: Defines the sort order in each group to Ascending or Descending.

Let's use the same example from the previous section, just add DelegateGroupDescriptor through
code instead.

Next snippet shows how the ListView instance is defined:

XAML
<telerikDataControls:RadListView x:Name="listView" ItemsSource="{Binding Cities}"
ItemTemplate="{StaticResource ListViewItemTemplate}"
GroupHeaderTemplate="{StaticResource ListViewGroupHeaderTemplate}"
GroupHeaderStyle="{StaticResource ListViewGroupHeaderStyle}">
</telerikDataControls:RadListView>
 

And you could create and apply a delegate for grouping the items (for example by their first letter) as
following:

C#
public DelegateGroupDescriptorGroups()
{
InitializeComponent();
listView.BindingContext = new ViewModel();

var delegateDescriptor = new DelegateGroupDescriptor


{
KeyExtractor = FirstLetterKeyExtractor
};

listView.GroupDescriptors.Add(delegateDescriptor);
}

private object FirstLetterKeyExtractor(object arg)


{
var item = arg as City;
return item?.Name.Substring(0, 1);
}
 

Figure 2: ListView grouped through DelegateGroupDescriptor

1204
Telerik UI for Xamarin

Sticky Group Headers


Starting with R1 2020 SP release RadListView provides the option to set its group headers as sticky.
This means the GroupHeader will "freeze" while scrolling through the items until the whole group is
scrolled away. As you scroll through the next group, the currently sticked group header will be
pushed by the next group header.

To enable the sticky group headers behavior, just set IsGroupHeaderSticky property of the ListView
to True. By default IsGroupHeaderSticky value is False.

XAML
<telerikDataControls:RadListView x:Name="listView"
IsGroupHeaderSticky="True" />
 

C#
var listView = new RadListView();
listView.IsGroupHeaderSticky = true;
 

Check below the sticky group headers in action:

1205
Telerik UI for Xamarin

Bindable GroupDescriptor
The GroupDescriptor collection now can be controlled by users using MVVM.

In order to control the GroupDescriptor collection through MVVM:

1. Create a property of type ObservableCollection in your ViewModel which will contain the
needed group descriptors:

C#
public ObservableCollection<GroupDescriptorBase> GroupDescriptors
{
get
{
return this.groupDescriptors;

1206
Telerik UI for Xamarin

}
set
{
if (this.groupDescriptors != value)
{
this.groupDescriptors = value;
OnPropertyChanged();
}
}
}
 

2. Use OneWayToSource binding mode to bind that property to the GroupDescriptors property
of RadListView:

XAML
<telerikDataControls:RadListView x:Name="listView"
Grid.Row="2"
GroupDescriptors="{Binding GroupDescriptors,
Mode=OneWayToSource}"
ItemsSource="{Binding Items}">
 

Here is how the GroupDescriptor collection looks like through MVVM:

You can find a working demo labeled Bindable Group Descriptors in the ListView/Bindable
Collections folder of the SDK Samples Browser application.
 

1207
Telerik UI for Xamarin

See Also
 Filtering
 Sorting
 Selection

1208
Telerik UI for Xamarin

Expand and Collapse Groups


RadListView supports groups expand and collapse operations either through the UI by tapping on
the group headers or programmatically. By default, all the groups are expanded.

This help topic will provide an overview of the methods and commands used to control the
expand/collapse state of the ListView groups.

Before proceeding, please check the Grouping topic which describes how you could enable the
grouping feature of RadListView.
 

Get the grouped ListView items


To manipulate the collapsible ListView groups, first you will need to call its GetDataView method. In
short, GetDataView method provides a view of the ItemsSource after all the Sort, Group and Filter
operations are applied. The return type is IDataViewCollection which exposes the expand and
collapse methods described in the following sections.

C#
var dataView = this.listView.GetDataView();
 

Expand and collapse all groups


In order to expand all groups, use the ExpandAll method and respectively use the CollapseAll
method - to collapse all groups.

C#
//expand all
var dataView = this.listView.GetDataView();
dataView.ExpandAll();

//collapse all
var dataView = this.listView.GetDataView();
dataView.CollapseAll();
 

Expand and collapse a certain group


You could retrieve the first-level groups through the GetGroups method of the IDataViewCollection
object and use ExpandGroup/CollapseGroup to make a certain group to expand or collapse
respectively. You could check whether a group is expanded trough the GetIsExpanded method.

Here is quick snippet on how these methods are used:

1209
Telerik UI for Xamarin

C#
var dataView = this.listView.GetDataView();
var rootGroups = dataView.GetGroups();

var isFirstExpanded = dataView.GetIsExpanded(rootGroups.First());


//expand a certain group
dataView.ExpandGroup(rootGroups.First());
//collapse a certain group
dataView.CollapseGroup(rootGroups.First());
 

Additionally, IDataViewCollection provides ExpandItem/CollapseItem methods that take a ListView


item as a parameter and expand/collapse the immediate group containing this item.

C#
var lastItem = (listView.ItemsSource as IEnumerable<City>).Last();
var dataView = this.listView.GetDataView();
dataView.CollapseItem(lastItem);
 

Handle GroupHeaderTap command


GroupHeaderTap command is raised when a group header of a grouped ListView is tapped. By
default, tapping on a group header collapses the group if it is expanded and vice-versa.

By handling GroupHeaderTap command you could control the collapse/expand behavior of a certain
group. The next example shows how to prevent the first-level groups from hiding their items.

Please check Commands topic for information on how to use RadListView commands.
 
First, let’s define the GroupHeaderTapCommand class that derives from ListViewCommand:

C#
public class GroupHeaderTapCommand : ListViewCommand
{
public GroupHeaderTapCommand()
{
Id = CommandId.GroupHeaderTap;
}
public override bool CanExecute(object parameter)
{
return true;
}
public override void Execute(object parameter)
{
var context = parameter as GroupHeaderContext;
if (context.Level > 1)
context.IsExpanded = !context.IsExpanded;
}
}

1210
Telerik UI for Xamarin

And add the GroupHeaderTapCommand to the Commands collection of the ListView instance:

C#
listView.Commands.Add(new GroupHeaderTapCommand());
 

See Also
 Grouping
 Commands

1211
Telerik UI for Xamarin

Multi-Level Grouping
This article provides an overview on how you could enable multi-level grouping in RadListView.

Before proceeding please go through Grouping Overview topic.


 
First, let's create the following business object:

C#
public class City
{
public string Continent { get; set; }
public string Name { get; set; }
public string Country { get; set; }
}
 

The next example demonstrates how RadListView could be bound to a collection of City objects and
grouped hieararchically by Continent and Country.

To accomplish the task, create a ViewModel class as shown below:

C#
public class ViewModel
{
public ObservableCollection<City> Cities { get; set; }

public ViewModel()
{
this.Cities = new ObservableCollection<City>()
{
new City() { Name = "Barcelona", Country = "Spain", Continent = "Europe"},
new City() { Name = "Madrid", Country = "Spain", Continent = "Europe" },
new City() { Name = "Rome", Country = "Italy", Continent = "Europe" },
new City() { Name = "Florence", Country = "Italy", Continent = "Europe" },
new City() { Name = "London", Country = "England", Continent = "Europe" },
new City() { Name = "Manchester", Country = "England", Continent = "Europe"},
new City() { Name = "New York", Country = "USA", Continent = "North America" },
new City() { Name = "Boston", Country = "USA", Continent = "North America" }
};
}
}
 

Then, in order to visualize the hierarchical relation between groups, add a custom
GroupHeaderTemplate (of type DataTemplate) to the Resources of your page:

XAML
<ResourceDictionary>

1212
Telerik UI for Xamarin

<local:LevelToMarginConverter x:Key="LevelToMarginConverter" />


<DataTemplate x:Key="ListViewItemTemplate">
<telerikListView:ListViewTemplateCell>
<telerikListView:ListViewTemplateCell.View>
<Grid Padding="50, 0, 0, 0" BackgroundColor="#F1F2F5">
<Label Text="{Binding Name}" TextColor="#6F6F70" FontSize="Small" />
</Grid>
</telerikListView:ListViewTemplateCell.View>
</telerikListView:ListViewTemplateCell>
</DataTemplate>
<DataTemplate x:Key="ListViewMultiLevelGroupHeaderTemplate">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Label Text="&#x25B8;" Margin="{Binding Level, Converter={StaticResource
LevelToMarginConverter}}"
TextColor="DarkGray" FontSize="Medium">
<Label.Triggers>
<DataTrigger TargetType="Label" Binding="{Binding IsExpanded}" Value="True">
<Setter Property="Text" Value="&#x25BE;" />
</DataTrigger>
</Label.Triggers>
</Label>
<Label Margin="0, 12, 0, 6" Text="{Binding }" Grid.Column="1"
TextColor="DarkGray" FontSize="Medium" HorizontalOptions="Start" />
</Grid>
</DataTemplate>
<telerikListView:ListViewGroupStyle x:Key="ListViewGroupHeaderStyle"
BackgroundColor="Transparent" />
</ResourceDictionary>
 

where LevelToMarginConverter just calculates the margin of each group header according to its
Level:

XAML
<ResourceDictionary>
<local:LevelToMarginConverter x:Key="LevelToMarginConverter" />
<DataTemplate x:Key="ListViewItemTemplate">
<telerikListView:ListViewTemplateCell>
<telerikListView:ListViewTemplateCell.View>
<Grid Padding="50, 0, 0, 0" BackgroundColor="#F1F2F5">
<Label Text="{Binding Name}" TextColor="#6F6F70" FontSize="Small" />
</Grid>
</telerikListView:ListViewTemplateCell.View>
</telerikListView:ListViewTemplateCell>
</DataTemplate>
<DataTemplate x:Key="ListViewMultiLevelGroupHeaderTemplate">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />

1213
Telerik UI for Xamarin

<ColumnDefinition />
</Grid.ColumnDefinitions>
<Label Text="&#x25B8;" Margin="{Binding Level, Converter={StaticResource
LevelToMarginConverter}}"
TextColor="DarkGray" FontSize="Medium">
<Label.Triggers>
<DataTrigger TargetType="Label" Binding="{Binding IsExpanded}" Value="True">
<Setter Property="Text" Value="&#x25BE;" />
</DataTrigger>
</Label.Triggers>
</Label>
<Label Margin="0, 12, 0, 6" Text="{Binding }" Grid.Column="1"
TextColor="DarkGray" FontSize="Medium" HorizontalOptions="Start" />
</Grid>
</DataTemplate>
<telerikListView:ListViewGroupStyle x:Key="ListViewGroupHeaderStyle"
BackgroundColor="Transparent" />
</ResourceDictionary>
 

Lastly, add the RadListView definition with two PropertyGroupDescriptors as shown in the next
snippet:

XAML
<telerikDataControls:RadListView x:Name="listView" ItemsSource="{Binding Cities}"
ItemTemplate="{StaticResource ListViewItemTemplate}"
GroupHeaderTemplate="{StaticResource ListViewMultiLevelGroupHeaderTemplate}"
GroupHeaderStyle="{StaticResource ListViewGroupHeaderStyle}">
<telerikDataControls:RadListView.GroupDescriptors>
<telerikListView:PropertyGroupDescriptor PropertyName="Continent"/>
<telerikListView:PropertyGroupDescriptor PropertyName="Country"/>
</telerikDataControls:RadListView.GroupDescriptors>
</telerikDataControls:RadListView>
 

Here is the final result:

1214
Telerik UI for Xamarin

See Also
 Grouping
 Filtering
 Sorting

1215
Telerik UI for Xamarin

Reorder Items in Grouped ListView


This help topic will provide an overview on how you could enable reordering feature of RadListView
control when its items are grouped.

Before proceeding, please check the Reorder Items topic which describes in details reordering
functionality of the ListView.
 
When the items of RadListView are grouped by a certain criteria and the end user drags/starts
reordering an item, the dragged item could be added to a different group. Since this depends on the
items' relation, in order to handle the scenario, you would need to subscribe to the ListView Reorder
Command and manually update the dragged item details. Below you could find a sample
implementation.

First, let's create a sample business object, for example Event:

C#
public class Event : NotifyPropertyChangedBase
{
public string _content;
public string _day;

public string Content


{
get { return this._content; }
set
{
if(this._content != value)
{
this._content = value;
OnPropertyChanged();
}
}
}
public string Day
{
get { return this._day; }
set
{
if(this._day != value)
{
this._day = value;
OnPropertyChanged();
}
}
}
}
 

1216
Telerik UI for Xamarin

Then, create a ViewModel class containing a collection of Event objects as well as a Reorder
command implementation considering the Events will be grouped according to Day property. Inside
the Reorder command you will have access to some useful details through
ReorderEndedCommandContext such as:

 Item: Refers to the data item that is being interacted with.


 DestinationItem: Refers to the data item that corresponds to the location where the dragged
item has been released.
 Group: Gets the group containing the data item that is being interacted with.
 DestinationGroup: Refers to the group that corresponds to the location where the dragged
item has been released.
 Placement (of type ItemReorderPlacement): Indicates whether the dragged item should be
placed before or after the destination item.

C#
public class ViewModel
{
public ViewModel()
{
this.Events = new ObservableCollection<Event>()
{
new Event() { Content = "Meeting with John", Day = "Tommorow" },
new Event() { Content = "This also happens today", Day = "Yesterday" },
new Event() { Content = "More events today", Day = "Today" },
new Event() { Content = "Go shopping after 19:00", Day = "Yesterday" },
new Event() { Content = "Lunch with Sara", Day = "Today" },
new Event() { Content = "Planning for tommorow", Day = "Today"},
new Event() { Content = "Free lunch time", Day = "Yesterday" },
new Event() { Content = "Kids Party", Day = "Tommorow" },
new Event() { Content = "Party", Day = "Tommorow" }
};
this.ReorderCommand = new Command<ReorderEndedCommandContext>(this.Reorder);
}
public ObservableCollection<Event> Events { get; set; }
public Command<ReorderEndedCommandContext> ReorderCommand { get; }
private void Reorder(ReorderEndedCommandContext context)
{
var sourceItem = (Event)context.Item;

this.Events.Remove(sourceItem);

var destinationItem = (Event)context.DestinationItem;


var destinationGroup = context.DestinationGroup;
var destinationIndex = this.Events.IndexOf(destinationItem);

if (context.Placement == ItemReorderPlacement.After)
{
destinationIndex++;
}

sourceItem.Day = (string)destinationGroup.Key;
this.Events.Insert(destinationIndex, sourceItem);

1217
Telerik UI for Xamarin

}
}
 

And here is the RadListView definition with PropertyGroupDescriptor and Reorder command applied:

XAML
<telerikDataControls:RadListView x:Name="listView"
ItemsSource="{Binding Events}"
IsItemsReorderEnabled="True">
<telerikDataControls:RadListView.ItemTemplate>
<DataTemplate>
<telerikListView:ListViewTemplateCell>
<telerikListView:ListViewTemplateCell.View>
<StackLayout Orientation="Horizontal" Padding="16, 0, 0, 0">
<Label Margin="0,2,0,0" Text="&#xf138;" FontFamily="{StaticResource
IconsFontFamily}" />
<Label Text="{Binding Content}" TextColor="#6F6F70" FontSize="Small" />
</StackLayout>
</telerikListView:ListViewTemplateCell.View>
</telerikListView:ListViewTemplateCell>
</DataTemplate>
</telerikDataControls:RadListView.ItemTemplate>
<telerikDataControls:RadListView.GroupDescriptors>
<telerikListView:PropertyGroupDescriptor PropertyName="Day"/>
</telerikDataControls:RadListView.GroupDescriptors>
<telerikDataControls:RadListView.Commands>
<telerikListViewCommands:ListViewUserCommand Id="ReorderEnded"
Command="{Binding ReorderCommand}" />
</telerikDataControls:RadListView.Commands>
</telerikDataControls:RadListView>
 

Lastly, set the ViewModel as a BindingContext:

C#
this.BindingContext = new ViewModel();
 

You could check the result on the image below:

1218
Telerik UI for Xamarin

See Also
 Grouping
 Commands

1219
Telerik UI for Xamarin

Sorting
RadListView can be used to sort the visualized data. This can be achieved by adding different
SortDescriptors to its SortDescriptors collection. There are two types of descriptors shipped with our
code.

PropertySortDescriptor
You can sort the data by a property value from the class that defines your business items. This
descriptor exposes the following properties:

 PropertyName: Defines the string name of the property that is used to retrieve the key to sort
by.
 SortOrder: Specifies sort order to Ascending or Descending.

DelegateSortDescriptor
This descriptor enables you to sort by a custom key (e.g. some complex expression combining two
or more properties) instead of being limited by the value of a single property. This descriptor exposes
the following properties:

 SortOrder: Sets the sort order to Ascending or Descending.


 Comparer: Defines the Compare method used by the internal IComparer.

Example
Here is an example that will guide you how to use SortDescriptor in ListView.

First, define the ListView in XAML:

XAML
<telerikDataControls:RadListView x:Name="listView" ItemsSource="{Binding Items}">
<telerikDataControls:RadListView.ItemTemplate>
<DataTemplate>
<telerikListView:ListViewTemplateCell>
<telerikListView:ListViewTemplateCell.View>
<StackLayout Orientation="Horizontal">
<Label Text="Name:"/>
<Label Text="{Binding Name}"/>
<Label Text=", Age:"/>
<Label Text="{Binding Age}"/>
</StackLayout>
</telerikListView:ListViewTemplateCell.View>
</telerikListView:ListViewTemplateCell>
</DataTemplate>
</telerikDataControls:RadListView.ItemTemplate>

1220
Telerik UI for Xamarin

</telerikDataControls:RadListView>
 

Add the following code to the Sorting class:

C#
public Sorting()
{
InitializeComponent();
this.BindingContext = new ViewModel();
listView.SortDescriptors.Add(new
Telerik.XamarinForms.DataControls.ListView.PropertySortDescriptor { PropertyName =
"Age", SortOrder = SortOrder.Ascending });
}
 

Use the following snippet for the ViewModel class:

C#
public class ViewModel
{
public ViewModel()
{
this.Items = GetData();
}

public ObservableCollection<Item> Items { get; set; }

private static ObservableCollection<Item> GetData()


{
var items = new ObservableCollection<Item>();

items.Add(new Item { Name = "Tom", Age = 41 });


items.Add(new Item { Name = "Anna", Age = 32 });
items.Add(new Item { Name = "Peter", Age = 28 });
items.Add(new Item { Name = "Teodor", Age = 39 });
items.Add(new Item { Name = "Lorenzo", Age = 25 });
items.Add(new Item { Name = "Andrea", Age = 33 });
items.Add(new Item { Name = "Martin", Age = 36 });
items.Add(new Item { Name = "Alexander", Age = 29 });
items.Add(new Item { Name = "Maria", Age = 22 });
items.Add(new Item { Name = "Elena", Age = 27 });
items.Add(new Item { Name = "Stefano", Age = 44 });
items.Add(new Item { Name = "Jake", Age = 31 });
items.Add(new Item { Name = "Leon", Age = 28 });

return items;
}
}
 

Create a class Person and add the code below:

1221
Telerik UI for Xamarin

C#
public class Item
{
public string Name { get; set; }
public int Age { get; set; }
}
 

Here is the result once the data is sorted.

A sample example how to create ListView with SortDescriptor can be found in the ListView/Features
folder of the SDK Samples Browser application.
 

Bindable SortDescriptor
Currently the SortDescriptor of the RadListView supports binding. What's new is that now the users
can control it using MVVM.

In order to control the descriptors collections through MVVM:

 Create a property of type ObservableCollection in your ViewModel which will contain the
needed sort descriptors:

C#
public ObservableCollection<SortDescriptorBase> SortDescriptors
{

1222
Telerik UI for Xamarin

get
{
return this.sortDescriptors;
}
set
{
if (this.sortDescriptors != value)
{
this.sortDescriptors = value;
OnPropertyChanged();
}
}
}
 

 Use OneWayToSource binding mode to bind that property to the SortDescriptors property of
RadListView:

XAML
<telerikDataControls:RadListView x:Name="listView"
Grid.Row="2" ItemsSource="{Binding Items}"
SortDescriptors="{Binding SortDescriptors,
Mode=OneWayToSource}">
 

Here is the result:

An example how to create a ListView with SortDescriptor collection that can be controlled through
MVVM can be found in the ListView/Bindable Collections folder of the SDK Samples Browser

1223
Telerik UI for Xamarin

application.
 

See Also
 Grouping
 Filtering
 Selection

1224
Telerik UI for Xamarin

Filtering
RadListView provides you with the functionality to programmatically filter its data at runtime. This can
be achieved through adding filter descriptors that implement the IFilter interface to the
RadListView.FilterDescriptors collection. You can use our DelegateFilterDescriptor implementation.

DelegateFilterDescriptor
 Filter: Defines the function used to check whether a data item passes the filter or not.

Example
First, define the ListView in XAML:

XAML
<telerikDataControls:RadListView x:Name="listView" ItemsSource="{Binding Items}">
<telerikDataControls:RadListView.ItemTemplate>
<DataTemplate>
<telerikListView:ListViewTemplateCell>
<telerikListView:ListViewTemplateCell.View>
<StackLayout Orientation="Horizontal">
<Label Text="Name:"/>
<Label Text="{Binding Name}"/>
<Label Text=", Age:"/>
<Label Text="{Binding Age}"/>
</StackLayout>
</telerikListView:ListViewTemplateCell.View>
</telerikListView:ListViewTemplateCell>
</DataTemplate>
</telerikDataControls:RadListView.ItemTemplate>
</telerikDataControls:RadListView>
 

Add the following code to the Filtering class:

C#
public Filtering()
{
InitializeComponent();
this.BindingContext = new ViewModel();
listView.FilterDescriptors.Add(new
Telerik.XamarinForms.DataControls.ListView.DelegateFilterDescriptor { Filter =
this.AgeFilter });
}
private bool AgeFilter(object arg)
{
var age = ((Item)arg).Age;
return age >= 25 && age <= 35;

1225
Telerik UI for Xamarin

}
 

Here is the ViewModel class:

C#
public class ViewModel
{
public ViewModel()
{
this.Items = GetData();
}

public ObservableCollection<Item> Items { get; set; }

private static ObservableCollection<Item> GetData()


{
var items = new ObservableCollection<Item>();

items.Add(new Item { Name = "Tom", Age = 41 });


items.Add(new Item { Name = "Anna", Age = 32 });
items.Add(new Item { Name = "Peter", Age = 28});
items.Add(new Item { Name = "Teodor", Age = 39});
items.Add(new Item { Name = "Lorenzo", Age = 25 });
items.Add(new Item { Name = "Andrea", Age = 33});
items.Add(new Item { Name = "Martin", Age = 36 });
items.Add(new Item { Name = "Alexander", Age = 29});
items.Add(new Item { Name = "Maria", Age = 22 });
items.Add(new Item { Name = "Elena", Age = 27 });
items.Add(new Item { Name = "Stefano", Age = 44 });
items.Add(new Item { Name = "Jake", Age = 31 });
items.Add(new Item { Name = "Leon", Age = 28 });

return items;
}
}
 

And here is the data class:

C#
public class Item
{
public string Name { get; set; }
public int Age { get; set; }
}
 

Here is the result after the data is filtered:

1226
Telerik UI for Xamarin

A sample example how to create ListView with FilterDescriptor can be found in the
ListView/Features folder of the SDK Samples Browser application.
 

Bindable FilterDescriptor
The RadListView control supports binding. What's new is that now the users can control the
FilerDescriptor collection through MVVM.

In order to control the FilterDescriptor collection through MVVM:

1. Create a property of type ObservableCollection in your ViewModel which will contain the
needed filters. Here is a sample ViewModel:

C#
public class ViewModel : INotifyPropertyChanged
{
private ObservableCollection<FilterDescriptorBase> filterDescriptors;
private bool isFilterSwitchToggled;
private List<Event> items;

public ViewModel()
{
this.Items = this.GetItems();
this.filterDescriptors = new ObservableCollection<FilterDescriptorBase>();
}

public event PropertyChangedEventHandler PropertyChanged;

1227
Telerik UI for Xamarin

public ObservableCollection<FilterDescriptorBase> FilterDescriptors


{
get
{
return this.filterDescriptors;
}
set
{
if (this.filterDescriptors != value)
{
this.filterDescriptors = value;
OnPropertyChanged();
}
}
}
public bool IsFilterSwitchToggled
{
get
{
return this.isFilterSwitchToggled;
}
set
{
if (this.isFilterSwitchToggled != value)
{
this.isFilterSwitchToggled = value;
OnPropertyChanged();
}
}
}

public List<Event> Items


{
get
{
return this.items;
}
set
{
if (this.items != value)
{
this.items = value;
OnPropertyChanged();
}
}
}

private List<Event> GetItems()


{
var results = new List<Event>();

results.Add(new Event() { Content = "Content of the item", Day = "Tommorow",


Category = "A" });
results.Add(new Event() { Content = "This also happens today", Day =

1228
Telerik UI for Xamarin

"Yesterday", Category = "A" });


results.Add(new Event() { Content = "More events today", Day = "Today",
Category = "A" });
results.Add(new Event() { Content = "Go shopping after 19:00", Day =
"Yesterday", Category = "B" });
results.Add(new Event() { Content = "You are now free to do whathever", Day =
"Today", Category = "B" });

results.Add(new Event() { Content = "For tommorow", Day = "Today", Category =


"B" });
results.Add(new Event() { Content = "It is a free day", Day = "Yesterday",
Category = "C" });
results.Add(new Event() { Content = "Go have some fun", Day = "Tommorow",
Category = "C" });
results.Add(new Event() { Content = "Party", Day = "Tommorow", Category = "C"
});

return results;
}

private void OnPropertyChanged([CallerMemberName] string propertyName = null)


{
this.UpdateExistingFilterDescriptor(propertyName);
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

private void UpdateExistingFilterDescriptor(string propertyName)


{
if (this.FilterDescriptors == null)
return;

if (this.FilterDescriptors.Count == 0)
{
this.FilterDescriptors.Add(new DelegateFilterDescriptor()
{
Filter = new Func<object, bool>((item) => ((Event)item).Category.Equals("A"))
});
}

if(propertyName.Equals(nameof(IsFilterSwitchToggled)))
{
((DelegateFilterDescriptor)this.FilterDescriptors.FirstOrDefault()).Filter =
this.isFilterSwitchToggled ?
new Func<object, bool>((item) => ((Event)item).Category.Equals("C")) :
new Func<object, bool>((item) => ((Event)item).Category.Equals("A"));
}
}
}
 

1. A sample business model:

C#
public class Event

1229
Telerik UI for Xamarin

{
public string Content { get; set; }
public string Day { get; set; }
public string Category { get; set; }
}
 

1. Use OneWayToSource binding mode to bind that property to the FilterDescriptors property of
RadListView:

XAML
<Grid Margin="16,0,0,0">
<Grid.RowDefinitions>
<RowDefinition Height="40" />
<RowDefinition />
</Grid.RowDefinitions>

<StackLayout Orientation="Horizontal">
<StackLayout>
<Label Text="Filter by Category A/C" />
<Label Text="Updates existing filter descriptor" FontSize="Micro"
TextColor="LimeGreen" LineBreakMode="WordWrap" />
</StackLayout>
<Switch IsToggled="{Binding IsFilterSwitchToggled, Mode=OneWayToSource}"
AutomationId="FilterCategorySwitch"/>
</StackLayout>
<telerikDataControls:RadListView x:Name="listView" Grid.Row="1"
FilterDescriptors="{Binding FilterDescriptors,
Mode=OneWayToSource}"
ItemsSource="{Binding Items}">
<telerikDataControls:RadListView.ItemTemplate>
<DataTemplate>
<telerikListView:ListViewTemplateCell>
<telerikListView:ListViewTemplateCell.View>
<StackLayout>
<Label Text="{Binding Content}" FontSize="Medium" />
<Label Text="{Binding Day}" FontSize="Small" TextColor="LimeGreen" />
<Label Text="{Binding Category}" FontSize="Micro" TextColor="Red" />
</StackLayout>
</telerikListView:ListViewTemplateCell.View>
</telerikListView:ListViewTemplateCell>
</DataTemplate>
</telerikDataControls:RadListView.ItemTemplate>
</telerikDataControls:RadListView>
</Grid>
 

Here is how this looks like:

1230
Telerik UI for Xamarin

Bindable Filter Descriptor example can be checked in our SDK Samples Browser application
ListView/BindableCollections folder.
 

See Also
 Grouping
 Sorting
 Selection

1231
Telerik UI for Xamarin

Header and Footer


With R1 2019 release of Telerik UI for Xamarin RadListView exposes two new templates - Header
and Footer, which will allow you to add content of your choice above and below the list with the
items. Both header and footer templates are scrolled along with the ListView items.

 HeaderTemplate(DataTemplate): Defines the Header of the ListView before all items.


 FooterTemplate(DataTemplate): Defines the Footer of the ListView after all items.

Example
Here is an example how to add Header and Footer to the RadListView control.

First, create a ViewModel:

C#
public class HeaderAndFooterViewModel
{
public HeaderAndFooterViewModel()
{
this.Items = GetItems(20);
}

public ObservableCollection<string> Items { get; set; }

private static ObservableCollection<string> GetItems(int count)


{
var items = new ObservableCollection<string>();
for (int i = 0; i < count; i++)
{
items.Add(string.Format("item {0}", i));
}

return items;
}
}
 

Add the following sample DataTemplates to the resources of the page that will be used as:

HeaderTemplate:

XAML
<DataTemplate x:Key="HeaderTemplate">
<Label Text="The Available Items are: "
TextColor="Black"
FontAttributes="Bold"
FontSize="25"/>

1232
Telerik UI for Xamarin

</DataTemplate>
 

FooterTemplate:

XAML
<DataTemplate x:Key="FooterTemplate">
<Label Text="All Items!"
TextColor="Black"
FontAttributes="Bold"
FontSize="25"/>
</DataTemplate>
 

Use the following snippet to declare the RadListView in XAML:

XAML
<telerikDataControls:RadListView x:Name="listView"
ItemsSource="{Binding Items}"
HeaderTemplate="{StaticResource HeaderTemplate}"
FooterTemplate="{StaticResource FooterTemplate}"/>
 

Here is how the ListView Header looks:

and the ListView Footer:

1233
Telerik UI for Xamarin

A sample Header and Footer example can be found in our SDK Samples Browser application and
QSF App.
 

See Also
 Events
 Selection
 Reordering

1234
Telerik UI for Xamarin

Load on Demand
Loading a large data set on a mobile device has its challenges. One of the most popular approaches
is using incremental data loading when the items need to be visualized. RadListView does this by
using its load-on-demand functionality.

Configuration
The following properties control the LoadOnDemand feature:

 IsLoadOnDemandEnabled(bool) - used to enable the load on demand mechanism of


RadListView.
 IsLoadOnDemandActive (bool) - used to control the loading indicator that is rendered when
the data is retrieved asynchronously. Set it to True when an async operation is running and
items are loading. Set it to False when the items are loaded.
 LoadOnDemandMode - used to set the loading mode. You can select between:
 Automatic - the data is requested automatically when you scroll near the end of the
ListView.
 Manual - a button is rendered at the end of the ListView. The data is requested explicitly
by pressing the button.

Methods to Load Data on Demand


There are three ways to load the data on demand, regardless of whether you use the Automatic or
Manual loading mode:

 Create a ListViewLoadOnDemandCollection instance as a source and pass it to the ListView


ItemsSource property.
 Subscribe to the LoadOnDemand event and add the loaded data to the source.
 Use the LoadOnDemand UserCommand and add the loaded data to the source.

All three approaches for loading items on demand in ListView work with both Automatic and Manual
LoadOnDemandMode.
 

Using LoadOnDemandCollection
To load items on demand, you can utilize the ListViewLoadOnDemandCollection and set it as
ItemsSource for ListView. The ListViewLoadOnDemandCollection accepts an action in the
constructor and this action is later executed by the ListView in a non-UI thread when new items are
requested.

The example below demonstrates how to use LoadOnDemandCollection:

1. Define a sample ViewModel class with Source property of type


ListViewLoadOnDemandCollection:

1235
Telerik UI for Xamarin

C#
public class ListViewModel
{
public ListViewLoadOnDemandCollection Source { get; set; }
private int lodTriggerCount;
public ListViewModel()
{
this.Source = new ListViewLoadOnDemandCollection((cancelationToken) =>
{
List<string> result = new List<string>();

try
{
//simulates connection latency
Task.Delay(4000, cancelationToken).Wait();

this.lodTriggerCount++;
foreach (string item in Enum.GetNames(typeof(DayOfWeek)))
{
result.Add(string.Format("LOD: {0} - {1}", lodTriggerCount, item));
}
return result;
}
catch
{
//exception is thrown when the task is canceled. Returning null does not affect
the ItemsSource.
return null;
}
});

for (int i = 0; i < 14; i++)


{
Source.Add(string.Format("Item {0}", i));
}
}
}
 

2. Define RadListView instance and bind its ItemsSource to the data in the viewmodel:

XAML
<telerikDataControls:RadListView x:Name="listView"
IsLoadOnDemandEnabled="True"
ItemsSource="{Binding Source}"
LoadOnDemandMode="Automatic" />
 

3. Define the ListView namespace:

XAML
xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te

1236
Telerik UI for Xamarin

lerik.XamarinForms.DataControls"
 

4. Set the ViewModel as BindingContext in the page constructor:

C#
this.BindingContext = new ListViewModel();
 

Using LoadOnDemand Event


Another way to handle loading more items is to use the LoadOnDemand event. This event is being
raised on a UI thread, so in the event handler you can add items right away or asynchronously:

 In case the data is available right away, add the items to the ListView ItemsSource in the
LoadOnDemand event handler.
 In case you require an async operation, set the IsLoadOnDemandActive property of the
ListView to True. This notifies the ListView that it must display the loading indicator. Then an
async call can be initiated to get the data. When the new items are ready, you must set the
IsLoadOnDemandActive property to False again to notify the ListView that the
load-on-demand operation is completed.

The example below demonstrates how to use the LoadOnDemand event:

1. Define ListView:

XAML
<telerikDataControls:RadListView x:Name="listView"
IsLoadOnDemandEnabled="True"
LoadOnDemand="ListView_LoadOnDemand"
LoadOnDemandMode="Automatic" />
 

2. Define the ListView namespace:

XAML
xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te
lerik.XamarinForms.DataControls"
 

3. Set ListView itemsSource in page constructor:

C#
this.source = new ObservableCollection<string>();
for (int i = 0; i < 14; i++)
{
source.Add(string.Format("Item {0}", i));
}
this.listView.ItemsSource = this.source;
 

1237
Telerik UI for Xamarin

4. Add the following event handler:

C#
private ObservableCollection<string> source;
private int lodCounter = 0;

private async void ListView_LoadOnDemand(object sender, EventArgs e)


{
// If you need to get new data asynchronously, you must manually update the
loading status.
this.listView.IsLoadOnDemandActive = true;

IEnumerable<string> newItems = await this.GetNewItems();


foreach (string newItem in newItems)
{
this.source.Add(newItem);
}

this.listView.IsLoadOnDemandActive = false;
}

private async Task<IEnumerable<string>> GetNewItems()


{
this.lodCounter++;
await Task.Delay(4000); // Mimic getting data from server asynchronously.
return Enum.GetNames(typeof(DayOfWeek)).Select(day => string.Format("LOD: {0} -
{1}", this.lodCounter, day));
}
 

Using LoadOnDemand Command


This approach is similar to using the LoadOnDemand event, but in this case, the load-on-demand is
handled in the ViewModel through the LoadOnDemandUserCommand exposed by RadListView. In
the Execute method of the command, you can add items right away or asynchronously:

 In case the data is available right away, add the items to the ListView ItemsSource in the
LoadOnDemand command Execute method.
 In case you require an async operation, set the IsLoadOnDemandActive property of the
ListView to True. This notifies the ListView that it must display the loading indicator. Then an
async call can be initiated to get the data. When the new items are ready, you must set the
IsLoadOnDemandActive property to False again to notify the ListView that the
load-on-demand operation is completed. You can control the behavior of
IsLoadOnDemandActive through a binding to a boolean property in the ViewModel class.

The example below demonstrates how to use the LoadOnDemand command:

1. Create a ViewModel class with a LoadItemsCommand as well as IsLoadingMoreItems bool


property:

C#
public class ListViewModel : NotifyPropertyChangedBase

1238
Telerik UI for Xamarin

{
private bool isLoadingMoreItems;
private int lodCounter = 0;

public ListViewModel()
{
this.Source = new ObservableCollection<string>();
for (int i = 0; i < 14; i++)
{
this.Source.Add(string.Format("Item {0}", i));
}
this.LoadItemsCommand = new Command(this.LoadItemsCommandExecute);
}

public ObservableCollection<string> Source { get; }


public ICommand LoadItemsCommand { get; set; }

public bool IsLoadingMoreItems


{
get { return this.isLoadingMoreItems; }
set { this.UpdateValue(ref this.isLoadingMoreItems, value); }
}

private async void LoadItemsCommandExecute(object obj)


{
// If you need to get new data asynchronously, you must manually update the
loading status.
this.IsLoadingMoreItems = true;

IEnumerable<string> newItems = await this.GetNewItems();


foreach (string newItem in newItems)
{
this.Source.Add(newItem);
}

this.IsLoadingMoreItems = false;
}

private async Task<IEnumerable<string>> GetNewItems()


{
this.lodCounter++;
await Task.Delay(4000); // Mimic getting data from server asynchronously.
return Enum.GetNames(typeof(DayOfWeek)).Select(day => string.Format("LOD: {0} -
{1}", this.lodCounter, day));
}
}
 

2. Define the RadListView instance in XAML with the ListViewUserCommand defined as well as
the IsLoadOnDemandActive property bound to the boolean property in the ViewModel:

XAML
<telerikDataControls:RadListView x:Name="listView"

1239
Telerik UI for Xamarin

ItemsSource="{Binding Source}"
IsLoadOnDemandEnabled="True"
IsLoadOnDemandActive="{Binding IsLoadingMoreItems}"
LoadOnDemandMode="Manual">
<telerikDataControls:RadListView.Commands>
<telerikListViewCommands:ListViewUserCommand Id="LoadOnDemand"
Command="{Binding LoadItemsCommand}" />
</telerikDataControls:RadListView.Commands>
</telerikDataControls:RadListView>
 

3. Define the following namespaces:

XAML
xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te
lerik.XamarinForms.DataControls"
xmlns:telerikListViewCommands="clr-namespace:Telerik.XamarinForms.DataControls.ListVie
w.Commands;assembly=Telerik.XamarinForms.DataControls"
 

1. Set the ViewModel as BindingContext in the page constructor:

C#
this.BindingContext = new ListViewModel();
 

Advanced Options
Control the Number of Preloaded Items
This feature works in conjunction with the LoadOnDemandMode.Automatic mode of the ListView. You
can control the minimum number of items loaded ahead through ListView's
LoadOnDemandBufferItemsCount property. By default, it is set to 10 items. When ListView requests
an item in the buffer, it will trigger a new loading batch.

Change the Appearance of the Manual Load Button


This feature works in conjunction with the LoadOnDemandMode.Manual mode of the ListView. You
can control the content of the Load More Button through the LoadOnDemandItemTemplate property.

XAML
<telerikDataControls:RadListView.LoadOnDemandItemTemplate>
<DataTemplate>
<Grid BackgroundColor="Red">
<Label FontSize="24"
HorizontalOptions="Center"
Text="Load more items"
TextColor="Black" />
</Grid>
</DataTemplate>

1240
Telerik UI for Xamarin

</telerikDataControls:RadListView.LoadOnDemandItemTemplate>
 

Change the Appearance of the Manual Loading Indicator


This feature works in conjunction with the LoadOnDemandMode.Manual mode of the ListView.You can
control the content of the Loading Indicator through the LoadingOnDemandItemTemplate property.

XAML
<telerikDataControls:RadListView.LoadingOnDemandItemTemplate>
<DataTemplate>
<Grid BackgroundColor="Green">
<Label FontSize="24"
HorizontalOptions="Center"
Text="Loading..."
TextColor="White" />
</Grid>
</DataTemplate>
</telerikDataControls:RadListView.LoadingOnDemandItemTemplate>
 

See Also
 Events
 Selection
 Reordering

1241
Telerik UI for Xamarin

Scrolling
Vertical ScrollBar
With R1 2020 SP release RadListView provides the option to set the visibility of its vertical scrollbar
according to your preferences:

 VerticalScrollBarVisibility(Xamarin.Forms.ScrollBarVisibility): Specifies whether the vertical


scrollbar will be visualized. By default it is set to ScrollBarVisibility.Default which means the
scrollbar behavior depends on the target platform.

Here is a quick snippet on how you can set it to ScrollBarVisibility.Always:

XAML
<telerikDataControls:RadListView x:Name="listView"
VerticalScrollBarVisibility="Always" />
 

C#
var listView = new RadListView();
listView.VerticalScrollBarVisibility = ScrollBarVisibility.Always;
 

Programmatic Scrolling
RadListView exposes the following method for programmatic scrolling to a specific data item:

 ScrollItemIntoView(object item): Attempts to bring the specified data item into the view.

Example
Here is the definition of the ListView control:

XAML
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<StackLayout>
<Button Clicked="ScrollItemIntoViewClicked" Text="ScrollItemIntoView"/>
<Label x:Name="label"/>
</StackLayout>
<telerikDataControls:RadListView x:Name="listView" Grid.Row="1"
ItemsSource="{Binding Items}"/>
</Grid>

1242
Telerik UI for Xamarin

use the following code to create a simple data for the ListView component:

C#
private Random rnd;
public ObservableCollection<string> Items { get; set; }
public ProgrammaticScrolling()
{
InitializeComponent();

this.rnd = new Random();


this.Items = new ObservableCollection<string>();

for (int i = 0; i < 100; i++)


{
this.Items.Add("Item " + i);
}

this.BindingContext = this;
}
 

Create a method called ScrollToItem and inside this method use ScrollItemIntoView to navigate to a
concrete item:

C#
private void ScrollItemIntoViewClicked(object sender, EventArgs e)
{
this.ScrollToItem();
}
private void ScrollToItem()
{
var item = this.Items[rnd.Next(this.Items.Count - 1)];
this.label.Text = "Scrolled to: " + item;
this.listView.ScrollItemIntoView(item);
}
 

And the end result:

Figure 1: Scrolling item into View

1243
Telerik UI for Xamarin

See Also
 Selection
 Grouping
 Reordering

1244
Telerik UI for Xamarin

Layouts
The RadListView control supports two layouts: linear and grid through the LayoutDefinition property.
It accepts values of type ListViewLayoutBase which is a base class for all list view layouts.

Here are the properties exposed by the ListViewLayoutBase class:

 VerticalItemSpacing (double): Gets or sets the vertical space between two items.
 HorizontalItemSpacing (double): Gets or sets the horizontal space between two items.
 ItemLength (double): Gets or sets the width or height (depending on the layout orientation) of
the items. The default value is -1 which means that the items will be sized according to the
targeted platform default behavior.
 GroupHeaderLength (double): Gets or sets the width or height (depending on the layout
orientation) of the group headers. The default value is -1 which means that the items will be
sized according to the targeted platform default behavior.
 Orientation (Orientation): Gets or sets the orientation (scroll direction) of the layout.

Linear Layout
Linear layout is the default layout of the control. It can be explicitly set by creating an instance of the
ListViewLinearLayout class and assigning it to the RadListView.LayoutDefinition property.

Example
This example will demonstrate how to use the RadListViewLinearLayout.

Here is the list view definition in Xaml:

XAML
<telerikDataControls:RadListView x:Name="listView">
<telerikDataControls:RadListView.ItemTemplate>
<DataTemplate>
<telerikListView:ListViewTemplateCell>
<telerikListView:ListViewTemplateCell.View>
<Grid BackgroundColor="{Binding Color}" />
</telerikListView:ListViewTemplateCell.View>
</telerikListView:ListViewTemplateCell>
</DataTemplate>
</telerikDataControls:RadListView.ItemTemplate>
<telerikDataControls:RadListView.LayoutDefinition>
<telerikListView:ListViewLinearLayout ItemLength="40" VerticalItemSpacing="2"
/>
</telerikDataControls:RadListView.LayoutDefinition>
</telerikDataControls:RadListView>
 

Where:

1245
Telerik UI for Xamarin

XAML
xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te
lerik.XamarinForms.DataControls"
xmlns:telerikListView="clr-namespace:Telerik.XamarinForms.DataControls.ListView;assemb
ly=Telerik.XamarinForms.DataControls"
 

The ItemsSource of the control can be set in the code behind of the page:

C#
var colors = new List<object>();
for (int i = 0; i < 16; i++)
{
var c = 200 - 10 * i;
colors.Add(new { Color = Color.FromRgb(c, c, c) });
};

listView.ItemsSource = colors;
 

This is the result:

Grid Layout
The Grid Layout allows distributing cells in a fixed number of columns/rows. It exposes the following
properties in addition to the basic layout properties:

 SpanCount (int): Gets or sets the count of the columns / rows (depending on the orientation)
of the list.

1246
Telerik UI for Xamarin

The grid layout can be utilized by setting the RadListView.LayoutDefinition property to a new
instance of the ListViewGridLayout class.

Example
This example will demonstrate how to use the RadListViewGridLayout.

Here is the list view definition in Xaml:

XAML
<telerikDataControls:RadListView x:Name="listView">
<telerikDataControls:RadListView.ItemTemplate>
<DataTemplate>
<telerikListView:ListViewTemplateCell>
<telerikListView:ListViewTemplateCell.View>
<Grid BackgroundColor="{Binding Color}" />
</telerikListView:ListViewTemplateCell.View>
</telerikListView:ListViewTemplateCell>
</DataTemplate>
</telerikDataControls:RadListView.ItemTemplate>
<telerikDataControls:RadListView.LayoutDefinition>
<telerikListView:ListViewGridLayout HorizontalItemSpacing="5"
ItemLength="120"
SpanCount="2"
VerticalItemSpacing="5" />
</telerikDataControls:RadListView.LayoutDefinition>
</telerikDataControls:RadListView>
 

Where:

XAML
xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te
lerik.XamarinForms.DataControls"
xmlns:telerikListView="clr-namespace:Telerik.XamarinForms.DataControls.ListView;assemb
ly=Telerik.XamarinForms.DataControls"
 

The ItemsSource of the control can be set in the code behind of the page:

C#
var colors = new List<object>();
for (int i = 0; i < 16; i++)
{
var c = 200 - 10 * i;
colors.Add(new { Color = Color.FromRgb(c, c, c) });
};

listView.ItemsSource = colors;
 

1247
Telerik UI for Xamarin

This is the result:

See Also
 ListView Cell Types
 Cell Swipe
 Pull to Refresh
 Reorder Items

1248
Telerik UI for Xamarin

Cell Swipe
Cell swipe allows end-users to use swipe gestures on cells. When users swipe, they reveal a
designated custom view with buttons, images etc.

The image below shows how swiping right could reveal a Delete button on the left:

You can reveal another custom view if the user swipes left. In this case, Cell Swipe displays the
custom view on the right. As soon as the user taps the swiped item or anywhere on the ListView, the
item returns to its original position.

Properties
You can use the following RadListView properties to configure the Cell Swipe feature:

 IsItemSwipeEnabled (bool): Enables or disables the Cell Swipe feature. The default value is
False.
 SwipeThreshold (double): Defines the length (in pixels) of the swipe gesture that is required
to trigger the feature. Shorter swipe gestures are not respected. The default value is 0.
 SwipeOffset (Thickness): Specifies how much to move the swiped cell to the side and stick it
there. The default value is 100.
 ItemSwipeContentTemplate (DataTemplate): Defines the content that will be visualized when
users swipe a cell.

The SwipeThreshold value must be lower than the SwipeOffset value. This is required because the
SwipeThreshold defines the minimum swipe gesture length that triggers the Cell Swipe feature and
reveals a custom view.
 

Methods
1249
Telerik UI for Xamarin

The following RadListView methods are related to the cell swiping feature:

 void EndItemSwipe(bool isAnimated): Moves the swiped item to its default position.

Events
The following RadListView events are related to the cell swiping feature:

 ItemSwipeStarting: Occurs when the user initiates the swipe gesture. The event arguments
are of the ItemSwipeStartingEventArgs type that provides the following properties:
 Item (object): The item that will be swiped.
 Cancel (bool): If you set this value to false, the swiping will be canceled.
 ItemSwiping: Occurs while the user is swiping the item. The event arguments are of the
ItemSwipingEventArgs type that provides the following properties:
 Item (object): The item that is being swiped.
 Offset (double): The current swipe offset.
 ItemSwipeCompleted: Occurs when the user finishes the swipe gesture. The event
arguments are of the ItemSwipeCompletedEventArgs type that provides the following
properties:
 Item (object): The item that has been swiped.
 Offset (double): The swipe offset at which the item has been dropped.

Commands
In addition to the swipe events, RadListView provides the following commands related to certain
swipe actions:

 ItemSwipeStarting
 ItemSwiping
 ItemSwipeCompleted

For more details on how to utilize the ListView commands, see Commands.

Examples
The RadListView swipe events allow you to configure custom actions that depend on the swipe
direction, the swipe gesture length or the data item.

Alternatively, you can add interactive elements to the swipe content and use the swipe gesture only
to reveal this content. The user can then choose how to interact with the revealed content.

Example with swipe events


The following example demonstrates how to use the ItemSwipeCompleted event. Depending on the
swipe gesture length, we will modify the data item or remove it from the source.

1250
Telerik UI for Xamarin

1. Add the view model for the ListView:

C#
public class Mail : NotifyPropertyChangedBase
{
bool isUnread;

public string Sender { get; set; }

public string Subject { get; set; }

public bool IsUnread


{
get { return isUnread; }
set
{
if (this.isUnread != value)
{
isUnread = value;
OnPropertyChanged();
}
}
}
}

public class ViewModel


{
public ViewModel()
{
this.Source = new ObservableCollection<Mail> {

1251
Telerik UI for Xamarin

new Mail{ Sender = "Terry Tye", Subject = "Re: Summer Vacation" , IsUnread =
true},
new Mail{ Sender = "Felicia Keegan", Subject = "Seminar Invitation", IsUnread =
true},
new Mail{ Sender = "Jared Linton", Subject = "Discount code"},
new Mail{ Sender = "Mark Therese", Subject = "Quick feedback", IsUnread =
true},
new Mail{ Sender = "Elvina Randall", Subject = "Happy Birthday!"},
new Mail{ Sender = "Emilia Porter", Subject = "Check the attachment", IsUnread
= true},
new Mail{ Sender = "Jared Linton", Subject = "Gillian Flynn"},
new Mail{ Sender = "Felicia Keegan", Subject = "Re: Summer Vacation"},
new Mail{ Sender = "Felicia Keegan", Subject = "Pictures"},
};
}

public ObservableCollection<Mail> Source { get; set; }


}
 

1. Set up ListView. Swiping left or right will reveal content with a hint for what will happen if the
user completes the swipe action.

XAML
<ContentView.BindingContext>
<local:ViewModel />
</ContentView.BindingContext>
<telerikDataControls:RadListView x:Name="listView"
IsItemSwipeEnabled="True"
ItemSwipeCompleted="OnItemSwipeCompleted"
ItemsSource="{Binding Source}"
SelectionMode="None"
SwipeOffset="70, 0, 70, 0"
SwipeThreshold="10">
<telerikDataControls:RadListView.ItemTemplate>
<DataTemplate>
<listView:ListViewTemplateCell>
<listView:ListViewTemplateCell.View>
<Grid BackgroundColor="White">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<StackLayout Margin="10,10,10,0" Orientation="Horizontal">
<Image HeightRequest="10"
IsVisible="{Binding IsUnread}"
Source="unread.png"
VerticalOptions="Center"
WidthRequest="10" />
<Label FontAttributes="Bold"
FontSize="16"
Text="{Binding Sender}"
TextColor="Black" />

1252
Telerik UI for Xamarin

</StackLayout>
<StackLayout Grid.Row="1"
Margin="10,0,10,10"
Orientation="Horizontal">
<Label FontSize="14"
Text="Subject:"
TextColor="Gray" />
<Label FontSize="14"
Text="{Binding Subject}"
TextColor="Gray" />
</StackLayout>
</Grid>
</listView:ListViewTemplateCell.View>
</listView:ListViewTemplateCell>
</DataTemplate>
</telerikDataControls:RadListView.ItemTemplate>
<telerikDataControls:RadListView.ItemSwipeContentTemplate>
<DataTemplate>
<Grid Margin="0"
Padding="0"
ColumnSpacing="0"
RowSpacing="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="70" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="70" />
</Grid.ColumnDefinitions>
<Label BackgroundColor="#2474d2"
HorizontalTextAlignment="Center"
Text="Mark as read"
TextColor="White"
VerticalTextAlignment="Center"
WidthRequest="70" />
<Label Grid.Column="2"
BackgroundColor="Red"
HorizontalTextAlignment="Center"
Text="delete"
TextColor="White"
VerticalTextAlignment="Center"
WidthRequest="70" />
</Grid>
</DataTemplate>
</telerikDataControls:RadListView.ItemSwipeContentTemplate>
</telerikDataControls:RadListView>
 

1. Define the ListView namespace:

XAML
xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te
lerik.XamarinForms.DataControls"
xmlns:telerikListView="clr-namespace:Telerik.XamarinForms.DataControls.ListView;assemb
ly=Telerik.XamarinForms.DataControls"

1253
Telerik UI for Xamarin

1. Configure what happens when the user completes the swipe gesture:

C#
void OnItemSwipeCompleted(object sender, ItemSwipeCompletedEventArgs e)
{
var listView = sender as RadListView;
var item = e.Item as Mail;

listView.EndItemSwipe();

if (e.Offset >= 70)


{
item.IsUnread = false;
}
else if (e.Offset <= -70)
{
(listView.ItemsSource as ObservableCollection<Mail>).Remove(item);
}
}
 

We call the EndItemSwipe() method to force the item to go to its default position since the scenario
does not require any interaction with the swipe content itself.

Example with interactive content


The following example demonstrates how to add a delete button to the swipe content. We use the
button's Clicked event handler to delete an item from the ListView source.

1254
Telerik UI for Xamarin

1. Add the view model for the ListView:

C#
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
}

public class ViewModel


{
public ViewModel()
{
this.Source = new ObservableCollection<Book> {
new Book{ Title = "The Fault in Our Stars ", Author = "John Green"},
new Book{ Title = "Divergent", Author = "Veronica Roth"},
new Book{ Title = "Gone Girl", Author = "Gillian Flynn"},
new Book{ Title = "Clockwork Angel", Author = "Cassandra Clare" },
new Book{ Title = "The Martian", Author = "Andy Weir"},
new Book{ Title = "Ready Player One", Author = "Ernest Cline"},
new Book{ Title = "The Lost Hero", Author = "Rick Riordan" },
new Book{ Title = "All the Light We Cannot See", Author = "Anthony Doerr"},
new Book{ Title = "Cinder", Author = "Marissa Meyer"},
new Book{ Title = "Me Before You", Author = "Jojo Moyes"},
new Book{ Title = "The Night Circus", Author = "Erin Morgenstern"},
};
}

public ObservableCollection<Book> Source { get; set; }


}

1255
Telerik UI for Xamarin

1. Set up ListView. Note that the SwipeOffset is equal to the width of the button in the swipe
content. Thus, when the swipe is complete, the revealed content will be the whole button.

XAML
<ContentView.BindingContext>
<local:ViewModel />
</ContentView.BindingContext>
<telerikDataControls:RadListView x:Name="listView"
BackgroundColor="White"
IsItemSwipeEnabled="True"
ItemsSource="{Binding Source}"
SelectionMode="None"
SwipeOffset="70, 0, 0, 0"
SwipeThreshold="10">
<telerikDataControls:RadListView.ItemTemplate>
<DataTemplate>
<telerikListView:ListViewTemplateCell>
<telerikListView:ListViewTemplateCell.View>
<Grid>
<Label Margin="10,10,10,0"
FontAttributes="Bold"
FontSize="16"
Text="{Binding Title}"
TextColor="Black" />
<Label Grid.Row="1"
Margin="10,0,10,10"
FontAttributes="Italic"
FontSize="13"
Text="{Binding Author}"
TextColor="Gray" />
</Grid>
</telerikListView:ListViewTemplateCell.View>
</telerikListView:ListViewTemplateCell>
</DataTemplate>
</telerikDataControls:RadListView.ItemTemplate>
<telerikDataControls:RadListView.ItemStyle>
<telerikListView:ListViewItemStyle BackgroundColor="White" />
</telerikDataControls:RadListView.ItemStyle>
<telerikDataControls:RadListView.ItemSwipeContentTemplate>
<DataTemplate>
<Grid Margin="0"
Padding="0"
ColumnSpacing="0"
RowSpacing="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="70" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Button Margin="0"
BackgroundColor="Red"
BorderRadius="0"

1256
Telerik UI for Xamarin

Clicked="RemoveBook"
Image="delete.png"
WidthRequest="70" />
</Grid>
</DataTemplate>
</telerikDataControls:RadListView.ItemSwipeContentTemplate>
</telerikDataControls:RadListView>
 

1. Define the ListView namespace:

XAML
xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te
lerik.XamarinForms.DataControls"
xmlns:telerikListView="clr-namespace:Telerik.XamarinForms.DataControls.ListView;assemb
ly=Telerik.XamarinForms.DataControls"
 

1. Configure what happens when the user completes the swipe gesture. The BindingContext of
the swipe content is the data item. This could be used to perform operations on the data. In
this case, we will delete the item from the source.

C#
void RemoveBook(object sender, EventArgs e)
{
var item = (sender as BindableObject).BindingContext as Book;
(this.BindingContext as ViewModel).Source.Remove(item);
}
 

Sample Cell Swipe examples are available in the ListView => Gestures folder of the SDK
Browser application.

You can directly explore the code in the SDKBrowser Examples repository on GitHub.

See Also
 ListView Cell Types
 ListView Layouts
 Commands
 Pull to Refresh
 Reorder Items

1257
Telerik UI for Xamarin

Pull to Refresh
If the list contains items, which may change after the initial load, it may be good idea to allow users
to refresh that list. RadListView is capable of doing this by a pull-to-refresh gesture. The feature
allows the data to be refreshed by swiping finger down when the content is scrolled up to the top.
This will trigger an animated activity indicator which will stay visible until data is refreshed.

This feature consists of:

 RadListView.IsPullToRefreshEnabled: a boolean property which gets or sets a statement


disabling or enabling the feature. The default value of the property is false.
 RadListView.RefreshRequested: a public event which is triggered when the pull-to-refresh
gesture is triggered. The custom data refreshing logic should be implemented in its handler.
 RadListView.EndRefresh(): a public method which must be called when the custom data
refreshing logic finishes executing.

Example
This example demonstrates how to enable the pull to refresh functionality.

Here is the definition of the list view in Xaml:

XAML
<telerikDataControls:RadListView x:Name="listView"
IsPullToRefreshEnabled="True"
RefreshRequested="RefreshRequested" />
 

Where:

XAML
xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te
lerik.XamarinForms.DataControls"
 

Let's set some simple source to the list view in the code behind of the page:

C#
listView.ItemsSource = Enumerable.Range(0, this.count);
 

And this is the method that updates the source of the list view when refresh is triggered:

C#
private int count = 10;

private async void RefreshRequested(object sender, PullToRefreshRequestedEventArgs e)

1258
Telerik UI for Xamarin

{
await Task.Delay(3000);
listView.ItemsSource = Enumerable.Range(this.count, 10);
this.count += 10;
listView.EndRefresh();
}
 

This is how the refresh indicator looks like:

Troubleshooting
RadListView should not be used in a View that restricts the Height to the minimum amount of vertical
space. An example is StackLayout or a Grid with <RowDefinition Height="Auto" />. This will
restrict the RadListView from expanding when items are populated and prevents Pull To Refresh
from working correctly.

The recommended use is to place the RadListView control in a container that expands to fill
available space. For example, the RadListView in the example below is in the star-sized Grid
RowDefinition.

<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>

<!-- This RadListView is in the star-sized row and will expand properly -->
<telerikDataControls:RadListView x:Name="EventsList" />

1259
Telerik UI for Xamarin

<Label Text="I'm in auto-sized row" Grid.Row="1" />


</Grid>
 

See Also
 ListView Cell Types
 ListView Layouts
 Cell Swipe
 Reorder Items

1260
Telerik UI for Xamarin

Reorder Items
The items reorder feature allows end-users reorder the list view data items. If the feature is enabled,
when the user holds on an item, the reorder mode is triggered and the user can move and release
the item at the desired position. This will perform reorder operation on the data.

Reorder functionality can be enabled by setting the IsItemsReorderEnabled property to true.

Example
This example will demonstrate how to enable the items reorder functionality and style the list view
items.

Here is the definition of the list view in Xaml:

XAML
<telerikDataControls:RadListView x:Name="listView"
IsItemsReorderEnabled="True"
SelectionMode="None">
<telerikDataControls:RadListView.ItemTemplate>
<DataTemplate>
<telerikListView:ListViewTemplateCell>
<telerikListView:ListViewTemplateCell.View>
<StackLayout Spacing="0">
<Label Margin="5,10,5,10"
FontSize="16"
Text="{Binding}"
TextColor="Black"
VerticalTextAlignment="Center" />
<BoxView Margin="0"
BackgroundColor="Gray"
HeightRequest="1" />
</StackLayout>
</telerikListView:ListViewTemplateCell.View>
</telerikListView:ListViewTemplateCell>
</DataTemplate>
</telerikDataControls:RadListView.ItemTemplate>
</telerikDataControls:RadListView>
 

Where:

XAML
xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te
lerik.XamarinForms.DataControls"
xmlns:telerikListView="clr-namespace:Telerik.XamarinForms.DataControls.ListView;assemb
ly=Telerik.XamarinForms.DataControls"
 

1261
Telerik UI for Xamarin

We will set the source in the code behind of the page:

C#
this.listView.ItemsSource = new ObservableCollection<string>()
{
"Check weather for London",
"Call Brian Ingram",
"Check the childrens' documents",
"Take care of the dog",
"Airplane tickets reschedule",
"Check the trains schedule",
"Bills due: Alissa's ballet class",
"Weekly organic basket"
};
 

Here is the result:

You could also take advantage of the Reorder Events for additional control over the reorder
functionality of RadListView.
 

See Also
 ListView Cell Types
 ListView Layouts
 Cell Swipe
 Pull to Refresh

1262
Telerik UI for Xamarin

Events
The RadListView component exposes the following events:

Item events

 ItemTapped - occurs when an item is tapped. The ItemTapped event handler receives two
parameters:
 The sender argument which is of type object, but can be cast to the RadListView type.
 An ItemTapEventArgs object which has a reference to the tapped item through its Item
property.
 ItemHold - occurs when the end user is holding on a specific item. The ItemHold event
handler receives two parameters:
 The sender argument which is of type object, but can be cast to the RadListView type.
 An ItemHoldEventArgs object which has a reference to the held item through its Item
property.
 RefreshRequested - occurs when the pull-to-refresh gesture is triggered. The
RefreshRequested event handler receives two parameters:
 The sender argument which is of type object, but can be cast to the RadListView type.
 A PullToRefreshRequestedEventArgs object which provides Cancel property used to
cancel the pull-to-refresh operation.

For more details on the RefreshRequested event usage go to Pull to Refresh topic.
 

Selection events

 SelectionChanged - occurs when the SelectionItems collection is updated. The


SelectionChanged event handler receives two parameters:
 The sender argument which is of type object, but can be cast to the RadListView type.
 A NotifyCollectionChangedEventArgs object which provides information on the collection
changed event. For more details check NotifyCollectionChangedEventArgs Class topic.

Group/Reorder events

 GroupHeaderTapped - occurs when a group header of a grouped ListView is tapped. The


GroupHeaderTapped event handler receives two parameters:
 The sender argument which is of type object, but can be cast to the RadListView type.
 A GroupHeaderTapEventArgs object which provides the following properties:
 Key - gets the specific key for the group;
 Items - gets the child items of the group;
 ReorderStarting - occurs when a reorder operation is about to start. The ReorderStarting
event handler receives two parameters:
 The sender argument which is of type object, but can be cast to the RadListView type.
 A ReorderStartingEventArgs object provides the following properties:
 Item - gets the item that is about to be dragged;
 Cancel - boolean property which can be used to cancel the reorder operation;

1263
Telerik UI for Xamarin

 ReorderEnded - occurs when a reorder operation has ended. The ReorderEnded event
handler receives two parameters:
 The sender argument which is of type object, but can be cast to the RadListView type.
 A ReorderEndedEventArgs object which has a reference to the item that was reordered
through its Item property;

Swipe Events
RadListView exposes a few useful events related to the item swiping feature, namely
ItemSwipeStarting, ItemSwiping and ItemSwipeCompleted. For detailed information on the swiping
events usage go to Cell Swipe topic.

See Also
 Selection
 Grouping
 Reordering
 Pull to Refresh
 Cell Swipe

1264
Telerik UI for Xamarin

Commands
The Command design-pattern is widely used in the XAML and MVVM world. RadListView strictly
follows the Command design-pattern best practices and provides an intuitive and easy-to-use set of
APIs that allow you to control various aspects of RadListView’s behavior.

RadListView exposes a Commands collection that allows you to register custom commands with
each control’s instance through the RadListView.Commands property:

 Commands: Gets the collection with all the custom commands registered with the
CommandService. Custom commands have higher priority than the built-in (default) ones.

CommandId Enumeration
All predefined commands within a RadListView instance are identified by a member of the
CommandId enumeration. This member is actually the key that relates a command instance to a
particular action/routine within the owning ListView.

To register a custom command within a RadListView instance you can:

 Inherit from the ListViewCommand class and override its CanExecute and Execute methods.
 Use the ListViewUserCommand class and bind its Command property to a Command in your
ViewModel.

In both cases, you need to set the Id property of the new command so that it can be properly
associated with the desired action/event.

Following are the members of the CommandId enumerations:

 ItemTap
 ItemSwiping
 ItemSwipeCompleted
 ItemSwipeStarting
 PullToRefreshRequested
 SelectionChanged
 LoadOnDemand
 ItemHold
 GroupHeaderTap
 ReorderStarting
 ReorderEnded

These actions correspond to the events exposed by RadListView. For more details, see the Events
topic.
 
For each of the available commands, there is a context object of type
[CommandId]CommandContext, for example, ItemTapCommandContext,
ItemHoldCommandContext, etc. The context object is passed as a parameter in its Execute method

1265
Telerik UI for Xamarin

and provides information identical to the corresponding event's args.

Inheriting from ListViewCommand


To demonstrate inheriting from ListViewCommand, the following example handles the ItemTap
action as a Command:

1. Create a class that inherits from ListViewCommand and set its Id property. Then override the
CanExecute and Execute methods:

C#
public class ItemTappedUserCommand : ListViewCommand
{
public ItemTappedUserCommand()
{
Id = CommandId.ItemTap;
}
public override bool CanExecute(object parameter)
{
return true;
}
public override void Execute(object parameter)
{
var tappedItem = (parameter as ItemTapCommandContext).Item;
//add your logic here
Application.Current.MainPage.DisplayAlert("", "You've selected " + tappedItem,
"OK");
}
}
 

2. Add the custom command to the Commands collection of the RadListView instance:

C#
listView1.Commands.Add(new ItemTappedUserCommand());
 

Binding ListViewUserCommand
With the ListViewUserCommand binding approach, you can directly handle the custom commands in
the ViewModel. Here is a quick example:

1. Add the custom command to the ViewModel:

C#
public class ViewModel
{
public ViewModel()
{

1266
Telerik UI for Xamarin

this.Source = new List<string> {"Tom", "Anna", "Peter", "Teodor", "Martin"};


this.ItemTapCommand = new Command<ItemTapCommandContext>(this.ItemTapped);
}
private void ItemTapped(ItemTapCommandContext context)
{
var tappedItem = context.Item;
//add your logic here
Application.Current.MainPage.DisplayAlert("", "You've selected " + tappedItem,
"OK");
}
public List<string> Source { get; set; }
public ICommand ItemTapCommand { get; set; }
}
 

2. Bind the ItemTapCommand through the predefined ListViewUserCommand command. Its Id


property is used to map the command to the corresponding action with the control:

XAML
<telerikDataControls:RadListView x:Name="listView2" ItemsSource="{Binding Source}"
AutomationId="bottomListView">
<telerikDataControls:RadListView.BindingContext>
<local:ViewModel />
</telerikDataControls:RadListView.BindingContext>
<telerikDataControls:RadListView.Commands>
<telerikListViewCommands:ListViewUserCommand Id="ItemTap" Command="{Binding
ItemTapCommand}" />
</telerikDataControls:RadListView.Commands>
</telerikDataControls:RadListView>
 

3. Define the telerikListViewCommands:

XAML
xmlns:telerikListViewCommands="clr-namespace:Telerik.XamarinForms.DataControls.ListVie
w.Commands;assembly=Telerik.XamarinForms.DataControls"
```
 

See Also
 Events
 Selection
 Reordering

1267
Telerik UI for Xamarin

Item Styles
The RadListView component provides styling mechanism for customizing the look of its items. This
mechanism consists of the following properties of type "ListViewItemStyle":

 ItemStyle
 SelectedItemStyle
 PressedItemStyle
 ReorderItemStyle

ListViewItemStyle
The properties of this object are respectively applied to the native components. The supported ones
are the following:

 BackgroundColor (Color): sets the background of the item(s).


 BorderColor (Color): sets the color of the border.
 BorderWidth (double): defines the width of the borer.
 BorderLocation (Location): describes an enumeration describing where the border should be
visible.
 TextCellTextColor (Color): defines the text color of the ListView TextCell.

Location
This enumeration contains the following members:

 None - the border should not be visualized.


 Top - the border should be visualized only at the top side.
 Bottom -the border should be visualized only at the bottom side.
 Left - the border should be visualized only at the left side.
 Right - the border should be visualized only at the right side.
 All (default value) - the border should be visualized all around the item.

Example
XAML
<telerikDataControls:RadListView x:Name="listView" ItemsSource="{Binding Source}"
IsItemsReorderEnabled="True">
<telerikDataControls:RadListView.BindingContext>
<local:ViewModel />
</telerikDataControls:RadListView.BindingContext>
<telerikDataControls:RadListView.ItemTemplate>
<DataTemplate>
<telerikListView:ListViewTextCell Text="{Binding Name}" />
</DataTemplate>
</telerikDataControls:RadListView.ItemTemplate>
<telerikDataControls:RadListView.ItemStyle>

1268
Telerik UI for Xamarin

<telerikListView:ListViewItemStyle BackgroundColor="#1263E5"
TextCellTextColor="#AAC7F6"
BorderColor="#0A3A82"
BorderWidth="2"
BorderLocation="All" />
</telerikDataControls:RadListView.ItemStyle>
<telerikDataControls:RadListView.SelectedItemStyle>
<telerikListView:ListViewItemStyle BackgroundColor="#83A9E2"
TextCellTextColor="#AAC7F6"
BorderColor="#0A3A82"
BorderWidth="2"
BorderLocation="Bottom"/>
</telerikDataControls:RadListView.SelectedItemStyle>
<telerikDataControls:RadListView.PressedItemStyle>
<telerikListView:ListViewItemStyle BackgroundColor="#C1C1C1"
TextCellTextColor="#AAC7F6"
BorderColor="#0B3D89"
BorderWidth="2"
BorderLocation="Bottom"/>
</telerikDataControls:RadListView.PressedItemStyle>
<telerikDataControls:RadListView.ReorderItemStyle>
<telerikListView:ListViewItemStyle BackgroundColor="#0B3D89"
TextCellTextColor="#AAC7F6"
BorderColor="Black"
BorderWidth="2"
BorderLocation="All" />
</telerikDataControls:RadListView.ReorderItemStyle>
</telerikDataControls:RadListView>
 

C#
var listView = new RadListView
{
ItemsSource = new ViewModel().Source,
ItemTemplate = new DataTemplate(() =>
{
var label = new Label { Margin = new Thickness(10) };
var content = new Grid();
content.Children.Add(label);
label.SetBinding(Label.TextProperty, new Binding(nameof(SourceItem.Name)));

return new ListViewTemplateCell


{
View = content
};
})
};
 

And here is the end result:

Figure 1: ListView with ItemStyle and SelectedItemStyle

1269
Telerik UI for Xamarin

Figure 2: ListView with ReorderItemStyle

You can find a working demo labeled ItemStyles in the ListView/Styling folder of the SDK Samples
Browser application.
 

ListViewItemStyle with Bindable Properties

1270
Telerik UI for Xamarin

Additionally, the styling properties of ListViewItemStyle could be used as bindable properties in order
to allow you even more flexibility in customizing the visual appearance of RadListiView.

Example
Here is a quick example on how you could bind ListViewItemStyle's properties to corresponding
properties of type Color/Location inside the ViewModel:

XAML
<telerikDataControls:RadListView.ItemStyle>
<telerikListView:ListViewItemStyle BackgroundColor="{Binding Background}"
BorderColor="{Binding BorderColor}"
BorderLocation="{Binding BorderLocation}"
BorderWidth="{Binding BorderWidth}" />
</telerikDataControls:RadListView.ItemStyle>
 

Here is how the ItemStyle bindable property looks:

Figure 3: ListView with Bindable ItemStyle

There are examples in the ListView/Styling folder of the SDK Samples Browser application, how you
can use those properties as a bindable.
 

See Also
 Selection

1271
Telerik UI for Xamarin

 Reordering
 StyleSelector

1272
Telerik UI for Xamarin

ItemStyle Selector
The RadListView component exposes conditional styling feature. It allows users to apply a different
Style to each item depending on a specific condition.

Example
The following example will demonstrate how to apply the Conditional Styling in the RadlistView
control.

Lets add the RadlistView component and create a simple data.

Here is an example how to setup the ListView control:

XAML
<telerikDataControls:RadListView x:Name="listView" ItemsSource="{Binding Source}">
<telerikDataControls:RadListView.BindingContext>
<local:ViewModel />
</telerikDataControls:RadListView.BindingContext>
<telerikDataControls:RadListView.ItemTemplate>
<DataTemplate>
<telerikListView:ListViewTemplateCell>
<telerikListView:ListViewTemplateCell.View>
<Grid>
<Label Margin="10" Text="{Binding Name}" />
</Grid>
</telerikListView:ListViewTemplateCell.View>
</telerikListView:ListViewTemplateCell>
</DataTemplate>
</telerikDataControls:RadListView.ItemTemplate>
</telerikDataControls:RadListView>
 

C#
var listView = new RadListView
{
ItemsSource = new ViewModel().Source,
ItemTemplate = new DataTemplate(() =>
{
var label = new Label { Margin = new Thickness(10) };
var content = new Grid();
content.Children.Add(label);
label.SetBinding(Label.TextProperty, new Binding(nameof(SourceItem.Name)));

return new ListViewTemplateCell


{
View = content
};

1273
Telerik UI for Xamarin

})
};
 

and lets create a simple data for the ListView component:

C#
public class SourceItem
{
public SourceItem(string name, int age)
{
this.Name = name;
this.Age = age;
}

public string Name { get; set; }

public int Age { get; set; }


}

public class ViewModel


{
public ViewModel()
{
this.Source = new List<SourceItem> {
new SourceItem("Tom", 25),
new SourceItem("Anna",18),
new SourceItem("Peter",43),
new SourceItem("Teodor",29),
new SourceItem("Lorenzo",65),
new SourceItem("Andrea",79),
new SourceItem("Martin",5) };
}

public List<SourceItem> Source { get; set; }


}
 

We can set a different style for a specific item using the ListViewStyleSelector class. We can use the
OnSelectStyle method to change the styles of the items in the RadListView control. A sample
implementation of a custom class that derives from ListViewStyleSelector and overrides its
OnSelectStyle method is shown below:

C#
public class ExampleListViewStyleSelector : ListViewStyleSelector
{
protected override void OnSelectStyle(object item, ListViewStyleContext
styleContext)
{
var style = new ListViewItemStyle();
styleContext.ItemStyle = style;
styleContext.SelectedItemStyle = new ListViewItemStyle

1274
Telerik UI for Xamarin

{
BackgroundColor = Color.Gray,
BorderColor = Color.Red,
BorderWidth = 2
};

var sourceItem = item as SourceItem;


if (sourceItem.Age < 18)
{
styleContext.ItemStyle.BackgroundColor = Color.Blue;
}
else if (sourceItem.Age < 65)
{
styleContext.ItemStyle.BackgroundColor = Color.Green;
}
}
}
 

All that is left is to set this custom style selector to the ItemStyleSelector property of the RadListView
control:

C#
listView.ItemStyleSelector = new ExampleListViewStyleSelector();
 

Conditional Styling
This is how the RadListView control will look like when conditional styling is used.

1275
Telerik UI for Xamarin

SDK Browser application contains an example that shows StyleSelector feature in RadListView
cotrol. You can find the application in the Examples folder of your local Telerik UI for Xamarin
installation.
 

See Also
 Selection
 Styling
 Reordering

1276
Telerik UI for Xamarin

GroupHeader Style
In addition to the Item Styles, RadListView gives the option to modify the visual appearance of its
group headers when grouping is enabled. The feature is implemented through the ListView's
GroupHeaderStyle property of type ListViewGroupStyle.

ListViewGroupStyle provides means for customizing the border as well as background and text color
of the group headers. Below you can find a list of the available styling options:

 BackgroundColor (Color): sets the background of the group header(s).


 BorderColor (Color): sets the color of the border.
 BorderWidth (double): defines the width of the borer.
 BorderLocation (Location): defines an enumeration describing where the border should be
visible.
 TextColor (Color): defines the text color of the ListView GroupHeader.

To learn more about the grouping functionality of RadListView check Grouping Overview topic.
 

Example
Let's have a simple City class:

C#
public class City
{
public string Name { get; set; }
public string Country { get; set; }
}
 

And a sample ViewModel class:

C#
public class ViewModel
{
public ObservableCollection<City> Cities { get; set; }

public ViewModel()
{
this.Cities = new ObservableCollection<City>()
{
new City() { Name = "Barcelona", Country = "Spain"},
new City() { Name = "Madrid", Country = "Spain"},
new City() { Name = "Rome", Country = "Italy"},
new City() { Name = "Florence", Country = "Italy"},
new City() { Name = "London", Country = "England"},
new City() { Name = "Manchester", Country = "England"},

1277
Telerik UI for Xamarin

new City() { Name = "New York", Country = "USA"},


new City() { Name = "Boston", Country = "USA"}
};
}
}
 

Set it as BindingContext:

C#
this.BindingContext = new ViewModel();
 

Lastly, add the RadListView definition with a GroupHeaderStyle applied:

XAML
<telerikDataControls:RadListView x:Name="listView"
ItemsSource="{Binding Cities}">
<telerikDataControls:RadListView.ItemTemplate>
<DataTemplate>
<telerikListView:ListViewTextCell Text="{Binding Name}"
TextColor="#1263E5" />
</DataTemplate>
</telerikDataControls:RadListView.ItemTemplate>
<telerikDataControls:RadListView.GroupHeaderStyle>
<telerikListView:ListViewGroupStyle BackgroundColor="#1263E5"
TextColor="#AAC7F6"
BorderColor="#0A3A82"
BorderWidth="1" />
</telerikDataControls:RadListView.GroupHeaderStyle>
<telerikDataControls:RadListView.GroupDescriptors>
<telerikListView:PropertyGroupDescriptor PropertyName="Country" />
</telerikDataControls:RadListView.GroupDescriptors>
</telerikDataControls:RadListView>
 

And here is the end result:

Figure 1: ListView with GroupHeaderStyle

1278
Telerik UI for Xamarin

You can find a working demo labeled GroupHeader Style in the ListView/Styling folder of the SDK
Samples Browser application.
 

See Also
 Grouping
 Item Styles
 Items StyleSelector

1279
Telerik UI for Xamarin

ListViewTemplateCell and
SelectedItemStyle
When using a ListViewTemplateCell, a SelectedItemStyle's TextCellTextColor value will not be used
for custom views in the DataTemplate. You can still achieve a similar result by using a model
property and ValueConverter, the example below uses such an approach.

Example
Add an IsSelected boolean property with NotifyPropertyChanged implemented to the business
object.

C#
public class SourceItem : INotifyPropertyChanged
{
public string Name { get; set; }

private bool isSelected;


public bool IsSelected
{
get => isSelected;
set
{
isSelected = value;
OnPropertyChanged();
}
}

public event PropertyChangedEventHandler PropertyChanged;


protected virtual void OnPropertyChanged([CallerMemberName] string propertyName =
null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
 

Create an IValueConverter implementation that returns a different color based on the value of
IsSelected.

C#
class SelectedToColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo
culture)
{
if ((bool)value == true)
{

1280
Telerik UI for Xamarin

return Color.Green;
}

return Color.Gray;
}

public object ConvertBack(object value, Type targetType, object parameter,


CultureInfo culture)
{
throw new NotImplementedException();
}
}
 

In XAML below, the following is implemented:

1. Added an instance of the SelectedToColorConverter to the RadListView control's Resources


2. The Label's TextColor property is bound to the IsSelected property, with a converter defined
using the SelectedToColorConverterKey.
3. An event hander is defined for SelectionChanged

XML
<telerikDataControls:RadListView SelectionChanged="RadListView_OnSelectionChanged">
<telerikDataControls:RadListView.Resources>
<ResourceDictionary>
<portable:SelectedToColorConverter x:Key="SelectedToColorConverterKey"/>
</ResourceDictionary>
</telerikDataControls:RadListView.Resources>
<telerikDataControls:RadListView.ItemTemplate>
<DataTemplate>
<telerikListView:ListViewTemplateCell>
<telerikListView:ListViewTemplateCell.View>
<Grid Padding="3">
<Label Margin="10"
Text="{Binding Name}"
TextColor="{Binding IsSelected, Converter={StaticResource
SelectedToColorConverterKey}}"/>
</Grid>
</telerikListView:ListViewTemplateCell.View>
</telerikListView:ListViewTemplateCell>
</DataTemplate>
</telerikDataControls:RadListView.ItemTemplate>
</telerikDataControls:RadListView>
 

Finally, in the SelectionChanged event handler, the IsSelected value is updated:

C#
private void RadListView_OnSelectionChanged(object sender,
NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null && e.NewItems.Count > 0)

1281
Telerik UI for Xamarin

{
(e.NewItems[0] as SourceItem).IsSelected = true;
}

if (e.OldItems !=null && e.OldItems.Count > 0)


{
(e.OldItems[0] as SourceItem).IsSelected = false;
}
}
 

See Also
 Selection
 Styling

1282
Telerik UI for Xamarin

Overview
Telerik Map for Xamarin is a data visualization control whose primary purpose is to visualize rich
spatial data. The control provides visualization of ESRI shapefiles that consist of geometric objects,
such as lines, polylines and polygons. Such objects are commonly used to display various schemes,
for example floor plans and seats distribution, all the way to parts of maps for countries, roads,
rivers, etc.

Figure 1: RadMap Overview

Key features
 Shape File(s) visualization: RadMap can display rich spatial data from ESRI shapefiles. Each
shapefile should be loaded and configured through a ShapefileLayer instance added to the
Layers collection of the control. For more details on this check Layers Overview topic.
 Support for multiple layers: The layered architecture of the control provides the option to load
multiple shapefiles, so you can visualize different types of elements on the same map.
 Various ways to load shapefiles: You could load the shapefiles from a stream, from a file
added as embedded resource or a file located on the device, etc. For more details check
here.
 Pan and Zooming: RadMap provides pan and zoom functionality that will help you interact
with the view and inspect your data. You could choose between only pan, only zoom or both
through InteractionMode property. For more details go here.

1283
Telerik UI for Xamarin

 Shape Labels: You can show a label for each shape in the RadMap control through the
LabelAttributeName property of the ShapefileLayer instance.
 Selection: The control supports single and multiple selection of shapes to help you draw
attention on specific areas. Read the Selection topic for more details regarding this feature.
 Commands: RadMap allows you to replace the default behavior of ZoomIn and ZoomOut
commands with a custom implementation. For detailed information on the matter check
Commands article.
 Shapes Styling: You could apply various Fill and Stroke colors to the shapes to make the
map consistent with the design of your app. For more details check Styling article.

See Also
 Getting Started

1284
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadMap control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadMap control

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadMap control you have to install the Telerik.UI.for.Xamarin.Map
nuget package. This nuget will automatically refer the Telerik.UI.for.Xamarin.Common,
Telerik.UI.for.Xamarin.Primitives, Telerik.UI.for.Xamarin.DataControls, SkiaSharp and
ShiaSharp.Views.Forms nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadMap component:

Platform Assemblies
Portable Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Map.dll
Android Telerik.Xamarin.Android.Common.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Map.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Map.dll
UWP Telerik.Core.dll
Telerik.UI.Xaml.Primitives.UWP.dll
Telerik.XamarinForms.Common.dll

1285
Telerik UI for Xamarin

Telerik.XamarinForms.Map.dll
RadMap is rendered via the SkiaSharp graphics library so you need to install also SkiaSharp and
SkiaSharp.Views.Forms in all projects of the Xamarin solution (portable, android, ios, etc).
 

3. Adding RadMap control


You could use one of the following approaches:

Drag the control from the Toolbox.

Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML or C#.

The snippet below shows a simple RadMap definition:

XAML
<telerikMap:RadMap x:Name="map">
<telerikMap:RadMap.Layers>
<telerikMap:ShapefileLayer>
<telerikMap:ShapefileLayer.Reader>
<telerikMap:MapShapeReader x:Name="reader"/>
</telerikMap:ShapefileLayer.Reader>
</telerikMap:ShapefileLayer>
</telerikMap:RadMap.Layers>
</telerikMap:RadMap>
 

C#
var map = new RadMap();

var assembly = this.GetType().Assembly;


var shapeFileLayer = new ShapefileLayer()
{
Reader = new MapShapeReader() { Source =
MapSource.FromResource("SDKBrowser.Examples.MapControl.world.shp", assembly) }
};
map.Layers.Add(shapeFileLayer);
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikMap="clr-namespace:Telerik.XamarinForms.Map;assembly=Telerik.XamarinForms
.Map"

1286
Telerik UI for Xamarin

C#
using Telerik.XamarinForms.Map;
 

RadMap uses *.shp files that contain the coordinates of the shapes that will be drawn by the map
and an optional *.dbf file for each *.shp file with additional attributes of the shapes.

You would need to assign the .shp file containing the data through the Source property of the
MapShapeReader like this:

C#
var assembly = this.GetType().Assembly;
var source = MapSource.FromResource("SDKBrowser.Examples.MapControl.world.shp",
assembly);
this.reader.Source = source;
 

In the example the .shp file is loaded as an EmbeddedResource, there are other options as well,
please check them in the ShapefileLayer topic.
 
This is the result:

SDK Browser and QSF applications contain different examples that show RadMap's main features.
You can find the applications in the Examples and QSF folders of your local Telerik UI for Xamarin
installation.
 

1287
Telerik UI for Xamarin

See Also
 ShapefileLayer
 Selection
 Styling

1288
Telerik UI for Xamarin

Key Features
The purpose of this help article is to show you the key features of the RadMap control.

Interaction Modes
RadMap provides pan and zoom functionality that will help you interact with the view and inspect
your data. The Map control handles the gestures drag, pinch-open and pinch-close which
respectively cause panning, zooming-in and zooming-out of the associated plot area.

You could configure which gesture manipulations the user can do with the map through the enum
InteractionMode property. InteractionMode can receive the following values:

 None: No interaction is allowed;


 Pan;
 Zoom;
 PanAndZoom (default value).

Here is a quick snippet how InteractionMode could be applied:

XAML
<telerikMap:RadMap x:Name="map" InteractionMode="Zoom">
<telerikMap:RadMap.Layers>
<telerikMap:ShapefileLayer>
<telerikMap:ShapefileLayer.Reader>
<telerikMap:MapShapeReader x:Name="reader"/>
</telerikMap:ShapefileLayer.Reader>
</telerikMap:ShapefileLayer>
</telerikMap:RadMap.Layers>
</telerikMap:RadMap>
 

where the Source of the MapShapeReader should be defined as well:

C#
var assembly = this.GetType().Assembly;
var source = MapSource.FromResource("SDKBrowser.Examples.MapControl.world.shp",
assembly);
this.reader.Source = source;
 

In the example the .shp file is loaded as an EmbeddedResource, there are other options as well,
please check them in the ShapefileLayer topic.
 

Zoom Level Support

1289
Telerik UI for Xamarin

RadMap exposes properties for applying min and max zoom values.

 MaxZoomLevel(double): Defines the maximum magnification factor at which content could


be maximized. The default value is 20.0
 MinZoomLevel(double): Defines the minimum magnification factor at which content could be
minimized. The default value is 1.0

You can check the current magnification through the readonly ZoomLevel property.

XAML
<telerikMap:RadMap x:Name="map" MinZoomLevel="2" MaxZoomLevel="5">
<telerikMap:RadMap.Layers>
<telerikMap:ShapefileLayer>
<telerikMap:ShapefileLayer.Reader>
<telerikMap:MapShapeReader x:Name="reader"/>
</telerikMap:ShapefileLayer.Reader>
</telerikMap:ShapefileLayer>
</telerikMap:RadMap.Layers>
</telerikMap:RadMap>
 

In addition, you can use the method below to set the provided zoom value as the current zoom level
of the map:

 void ZoomToLevel(double zoomLevel);

Layers
RadMap can display rich spatial data from ESRI shapefiles. Each shapefile should be loaded and
configured through a ShapefileLayer instance added to the Layers collection of the control. By
adding more ShapefileLayers you can visualize different types of elements on the same map. For
detailed information on the matter go to Layers Overview topic.

Setting the View


If you would like to show a specific area from the map, you can use SetView method as described
below:

 SetView(LocationRect locationRect) – Sets the provided location as the current view of the
map.

LocationRect class is a special type from the Telerik.XamarinForms.ShapefileReader namespace,


which describes a rectangle region through the locations of the northwest and southeast points.

For more details on how points are positioned in the geographic coordinate system, check Layers
Overview topic.
 
Here is an example how you could utilize SetView method (in the example the used latitude and
longitude values are chosen to form a region around Italy):

1290
Telerik UI for Xamarin

C#
var northWest = new Location(45.7, 4.8);
var southEast = new Location(37.7, 20.08);
var view = new LocationRect(northWest, southEast);
this.map.SetView(view);
 

Hardware Acceleration
RadMap is rendered via the SkiaSharp library and uses by default the hardware-accelerated
SKGLView class for its drawing. You could easily replace it with the SKCanvasView by setting
EnableHardwareAcceleration to False.

A sample Key Features example can be found in the Accordion/Features folder of the SDK Samples
Browser application.
 

See Also
 Layers
 Selection
 Styling

1291
Telerik UI for Xamarin

Overview
The RadMap control visualizes spatial data using layered architecture. It could display spatial data
points (e.g. location of cities), polylines (e.g. road connections), or polygons (shape of countries or
continents) in a geographic coordinate system. In this coordinate system, a point on the surface of
the earth is defined using latitudes and longitudes.

 Latitude: This is measured as the angle from the equatorial plane to the line drawn from the
center of the earth to the point on the surface. Usually latitude values range from 90° (toward
the North Pole and suffixed with "N") to -90° (towards the South Pole and suffixed with "S").
 Longitude: This is measured on the equatorial plane and is defined as the angle between the
line drawn from the center of the earth to the point and the line drawn from center of the
earth to the prime meridian. Usually the longitude values range from 180° (to the east of
prime meridian and suffixed with "E") to -180° (to the west of prime meridian and suffixed
with "W").

The position of the spatial data is described by the Location structure, that has the following
properties:

 Latitude (double): Gets the latitude value of the location. The value should be between -90°
and 90°.
 Longitude (double): Gets the longitude value of the location. The value should be between
-180° and 180°.

The RadMap control works with layers of type ShapefileLayer that use ESRI shapefiles as a data
source. For detailed information on how shapefiles could be utilized go to ShapefileLayer topic.

See Also

1292
Telerik UI for Xamarin

 ShapefileLayer

1293
Telerik UI for Xamarin

ShapefileLayer
ShapefileLayer class provides a way to load an ESRI shapefile into the Map and visualize the
shapes defined in it. You would need to create a ShapefileLayer for each shapefile and add it to the
Layers collection of RadMap.

Reading a shapefile
ShapefileLayer provides a Reader property used to read the data from the defined shapefile. The
Reader is of type Telerik.XamarinForms.Map.MapShapeReader and has two important properties
you need to apply in order to properly load and visualize your shapes:

 Source (of type Telerik.XamarinForms.Map.MapSource) : Gets or sets the MapSource that


points to the .shp file to read data from.
 DataSource (of type Telerik.XamarinForms.Map.MapSource) : Gets or sets the MapSource
that points to the *dbf file, containing the data(or attributes) for each shape within the shape
file.

The above used MapSource class provides a few useful static methods that will help load the
shapefile:

 FromResource(string resource, Assembly sourceAssembly) / FromResource(string resource,


Type resolvingType): Two overrides you can choose from to easily create MapSource from a
provided embedded resource.
 FromStream(Stream stream): returns a MapSource from a passed stream.
 FromFile(string file): Returns MapSource from a passed string the represents a specific file
path.

In addition, MapShapeReader provides a read-only Shapes property that can be used to get a list of
all the shapes that are read from the Source.

Get Best View


ShapefileLayer provides a way to visualize the shapes in such a way that the best view of the layer
is achieved. The approach is implemented through the GetBestView method:

 LocationRect GetBestView() - Gets location rectangle which represents best view for the
layer.

First, LocationRect class is a special type from the Telerik.XamarinForms.ShapefileReader


namespace which describes a rectangle region through the locations of the northwest to the
southeast points.

For more details on how points are positioned in the geographic coordinate system, check Layers
Overview topic.
 
So, through GetBestView method the map will calculate that region that encompasses all the shapes

1294
Telerik UI for Xamarin

as well as apply proper zoom level, so that the best view is achieved. After that, you could pass the
result directly to the SetView method of the Map instance like this:

C#
var bestView = this.mapShapeLayer.GetBestView();
this.map.SetView(bestView);
 

Labels
You can add a label for each shape in a ShapefileLayer by setting the ShapeLabelAttributeName
property to an attribute from the *.dbf file specified in the DataSource property of the layer.

Check below a quick example:

XAML
<telerikMap:RadMap x:Name="map">
<telerikMap:RadMap.Layers>
<telerikMap:ShapefileLayer x:Name="mapShapeLayer"
LabelAttributeName="CNTRY_NAME">
<telerikMap:ShapefileLayer.Reader>
<telerikMap:MapShapeReader x:Name="reader"/>
</telerikMap:ShapefileLayer.Reader>
</telerikMap:ShapefileLayer>
</telerikMap:RadMap.Layers>
</telerikMap:RadMap>
 

where the Source and the DataSource of the MapShapeReader should be defined to a .shp and .dbf
files, respectively:

C#
var assembly = this.GetType().Assembly;
var source = MapSource.FromResource("SDKBrowser.Examples.MapControl.world.shp",
assembly);
var dataSource = MapSource.FromResource("SDKBrowser.Examples.MapControl.world.dbf",
assembly);
this.reader.Source = source;
this.reader.DataSource = dataSource;
 

1295
Telerik UI for Xamarin

Selection
RadMap supports single and multiple selection of shapes to help you draw attention on specific
areas. You would need to set SelectionMode property of the ShapefileLayer to enable the selection.

SelectionMode could receive the following values:

 None;
 Single;
 Multiple.

Read the Selection topic for more details regarding this feature.

Styling
RadMap provides the option to apply various Fill and Stroke colors to the shapes to make the map
consistent with the design of the app. For more details check Styling article.

See Also
 Selection
 Styling

1296
Telerik UI for Xamarin

Selection
RadMap control exposes selection feature. It allows users to select one or many shapes out of the
source applied by each ShapefileLayer. This feature provides both visual and programmatic
feedback for the actions of the user.

The following members of the ShapefileLayer class are related to the selection:

 SelectionMode: Enum property which indicates what will be the selection. It could receive the
following values:
 None;
 Single;
 Multiple.
 SelectedShape (of type IShape): Defines the currently selected shape instance. When
multiple selection is enabled, this value is set to the first selected shape.
 SelectedShapes (of type ObservableCollection<IShape>): Reads the collection with the
currently selected shapes. When the selection is single only one shape could be selected –
thus the collection will have count = 1.
 SelectedShapeStyle (of type MapShapeStyle): Defines the way selected shape look through
the provided StrokeWidth, StrokeColor and FillColor properties. For more details on the
MapShapeStyle usage go to Shapes Styling topic.

The next snippet shows how SelectionMode is applied:

XAML
<telerikMap:RadMap x:Name="map">
<telerikMap:RadMap.Layers>
<telerikMap:ShapefileLayer x:Name="mapShapeLayer" SelectionMode="Multiple">
<telerikMap:ShapefileLayer.Reader>
<telerikMap:MapShapeReader x:Name="reader"/>
</telerikMap:ShapefileLayer.Reader>
</telerikMap:ShapefileLayer>
</telerikMap:RadMap.Layers>
</telerikMap:RadMap>
 

where the Source and the DataSource of the MapShapeReader should be set to a .shp and .dbf
files, respectively:

C#
var assembly = this.GetType().Assembly;
var source = MapSource.FromResource("SDKBrowser.Examples.MapControl.world.shp",
assembly);
var dataSource = MapSource.FromResource("SDKBrowser.Examples.MapControl.world.dbf",
assembly);
this.reader.Source = source;
this.reader.DataSource = dataSource;
 

1297
Telerik UI for Xamarin

Check below how RadMap with a few selected shapes will look like:

The snippet below demonstrates how you could select a certain shape programmatically. In the
example the used ESRI file contains the world map, so the shape that is selected is a country. The
example uses the Shapes property of the Map to traverse through all the available shapes.

Let's select/unselect "France", for example, on clicking buttons:

XAML
<Button Text="Select France" Clicked="SelectFranceClicked" />
<Button Text="Deselect France" Clicked="DeselectFranceClicked" />
 

And here are the event handlers:

C#
private void SelectFranceClicked(object sender, EventArgs e)
{
var shape = this.GetItemFromCountryName("France");
if (shape != null)
{
this.mapShapeLayer.SelectedShapes.Add(shape);
}
}

private void DeselectFranceClicked(object sender, EventArgs e)


{
var shape = this.GetItemFromCountryName("France");

1298
Telerik UI for Xamarin

if (shape != null && this.mapShapeLayer.SelectedShapes.Contains(shape))


{
this.mapShapeLayer.SelectedShapes.Remove(shape);
}
}

private IShape GetItemFromCountryName(string countryName)


{
foreach (var shape in this.reader.Shapes)
{
var name = shape.GetAttribute("CNTRY_NAME").ToString();
if (name == countryName)
{
return shape;
}
}
return null;
}
 

Here is the result:

A sample Programmatic Selection example can be found in the Map/Selection folder of the SDK
Samples Browser application.
 

See Also
 ShapefileLayer

1299
Telerik UI for Xamarin

 Shapes Styling

1300
Telerik UI for Xamarin

Commands
RadMap provides the following commands of type ICommand which handle the zoom level of the
visualized shapes:

 ZoomInCommand
 ZoomOutCommand

You can manually call these commands, for example on button click action, to zoom-in or zoom-out
respectively, the shapes displayed in RadMap.

Following is a quick example on how the commands of the Map control can be called from external
UI:

Let's have the following Map definition:

XAML
<telerikMap:RadMap x:Name="map" MinZoomLevel="2" MaxZoomLevel="5">
<telerikMap:RadMap.Layers>
<telerikMap:ShapefileLayer>
<telerikMap:ShapefileLayer.Reader>
<telerikMap:MapShapeReader x:Name="reader"/>
</telerikMap:ShapefileLayer.Reader>
</telerikMap:ShapefileLayer>
</telerikMap:RadMap.Layers>
</telerikMap:RadMap>
 

where the Source of the MapShapeReader is defined like this:

C#
var assembly = this.GetType().Assembly;
var source = MapSource.FromResource("SDKBrowser.Examples.MapControl.world.shp",
assembly);
this.reader.Source = source;
 

Lastly, add two buttons that will execute the Map commands - their Command property is bound to
the corresponding Zoom command of the Map instance:

XAML
<Button Text="Zoom In" Command="{Binding Source={x:Reference map},
Path=ZoomInCommand}"/>
<Button Text="Zoom Out" Command="{Binding Source={x:Reference map},
Path=ZoomOutCommand}"/>
 

See Also

1301
Telerik UI for Xamarin

 Key Features

1302
Telerik UI for Xamarin

Label Styling
The ShapefileLayer has a ShapeLabelStyle property that is of MapShapeLabelStyle type and
defines the style of the labels.

MapShapeLabelStyle provides the following properties you could use to customize the way labels on
the map will look:

 TextColor
 FontSize
 FontFamily
 FontAttributes

The snippet below shows how ShapeLabelStyle property can be applied:

XAML
<telerikMap:RadMap x:Name="map">
<telerikMap:RadMap.Layers>
<telerikMap:ShapefileLayer LabelAttributeName="CNTRY_NAME">
<telerikMap:ShapefileLayer.Reader>
<telerikMap:MapShapeReader x:Name="reader"/>
</telerikMap:ShapefileLayer.Reader>
<telerikMap:ShapefileLayer.ShapeLabelStyle>
<telerikMap:MapShapeLabelStyle TextColor="DarkRed"
FontAttributes="Bold"
FontSize="12"
FontFamily="Arial"/>
</telerikMap:ShapefileLayer.ShapeLabelStyle>
</telerikMap:ShapefileLayer>
</telerikMap:RadMap.Layers>
</telerikMap:RadMap>
 

where the Source and the DataSource of the MapShapeReader should be set to a .shp and .dbf
files, respectively:

C#
var assembly = this.GetType().Assembly;
var source = MapSource.FromResource("SDKBrowser.Examples.MapControl.world.shp",
assembly);
var dataSource = MapSource.FromResource("SDKBrowser.Examples.MapControl.world.dbf",
assembly);
this.reader.Source = source;
this.reader.DataSource = dataSource;
 

Here is the result:

1303
Telerik UI for Xamarin

A sample Labels Styling example can be found in the Map/Features folder of the SDK Samples
Browser application.
 

See Also
 ShapefileLayer
 Styling

1304
Telerik UI for Xamarin

Shapes Styling
The ShapefileLayer exposes ShapeStyle/SelectedShapeStyle as well as a ShapeStyleSelector
properties that will help achieve the desired look & feel of the shapes on the map.

Shapes Styles
ShapeStyle and SelectedShapeStyle properties are of type MapShapeStyle which provides the
following styling options for the shapes:

 StrokeWidth;
 StrokeColor;
 FillColor.

The snippet below shows how ShapeStyle property can be applied:

XAML
<telerikMap:RadMap x:Name="map">
<telerikMap:RadMap.Layers>
<telerikMap:ShapefileLayer>
<telerikMap:ShapefileLayer.Reader>
<telerikMap:MapShapeReader x:Name="reader"/>
</telerikMap:ShapefileLayer.Reader>
<telerikMap:ShapefileLayer.ShapeStyle>
<telerikMap:MapShapeStyle FillColor="White"
StrokeColor="#7BD5FB"/>
</telerikMap:ShapefileLayer.ShapeStyle>
</telerikMap:ShapefileLayer>
</telerikMap:RadMap.Layers>
</telerikMap:RadMap>
 

Here is the result:

1305
Telerik UI for Xamarin

where the Source and the DataSource of the MapShapeReader should be set to a .shp and .dbf
files, respectively:

C#
var assembly = this.GetType().Assembly;
var source = MapSource.FromResource("SDKBrowser.Examples.MapControl.world.shp",
assembly);
var dataSource = MapSource.FromResource("SDKBrowser.Examples.MapControl.world.dbf",
assembly);
this.reader.Source = source;
this.reader.DataSource = dataSource;
 

Shapes StyleSelector
Through the ShapeStyleSelector property of the ShapefileLayer you could implement conditional
styling.

The example below shows how to apply different styles to shapes according to certain property
value of each shape.

First, create the selector class that should inherit from MapShapeStyleSelector:

C#
public class PopulationShapeStyleSelector : MapShapeStyleSelector
{
public MapShapeStyle HighPopulationShapeStyle { get; set; }
public MapShapeStyle MediumPopulationShapeStyle { get; set; }

1306
Telerik UI for Xamarin

public MapShapeStyle LowPopulationShapeStyle { get; set; }

public override MapShapeStyle SelectStyle(object shape, BindableObject container)


{
var attributesShape = shape as IShape;
if (attributesShape != null)
{
var populationText = attributesShape.GetAttribute("POP_CNTRY").ToString();
int population;
if (int.TryParse(populationText, out population))
{
if (population > 20000000)
{
return this.HighPopulationShapeStyle;
}
else if (population < 1000000)
{
return this.LowPopulationShapeStyle;
}

return this.MediumPopulationShapeStyle;
}
}

return null;
}
}
 

Then, define the selector with the Styles as a resource inside a ResourceDictionary:

XAML
<ResourceDictionary>
<local:PopulationShapeStyleSelector x:Key="PopulationShapeStyleSelector">
<local:PopulationShapeStyleSelector.HighPopulationShapeStyle>
<telerikMap:MapShapeStyle FillColor="DarkGreen" StrokeColor="LightGray"/>
</local:PopulationShapeStyleSelector.HighPopulationShapeStyle>
<local:PopulationShapeStyleSelector.MediumPopulationShapeStyle>
<telerikMap:MapShapeStyle FillColor="Green" StrokeColor="LightGray"/>
</local:PopulationShapeStyleSelector.MediumPopulationShapeStyle>
<local:PopulationShapeStyleSelector.LowPopulationShapeStyle>
<telerikMap:MapShapeStyle FillColor="LightGreen" StrokeColor="LightGray"/>
</local:PopulationShapeStyleSelector.LowPopulationShapeStyle>
</local:PopulationShapeStyleSelector>
</ResourceDictionary>
 

Lastly, add the definition of the RadMap control with the PopulationShapeStyleSelector applied;

XAML
<telerikMap:RadMap x:Name="map">
<telerikMap:RadMap.Layers>

1307
Telerik UI for Xamarin

<telerikMap:ShapefileLayer ShapeStyleSelector="{StaticResource
PopulationShapeStyleSelector}">
<telerikMap:ShapefileLayer.Reader>
<telerikMap:MapShapeReader x:Name="reader"/>
</telerikMap:ShapefileLayer.Reader>
</telerikMap:ShapefileLayer>
</telerikMap:RadMap.Layers>
</telerikMap:RadMap>
 

Check the result in the screenshot below:

Sample Shapes Styling examples can be found in the Map/Features folder of the SDK Samples
Browser application.
 

See Also
 ShapefileLayer
 Labels Styling

1308
Telerik UI for Xamarin

Overview
RadMaskedInput for Xamarin allows to control the data input within your Xamarin Forms application.
It enhances the functionality of the Entry control by adding input validation and custom masks which
serve as a footprint for the user.

Figure 1: RadMaskedInput Overview

Key features
 Validation: RadMaskedInput control uses a mask to distinguish between proper and
improper user input. Validation mechanism can be based on custom regular expressions or
built-in tokens. Read more about this in the Tokens Validation and RegEx Validation topics.
 Mask Tokens: You can choose from a set of predefined tokens in order to restrict user’s
input. For more details on the available tokens go to Tokens Validation topic.
 Commands: MaskedInput allows you to attach commands that will be executed when certain
actions, such as ApplyMaskStarted and ApplyMaskFinished occur. For detailed information
on the matter go to Commands article.
 Customizable Validation UI: With RadMaskedInput you can easily modify the appearance of
the input-related errors, please refer to the Validation UI topic for more details.
 Keyboard support: You can specify the virtual keyboard to be used with RadMaskedInput
considering the expected input.

See Also
 Getting Started

1309
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadMaskedInput control in your
application and will provide information regarding the most important properties of the control.

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadMaskedInput control you have to install the
Telerik.UI.for.Xamarin.Input nuget package. This nuget will automatically refer the
Telerik.UI.for.Xamarin.Primitives, Telerik.UI.for.Xamarin.Common, and
Telerik.UI.for.Xamarin.DataControls nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadMaskedInput component:

Platform Assemblies
Portable Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll
Android Telerik.Xamarin.Android.Common.dll
Telerik.Xamarin.Android.Data.dll
Telerik.Xamarin.Android.Input.dll
Telerik.Xamarin.Android.List.dll
Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll
UWP Telerik.Core.dll
Telerik.Data.dll
Telerik.UI.Xaml.Controls.Data.UWP.dll

1310
Telerik UI for Xamarin

Telerik.UI.Xaml.Input.UWP.dll
Telerik.UI.Xaml.Primitives.UWP.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll

3. Adding RadMaskedInput control


If your app is setup, you are ready to add a RadMaskedInput control.

The RadMaskedInput control exposes a MaskType property which can be either "Text" or "Regex". It
controls the type of the validation. If you choose to use a Text type, the Mask of the control should
be set by utilizing the Mask Tokens. In case you decide to use a Regex for validating the input, you
should set such to the Mask property as demonstrated in the RegEx Vaidation topic.

Here is an example how to add RadMaskedInput control with Text MaskType:

XAML
<telerikInput:RadMaskedInput x:Name="maskedInput"
WatermarkText="Watermark"
Mask="(CC) 00"
MaskType="Text"/>
 

In addition to this you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

C#
using Telerik.XamarinForms.Input;
 

This is the result:

1311
Telerik UI for Xamarin

SDK Browser and QSF applications contain different examples that show RadMaskedInput's main
features. You can find the applications in the Examples and QSF folders of your local Telerik UI for
Xamarin installation.
 

See Also
 Tokens
 RegEx
 Validation
 Commands
 Events
 Theming and Style

1312
Telerik UI for Xamarin

Key Features
The purpose of this help article is to show you the key features of the RadMaskedInput control.

Mask-related properties:
 MaskType(of type Telerik.XamarinForms.Input.MaskedInput.MaskType): Defines the
expected validation type of the Mask. Here are the two options:
 Text (for Tokens validation)
 Regex (for RegEx validation)
 Mask(string): Specifies a string defining the mask. In case of using Text validation, you
should use the available Mask Tokens. Otherwise, a regular expression should be set.
 IsMaskFull(bool): Gets a value indicating if all required symbols are filled. The default value
is true. Can be false only when required symbols tokens are present in the mask.
(ReadOnly)
 InputValue(string): Defines the input value.
 IsInputAccepted(bool): Gets a value indicating whether the input matches the
mask.(ReadOnly)
 Keyboard (Xamarin.Forms.Keyboard): Defines the type of the keyboard that will be
visualized by the device.

Appearance-related properties:
 WatermarkText(string): Specifies the text used as watermark.
 WatermarkTextColor(Color): Specifies the color of the text of the watermark.
 DisplayedText(string): Gets the displayed text.(ReadOnly)
 DisplayedTextColor(Color): Defines the color of the displayed text.
 DisplayedTextFont(string): Defines the font of the displayed text.
 DisplayedTextFontSize(double): Defines the size of the font used for the displayed text.
 BorderStyle(of type Telerik.XamarinForms.Input.BorderStyle) Gets or sets a
Telerik.XamarinForms.Input.RadMaskedInput.BorderStyle defining the look of the border
around the entry. The default value is defined by the OS.
 Placeholder(char): Specifies the symbol that will be used to mark an empty position. The
default value is '_'.

Validation-related properties:
 InvalidInputErrorText(string): Defines the text that is shown as error message on invalid
input.
 ErrorColor(Color): Specifies the color of the error text.
 ErrorFontSize(double): Specifies the font size of the error text.
 RejectedSymbolErrorText(string): Defines the error text when a symbol was rejected.
 IsErrorTextVisible(bool): Gets a value indicating whether the error text is visible. (ReadOnly)

SDK Browser and QSF applications contain different examples that show RadMaskedInput's main
features. You can find the applications in the Examples and QSF folders of your local Telerik UI for

1313
Telerik UI for Xamarin

Xamarin installation.
 

See Also
 Tokens
 RegEx
 Validation
 Commands
 Events
 Theming and Style

1314
Telerik UI for Xamarin

Control Template
RadMaskedInput's visual appearance is defined through a Control Template. In order to customize
the way the MaskedInput looks, you would need to take the default ControlTemplate and modify it.

This topic gives an overview of the ControlTemplate of the MaskedInput control, so you can copy it
to your app and make changes.

The original ControlTemplate

The XAML defined below relies on the following namespace to be set:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

XAML
<ResourceDictionary>
<ControlTemplate x:Key="MaskedInput_ControlTemplate">
<Grid BackgroundColor="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<telerikInput:MaskedInputElement x:Name="InputElement"
HorizontalTextAlignment="Start"
BackgroundColor="Transparent"
Mask="{TemplateBinding Mask}"
MaskType="{TemplateBinding MaskType}"
Placeholder="{TemplateBinding Placeholder}"
BorderStyle="{TemplateBinding BorderStyle}"
WatermarkText="{TemplateBinding WatermarkText}"
InputValue="{TemplateBinding InputValue, Mode=TwoWay}"
DisplayedTextFont="{TemplateBinding DisplayedTextFont}"
WatermarkTextColor="{TemplateBinding WatermarkTextColor}"
DisplayedTextColor="{TemplateBinding DisplayedTextColor}"
DisplayedTextFontSize="{TemplateBinding DisplayedTextFontSize}"/>
<Label FontSize="{TemplateBinding ErrorFontSize}"
BackgroundColor="Transparent"
Grid.Row="1">
<Label.Triggers>
<DataTrigger TargetType="Label"
Binding="{TemplateBinding IsMaskFull}"
Value="False">
<Setter Property="Text" Value="{TemplateBinding InvalidInputErrorText}" />
</DataTrigger>
<DataTrigger TargetType="Label"
Binding="{TemplateBinding IsMaskFull}"

1315
Telerik UI for Xamarin

Value="True">
<Setter Property="Text" Value="{TemplateBinding RejectedSymbolErrorText}" />
</DataTrigger>
<DataTrigger TargetType="Label"
Binding="{TemplateBinding IsErrorTextVisible}"
Value="True">
<Setter Property="TextColor" Value="{TemplateBinding ErrorColor}" />
</DataTrigger>
<DataTrigger TargetType="Label"
Binding="{TemplateBinding IsErrorTextVisible}"
Value="False">
<Setter Property="TextColor" Value="Transparent" />
</DataTrigger>
</Label.Triggers>
</Label>
</Grid>
</ControlTemplate>
</ResourceDictionary>
 

Finally, use the custom ControlTemplate as a StaticResource on any instance of RadMaskedInput:

XAML
<StackLayout>
<telerikInput:RadMaskedInput x:Name="maskedInput"
ControlTemplate="{StaticResource MaskedInput_ControlTemplate}"/>

</StackLayout>
 

See Also
 RadMaskedInput Tokens
 RadMaskedInput Events
 RadMaskedInput Commands

1316
Telerik UI for Xamarin

Mask Tokens
When the MaskType of the RadMaskedInput control is set to Text, you can utilize the available Mask
Tokens to restrict the user input. Below you can find a list of the available tokens and their purpose:

Token Corresponding Regex Usage


0 "[0-9]" a single digit
9 "[0-9]{1}" a single digit(required)
L "[a-zA-Z]" a single letter
? "[a-zA-Z]{1}" a single letter(required)
& "\S" all symbols without space
C "." all symbols
A "[0-9a-zA-Z]" all without special symbols
and space
a "[0-9a-zA-Z ]" all without special symbols

Mask Tokens Example


XAML
<telerikInput:RadMaskedInput x:Name="maskedInput"
WatermarkText="Watermark"
Mask="(CC) 00"
MaskType="Text"/>
 

See Also
 Getting Started
 Events
 Commands

1317
Telerik UI for Xamarin

Validation through custom Regular


Expressions
One of the main features that RadMaskedInput supports is validation through a custom regular
expression. You can define a input pattern of your choice and set it to the Mask property of the
control. In order to use the validation through regular expressions, you should set the MaskType to
Regex.

Below you can find a list of the available Regex and their usage:

Corresponding Regex Usage


"[0-9]" a single digit
"[0-9]{1}" a single digit(required)
"[a-zA-Z]" a single letter
"[a-zA-Z]{1}" a single letter(required)
"\S" all symbols without space
"." all symbols
"[0-9a-zA-Z]" all without special symbols and space
"[0-9a-zA-Z ]" all without special symbols

Custom Regex Example


MaskedInput with custom RegEx validation. The Keyboard type is Numeric.

XAML
<telerikInput:RadMaskedInput MaskType="Regex"
InvalidInputErrorText="Invalid date format!"
ErrorColor="Red"
WatermarkText="Enter Date"
Keyboard="Numeric"
Mask="^[0-9]{4}\/(30|31|[0-2]{0,1}[0-9]{1})\/(10|11|12|[0-9]{1})$"/>
 

Mask Extensions
The static class Telerik.XamarinForms.Input.MaskedInput.MaskExtensions contains two static
regular expressions which you can directly use for validation when the MaskType is Regex:

 IP: "^(([1-9]?\d|1\d\d|2[0-5][0-5]|2[0-4]\d)\.){3}([1-9]?\d|1\d\d|2[0-5][0-5]|2[0-4]\d)$"
 Email:

1318
Telerik UI for Xamarin

"^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,
3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$"

Built-in Regex Example


Validation using the MaskExtensions class. The MaskedExtention type is Email. Note that the
Keyboard type is set to Email.

XAML
<telerikInput:RadMaskedInput MaskType="Regex"
InvalidInputErrorText="Invalid E-Mail format!"
ErrorColor="Red"
Keyboard="Email"
WatermarkText="Enter E-mail"
Mask="{x:Static extensions:MaskExtensions.Email}"/>
 

Where the following namespace is used:

XAML
xmlns:extensions="clr-namespace:Telerik.XamarinForms.Input.MaskedInput;assembly=Teleri
k.XamarinForms.Input"
 

See Also
 Getting Started
 Events
 Commands

1319
Telerik UI for Xamarin

Validation
The RadMaskedInput has a built-in validation mechanism, and you can utilize the following
properties to modify the appearance when an input-related error is observed:

 InvalidInputErrorText(string): Defines the text that is shown as an error message on invalid


input.
 RejectedSymbolErrorText(string): Defines the error text when a symbol was rejected.
 ErrorColor(Color): Defines the color of the error text.
 ErrorFontSize(double): Specifies the font size of the error text.

The ErrorColor and ErrorFontSize will affect the error message from both the InvalidInputErrorText
and the RejectedSymbolErrorText properties.
 

InvalidInputErrorText
The message from this property will appear when you have a required symbol in the input which is
not filled in(the '9' or '?' tokens are in use). Your users will be notified of the need to fill in the required
symbol by noticing the custom message you have set.

Here is an example of how to trigger the error message.

The RadMaskedInput definition:

XAML
<telerikInput:RadMaskedInput x:Name="maskedInput"
RejectedSymbolErrorText="Rejected Symbol"
InvalidInputErrorText="Invalid Input"
ErrorColor="Red"
ErrorFontSize="22"
Mask="(CC) 09"
MaskType="Text"/>
 

The way the mask is set, it is mandatory to fill in a digit in the last position. In case you leave it empty
and move the focus from the field. Figure 1 shows the appearance of the message.

Figure 1: Invalid input error message

1320
Telerik UI for Xamarin

RejectedSymbolErrorText
The string set to the RejectedSymbolErrorText will be observed in case the input typed into the
RadMaskedInput is rejected. In the case of the previously declared mask, this will happen if you try
to type in a letter in the last symbol. The effect is observed in Figure 2.

Figure 2: Rejected symbol error message

1321
Telerik UI for Xamarin

You can find a working demo labeled Validation in the MaskedInput/Features folder of the SDK
Samples Browser application.
 

See Also
 RadMaskedInput Tokens
 RadMaskedInput Events
 RadMaskedInput Commands

1322
Telerik UI for Xamarin

Commands
Apart from utilizing the Events that the control exposes for modeling the user input, you can also
achieve this by utilizing the commands mechanism which is the preferred approach in a MVVM
setup.

When using commands, you should inherit the MaskedInputCommandBase class and explicitly set
the ID of your command to one of the available within the MaskedInputCommandID enum.
 

ApplyMaskStarted Command
In case you would like to add some logic through a command when applying the mask has started,
you need to set the ID of your command to MaskedInputcommandId.ApplyMaskStarted. Eventually,
the parameter that you will receive in the Execute method will be of type
ApplyMaskStartedCommandContext. It exposes the following properties, which are identical to those
of the ApplyMaskStartedEventArgs:

 NewDisplayedText(string): The updated text of the MaskedInput control after the symbol is
added.
 NewInputValue(string): The new InputValue(the whole string value that the mask contains).
 OldDisplayedText(string): The text of the MaskedInput before the symbol is added.
 OldInputValue(string): The previous input value. Returns empty string if such is not available.

Example
Here is an example of a command that is invoked on ApplyMaskStarted:

C#
public class CustomBeforeTextMaskedCommand : MaskedInputCommandBase
{
public CustomBeforeTextMaskedCommand()
{
this.Id = MaskedInputCommandId.ApplyMaskStarted;
}

public override void Execute(object parameter)


{
var context = parameter as ApplyMaskStartedCommandContext;
context.NewDisplayedText = context.NewDisplayedText.ToUpper();
}
}
 

You should also make sure that the command is added in the Commands collection of the
RadMaskedInput instance:

C#

1323
Telerik UI for Xamarin

this.input.Commands.Add(new CustomBeforeTextMaskedCommand());
 

and the RadMaskedInput definition:

XAML
<StackLayout Margin="16">
<Label Text="The default C token allows x to be input. Using custom command we
reject x from input."/>
<telerikInput:RadMaskedInput x:Name="input" Mask="CC (00)" Placeholder="#" />
</StackLayout>
 

ApplyMaskFinished Command
Similar to the ApplyMaskStarted Command, you can create a command that is executed when
applying the mask has finished. In this case, you need to set the ID of your command to
MaskedInputcommandId.ApplyMaskFinished The parameter that you will receive in the Execute
method will then be of type ApplyMaskFinishedCommandContext. Identically to
ApplyMaskFinishedEventArgs, it has the following properties:

 CaretPosition(int): The position of the caret after the symbol was typed. It can be controlled
to manually set the caret position.
 IsAccepted(bool): Boolean property that indicates whether the symbol was accepted by the
mask. It can be set to manually control the action.
 NewDisplayedText(string): The updated text of the MaskedInput control after the symbol is
added.
 NewInputValue(string): The new InputValue(the whole string value that the mask contains).
 OldDisplayedText(string): The text of the MaskedInput before the symbol is added.
 OldInputValue(string): The previous input value. Returns empty string if such is not available.

Example
Here is an example of a command that is invoked on ApplyMaskFinished:

C#
public class CustomAfterTextMaskedCommand : MaskedInputCommandBase
{
public CustomAfterTextMaskedCommand()
{
this.Id = MaskedInputCommandId.ApplyMaskFinished;
}

private int lastValidCaretPosition = 0;


public override void Execute(object parameter)
{
var context = parameter as ApplyMaskFinishedCommandContext;
if (context.NewDisplayedText.Contains("X"))
{
context.IsAccepted = false;

1324
Telerik UI for Xamarin

context.CaretPosition = lastValidCaretPosition;
}
else
{
lastValidCaretPosition = context.CaretPosition;
}
}
}
 

Once again, make sure that the command is added to the Commands collection of the
RadMaskedInput control:

C#
this.input.Commands.Add(new CustomAfterTextMaskedCommand());
 

and the RadMaskedInput definition:

XAML
<StackLayout Margin="16">
<Label Text="The default C token allows x to be input. Using custom command we
reject x from input."/>
<telerikInput:RadMaskedInput x:Name="input" Mask="CC (00)" Placeholder="#" />
</StackLayout>
 

You can find a working demo in the MaskedInput/Features/Commands folder of the SDK Samples
Browser application.
 

See Also
 Getting Started
 Tokens
 Events

1325
Telerik UI for Xamarin

Events
The RadMaskedInput exposes the following events which can be utilized for additional control of the
user's input:

 ApplyMaskStarted: Occurs when you type a symbol, before the mask is applied.
 ApplyMaskFinished: Occurs after you type a symbol, when the mask is already applied.

ApplyMaskStarted
The event occurs when you type in a symbol in the RadMaskedInput and the mask is about to be
applied. The event arguments are of type ApplyMaskStartedEventArgs and expose following
properties:

 NewDisplayedText(string): The updated text of the MaskedInput control after the symbol is
added.
 NewInputValue(string): The new InputValue(the whole string value that the mask contains).
 OldDisplayedText(string): The text of the MaskedInput before the symbol is added.
 OldInputValue(string): The previous input value. Returns empty string if such is not available.

ApplyMaskFinished
The event occurs when the mask is already applied. The event arguments are of type
ApplyMaskFinishedEventArgs and expose the following properties:

 CaretPosition(int): The position of the caret after the symbol was typed. It can be controlled
to manually set the caret position.
 IsAccepted(bool): Boolean property that indicates whether the symbol was accepted by the
mask. It can be set to manually control the action.
 NewDisplayedText(string): The updated text of the MaskedInput control after the symbol is
added.
 NewInputValue(string): The new InputValue(the whole string value that the mask contains).
 OldDisplayedText(string): The text of the MaskedInput before the symbol is added.
 OldInputValue(string): The previous input value. Returns empty string if such is not available.

Example
ApplyMaskStarted example
Here is a sample definition of the RadMaskedInput control

XAML
<StackLayout Margin="16">
<Label Text="The default C token allows x to be input. Using event we reject x
from input."/>
<telerikInput:RadMaskedInput x:Name="input" Mask="CC (00)" Placeholder="#" />

1326
Telerik UI for Xamarin

</StackLayout>
 

In addition to this you will need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

then attach the event handler to the MaskedInput control:

C#
this.input.ApplyMaskStarted += Input_BeforeTextMasked;
 

and here is a sample implementation of the handler:

C#
private void Input_BeforeTextMasked(object sender,
Telerik.XamarinForms.Input.MaskedInput.ApplyMaskStartedEventArgs e)
{
e.NewDisplayedText = e.NewDisplayedText.ToUpper();
}
 

ApplyMaskFinished example
Here is a sample definition of the RadMaskedInput control

XAML
<StackLayout Margin="16">
<Label Text="The default C token allows x to be input. Using event we reject x
from input."/>
<telerikInput:RadMaskedInput x:Name="input" Mask="CC (00)" Placeholder="#" />
</StackLayout>
 

In addition to this you will need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

then attach the event handler to the MaskedInput control:

C#
this.input.ApplyMaskFinished += Input_AfterTextMasked;
 

1327
Telerik UI for Xamarin

and here is a sample implementation of the handler:

C#
private int lastValidCaretPosition = 0;
private void Input_AfterTextMasked(object sender,
Telerik.XamarinForms.Input.MaskedInput.ApplyMaskFinishedEventArgs e)
{
if (e.NewDisplayedText.Contains("X"))
{
e.IsAccepted = false;
e.CaretPosition = lastValidCaretPosition;
}
else
{
lastValidCaretPosition = e.CaretPosition;
}
}
 

You can find a working demo labeled Events in the MaskedInput/Features folder of the SDK Samples
Browser application.
 

See Also
 Getting Started
 Tokens
 Commands

1328
Telerik UI for Xamarin

Theming and Style


RadMaskedInput exposes the following properties for customizing the appearance of the control:

 WatermarkText(string): Specifies the text used as watermark.


 WatermarkTextColor(Color): Specifies the color of the text of the watermark.
 DisplayedText(string): Gets the displayed text.(ReadOnly)
 DisplayedTextColor(Color): Defines the color of the displayed text.
 DisplayedTextFont(string): Defines the font of the displayed text.
 DisplayedTextFontSize(double): Defines the size of the font used for the displayed text.
 BorderStyle(of type Telerik.XamarinForms.Input.BorderStyle) Gets or sets a
Telerik.XamarinForms.Input.RadMaskedInput.BorderStyle defining the look of the border
around the entry. The default value is defined by the OS.
 Placeholder(char): Specifies the symbol that will be used to mark an empty position. The
default value is '_'.

Example
Here is the RadMaskedInput definition with the properties described above applied:

XAML
<StackLayout>
<telerikInput:RadMaskedInput x:Name="maskedInput"
WatermarkText="Watermark"
WatermarkTextColor="LightPink"
DisplayedTextColor="LightSkyBlue"
DisplayedTextFontSize="20"
Placeholder="*"
Mask="(CC) 00"
MaskType="Text">
<telerikInput:RadMaskedInput.BorderStyle>
<telerikInput:BorderStyle BorderColor="Gray"
BorderThickness="3"
CornerRadius="5"/>
</telerikInput:RadMaskedInput.BorderStyle>
</telerikInput:RadMaskedInput>
</StackLayout>
 

Here is how the control looks when the above properties are applied:

1329
Telerik UI for Xamarin

And here is how the control looks when Theming is applied:

And how the MaskedInput control looks when in edit mode with Keyboard type Telephone.

1330
Telerik UI for Xamarin

You can find a working demo labeled Theme in the MaskedInput/Features folder of the SDK Samples
Browser application.
 

See Also
 RadMaskedInput Tokens
 RadMaskedInput Events
 RadMaskedInput Commands

1331
Telerik UI for Xamarin

Overview
RadNumericInput is a highly customizable input control for numeric data. It allows the user to set/edit
a number using the decrease and increase buttons or directly enter it in the input field.
RadNumericInput also provides consistent look with the rest of the controls from the Telerik UI for
Xamarin suite.

Figure 1: RadNumericInput Overview

Key features
 Minimum/Maximum values: RadNumericInput allows you to restrict the input value through
Min/Max properties, check here for more details.
 Increment Step: You could define the step that will be applied to the input value upon each
decrease/increase. Read more about this here.
 Customizable text of the buttons: You could specify the text of the increase/decrease
buttons, so that it’s applicable to your scenario, read here for more details.

1332
Telerik UI for Xamarin

 Commands: You could use the NumericInput commands to define custom functionality upon
decrease/increase action. Check the Commands topic for more details.

See Also
 Getting Started
 Key Features
 Commands

1333
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadNumericInput control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadNumericInput control

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadNumericInput control you have to install the
Telerik.UI.for.Xamarin.Input nuget package. This nuget will automatically refer the
Telerik.UI.for.Xamarin.Primitives, Telerik.UI.for.Xamarin.Common, and
Telerik.UI.for.Xamarin.DataControls nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadNumericInput component:

Platform Assemblies
Portable Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll
Android Telerik.Xamarin.Android.Common.dll
Telerik.Xamarin.Android.Data.dll
Telerik.Xamarin.Android.Input.dll
Telerik.Xamarin.Android.List.dll
Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll

1334
Telerik UI for Xamarin

UWP Telerik.Core.dll
Telerik.Data.dll
Telerik.UI.Xaml.Controls.Data.UWP.dll
Telerik.UI.Xaml.Input.UWP.dll
Telerik.UI.Xaml.Primitives.UWP.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll

3. Adding RadNumericInput control


You could use one of the following approaches:

Drag the control from the Toolbox.

Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML or C#.

The snippet below shows a simple RadAutoCompleteView definition:

XAML
<telerikInput:RadNumericInput x:Name="numericInput" />
 

C#
var numericInput = new RadNumericInput();
 

In addition to this you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

C#
using Telerik.XamarinForms.Input;
 

Here is the result:

1335
Telerik UI for Xamarin

The SDK Browser and QSF applications contain different examples that show RadNumericInput's
main features. You can find the applications in the Examples and QSF folders of your local Telerik UI
for Xamarin installation.
 

See Also
 Key Features
 Globalization
 Commands

1336
Telerik UI for Xamarin

Key Features
The purpose of this help article is to show you the key features of the RadNumericInput control.

Setting and reading numbers


RadNumericInput exposes a Value property that is used to set and read the number presented by
the control.

The Value property is of type nullable double, which enables the NumericInput control to accept null
value as well.

XAML
<telerikInput:RadNumericInput x:Name="numericInput" Value="12" />
 

Where:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

Restricting the input


RadNumericInput provides Minimum and Maximum properties used to define the allowed range of its
value:

XAML
<telerikInput:RadNumericInput x:Name="numericMinMax" Minimum="0" Maximum="15" />
 

Setting the step for decrement/increment the value


The Step property defines the value step that will be applied to the input value upon each
decrease/increase action. The default step is 1.

XAML
<telerikInput:RadNumericInput x:Name="numericStep" Step="10" />
 

Setting buttons’ text


You could use IncreaseButtonText and DecreaseButtonText properties to specify the text of the

1337
Telerik UI for Xamarin

NumericInput buttons, so that it’s applicable to your scenario.

XAML
<telerikInput:RadNumericInput x:Name="numericBtnText" IncreaseButtonText=" &gt;"
DecreaseButtonText=" &lt;" />
 

Read-only mode
RadNumericInput supports read-only mode in which the end user cannot type into the input field –
updating the value is possible only through the increase/decrease buttons. You could enable the
read-only mode through IsReadOnly property:

XAML
<telerikInput:RadNumericInput x:Name="numericReadOnly" IsReadOnly="True" />
 

Formatting the value


RadNumericInput provides you the option to define the format of its numeric value through the
StringFormat property. You can set it to the desired format which will be applied when the control
loses focus.

XAML
<telerikInput:RadNumericInput x:Name="numericStrFormat" StringFormat="{}{0:C2}" />
 

You can find detailed information about the supported numeric formats here: Standard Numeric
Format Strings.
 

See Also
 Globalization
 Commands

1338
Telerik UI for Xamarin

Control Template
RadNumericInput's visual appearance is defined through a Control Template. In order to customize
the way the NumericInput looks, you would need to take the default ControlTemplate and modify it.

This topic gives an overview of the ControlTemplate of the NumericInput control, so you can copy it
to your app and make changes. The template consists of decrease and increase buttons, the entry
control for entering values as well as the accompanying styles.

The original ControlTemplate

The XAML defined below relies on the following namespaces to be set:

xml
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
xmlns:numericInput="clr-namespace:Telerik.XamarinForms.Input.NumericInput;assembly=Tel
erik.XamarinForms.Input"
xmlns:common="clr-namespace:Telerik.XamarinForms.Common;assembly=Telerik.XamarinForms.
Common"
 

XAML
<ResourceDictionary>
<OnPlatform x:TypeArguments="x:Double" x:Key="Height" Default="32">
<On Platform="Android" Value="45"/>
<On Platform="iOS" Value="36"/>
<On Platform="UWP" Value="32"/>
</OnPlatform>
<OnPlatform x:TypeArguments="x:Double" x:Key="MinimumHeight" Default="33">
<On Platform="Android" Value="28"/>
<On Platform="iOS" Value="28"/>
<On Platform="UWP" Value="33"/>
</OnPlatform>
<OnPlatform x:TypeArguments="x:Double" x:Key="Spacing" Default="10">
<On Platform="Android" Value="10"/>
<On Platform="iOS" Value="10"/>
<On Platform="UWP" Value="10"/>
</OnPlatform>
<GridLength x:Key="ButtonWidth">58</GridLength>

<ControlTemplate x:Key="CustomRadNumericInput_ControlTemplate">
<Grid ColumnSpacing="{StaticResource Spacing}"
HeightRequest="{StaticResource Height}"
MinimumHeightRequest="{StaticResource MinimumHeight}">
<Grid.Resources>
<ResourceDictionary>
<Style TargetType="numericInput:NumericInputButton"
Class="DefaultNumericInputButtonStyle">
<Setter Property="BorderRadius">

1339
Telerik UI for Xamarin

<Setter.Value>
<OnPlatform x:TypeArguments="x:Int32">
<On Platform="iOS" Value="10"/>
<On Platform="UWP" Value="0"/>
</OnPlatform>
</Setter.Value>
</Setter>
<Setter Property="BorderColor" Value="Accent"/>
<Setter Property="TextColor" Value="Accent"/>
<Setter Property="BackgroundColor" Value="Transparent"/>
<Setter Property="BorderThickness" Value="2"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="Padding" Value="0,0,0,0"/>
</Style>
<Style TargetType="numericInput:NumericInputEntry"
Class="DefaultNumericInputEntryStyle">
<Setter Property="HorizontalTextAlignment" Value="Center"/>
<Setter Property="VerticalTextAlignment" Value="Center"/>
<Setter Property="Padding" Value="0,0,0,0"/>
<Setter Property="Keyboard" Value="Numeric"/>
<Setter Property="BorderStyle">
<Setter.Value>
<telerikInput:BorderStyle>
<telerikInput:BorderStyle.BorderThickness>
<OnPlatform x:TypeArguments="Thickness" Default="2">
<On Platform="Android" Value="0,0,0,2"/>
<On Platform="iOS" Value="2"/>
<On Platform="UWP" Value="2"/>
</OnPlatform>
</telerikInput:BorderStyle.BorderThickness>
</telerikInput:BorderStyle>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
</Grid.Resources>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{StaticResource ButtonWidth}"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="{StaticResource ButtonWidth}"/>
</Grid.ColumnDefinitions>
<numericInput:NumericInputButton Text="{TemplateBinding DecreaseButtonText}"
Command="{TemplateBinding DecreaseCommand}"
StyleClass="DefaultNumericInputButtonStyle"
common:StyleManager.InheritedStyleClass="{TemplateBinding ActualStyleClass}"
AutomationId="NumericDecreaseButton">
<AutomationProperties.HelpText>
<OnPlatform x:TypeArguments="x:String">
<On Platform="UWP" Value="NumericDecreaseButton"/>
<On Platform="iOS" Value="NumericDecreaseButton"/>
</OnPlatform>
</AutomationProperties.HelpText>

1340
Telerik UI for Xamarin

</numericInput:NumericInputButton>

<numericInput:NumericInputEntry Grid.Column="1"
x:Name="PART_Entry"
StyleClass="DefaultNumericInputEntryStyle"
Text="{TemplateBinding Value, Mode=OneWay}"
InputTransparent="{TemplateBinding IsReadOnly}"
common:StyleManager.InheritedStyleClass="{TemplateBinding ActualStyleClass}"
AutomationId="NumericEntry"/>

<numericInput:NumericInputButton Grid.Column="2"
Text="{TemplateBinding IncreaseButtonText}"
Command="{TemplateBinding IncreaseCommand}"
StyleClass="DefaultNumericInputButtonStyle"
common:StyleManager.InheritedStyleClass="{TemplateBinding ActualStyleClass}"
AutomationId="NumericIncreaseButton">
<AutomationProperties.HelpText>
<OnPlatform x:TypeArguments="x:String">
<On Platform="iOS" Value="NumericIncreaseButton"/>
<On Platform="UWP" Value="NumericIncreaseButton"/>
</OnPlatform>
</AutomationProperties.HelpText>
</numericInput:NumericInputButton>
</Grid>
</ControlTemplate>
</ResourceDictionary>
 

You need to copy the original ControlTemplate and its resource dependencies to the Resources
section of the page, then you can modify the used colors, sizes, relocate or remove elements (for
example you can align the two buttons after the entry).

Any ControlTemplate element that is prefixed with "PART_" is almost always a required part.
Removing such a part will result in the control not working. For example the NumericInputEntry
control is named PART_Entry and cannot be removed.
 
Finally, use the custom ControlTemplate as a StaticResource on any instance of RadNumericInput:

XAML
<telerikInput:RadNumericInput x:Name="numericInput"
ControlTemplate="{StaticResource CustomRadNumericInput_ControlTemplate}" />
 

See Also
 Key Features

1341
Telerik UI for Xamarin

Globalization
 

Globalization is the process of designing and developing your application in such a way that it adapts
to different culture configurations. The number formatting also varies between cultures, especially for
some specific symbols, such as decimal separators, currency and other.

RadNumericInput provides you the option to define the format of its numeric value through the
StringFormat property. You can set it to the desired format which will be applied when the control
loses focus.

You can find detailed information about the supported numeric formats here: Standard Numeric
Format Strings.
 
Any culture-specific symbols in the display format will be applied according to the UICulture of the
current thread. If not set explicitly, the UICulture is taken from the target device.

Let’s, for example, have the following NumericInput where “C” represents the Currency symbol:

<telerikInput:RadNumericInput StringFormat="{}{0:C2}" Value="1000" />


 

Depending on the UICulture of the current thread, the result is the following:

Figure 1: NumericInput with UICulture set to “en-US”

Figure 2: NumericInput with UICulture set to “de-DE”

String format is applied when the NumericInput control loses focus. So, in case you’d like to switch

1342
Telerik UI for Xamarin

the thread UICulture dynamically, you’d need to explicitly focus the NumericInput, then switch the
focus to some other control, so that the change to take effect.

Here is a quick snippet:

this.input.Focus();
this.othercontrol.Focus();
 

See Also
 Key Features
 Commands

1343
Telerik UI for Xamarin

Commands
RadNumericInput exposes IncreaseCommand and DecreaseCommand which could be used to
define custom functionality upon the respective actions. These commands allow you to easily
change and extend the control's default behavior.

In the next example, you can see how the NumericInput commands could be utilized in order to
implement auto-reverse functionality – start from the Minimum value when the Maximum is reached
and vice versa.

First, create the ViewModel with both IncreaseCommand and DecreaseCommand implementations:

C#
public class CommandsViewModel : INotifyPropertyChanged
{
private double value;
public event PropertyChangedEventHandler PropertyChanged;
public CommandsViewModel()
{
this.CustomIncreaseCommand = new Command(this.IncreaseCommandExecute,
this.IncreaseCommandCanExecute);
this.CustomDecreaseCommand = new Command(this.DecreaseCommandExecute,
this.DecreaseCommandCanExecute);
this.Step = 1;
this.Value = 0;
this.Minimum = 0;
this.Maximum = 5;
}
public double Maximum { get; set; }
public double Minimum { get; set; }
public double Step { get; set; }
public double Value
{
get
{
return this.value;
}
set
{
if (this.value != value)
{
this.value = value;
OnPropertyChanged("Value");
}
}
}
public ICommand CustomDecreaseCommand { get; set; }
public ICommand CustomIncreaseCommand { get; set; }
private bool DecreaseCommandCanExecute(object arg)
{

1344
Telerik UI for Xamarin

return true;
}
private void DecreaseCommandExecute(object obj)
{
double newValue = this.Value - this.Step;
if (newValue >= this.Minimum)
this.Value = newValue;
else
this.Value = this.Maximum;
}
private bool IncreaseCommandCanExecute(object arg)
{
return true;
}
private void IncreaseCommandExecute(object obj)
{
double nextValue = this.Value + this.Step;
if (nextValue <= this.Maximum)
this.Value = nextValue;
else
this.Value = this.Minimum;
}
private void OnPropertyChanged(string propertyName)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
 

And define the NumericInput with the respective bindings:

XAML
<telerikInput:RadNumericInput x:Name="input"
Minimum="{Binding Minimum}"
Maximum="{Binding Maximum}"
Step="{Binding Step}"
Value="{Binding Value, Mode=TwoWay}"
IncreaseCommand="{Binding CustomIncreaseCommand}"
DecreaseCommand="{Binding CustomDecreaseCommand}">
<telerikInput:RadNumericInput.BindingContext>
<local:CommandsViewModel />
</telerikInput:RadNumericInput.BindingContext>
</telerikInput:RadNumericInput>
 

Where:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

1345
Telerik UI for Xamarin

You can find a working demo in the NumericInput/Features/Commands folder of the SDK Samples
Browser application.
 

See Also
 Key Features
 Globalization

1346
Telerik UI for Xamarin

Overview
RadPath is a control which can be used to draw complex shapes that are composed of different
geometries like arcs, ellipses, lines and rectangles.

Figure 1: RadPath Overview

Key features
 Styling options: RadPath exposes a few useful properties for defining the colors of the drawn
shape. For more info go to Styling topic.
 Geometry support: You could implement any shape through the RadPathGeometry object
which contains Figures such as Line and Arc. For more details on this check the following
topic: PathGeometry.
 MultiPath object: Through RadMultiPath you could combine several PathGeometry objects
into a single element. Check MultiPath article for more information on this.

See Also
 Getting Started

1347
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadPath control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadPath control

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add
separate nuget packages. For RadPath control you have to install the
Telerik.UI.for.Xamarin.Primitives and Telerik.UI.for.Xamarin.Input nuget packages. These nugets will
automatically refer the Telerik.UI.for.Xamarin.Common, Telerik.UI.for.Xamarin.DataControls and
Telerik.UI.for.Xamarin.SkiaSharp nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadPath component:

Platform Assemblies
Portable Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.SkiaSharp.dll
Android Telerik.Xamarin.Android.Common.dll
Telerik.Xamarin.Android.Data.dll
Telerik.Xamarin.Android.Input.dll
Telerik.Xamarin.Android.List.dll
Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataControls.dll

1348
Telerik UI for Xamarin

Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.SkiaSharp.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.SkiaSharp.dll
UWP Telerik.Core.dll
Telerik.Data.dll
Telerik.UI.Xaml.Controls.Data.UWP.dll
Telerik.UI.Xaml.Input.UWP.dll
Telerik.UI.Xaml.Primitives.UWP.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.SkiaSharp.dll
RadPath is rendered via the SkiaSharp graphics library so you need to install also
SkiaSharp.Views.Forms in all projects of the Xamarin solution (.Net Standard/Shared, Android, iOS,
etc).
 

3. Adding RadPath control


If your app is correctly set, you are ready to add a RadPath control within your page.

RadPath control exposes Geometry property which should be assigned to a RadPathGeometry


object. RadPathGeometry consists of different RadPathFigures such as line and arc. RadPath also
provides a few predefined geometries such as star, circle and other. Below you can find two
examples of creating a path with built-in as well as custom geometry.

Creating RadPath with built-in geometry


RadPath provides several built-in geometries that can be found in the
Telerik.XamarinForms.Input.Geometries static class. Below you could find a list of the available
geometries:

 Star;
 Circle;
 Heart;
 Diamond.

You can choose any of those and set it directly to the Geometry property of the Path component:

XAML
<telerikPrimitives:RadPath x:Name="starPath"

1349
Telerik UI for Xamarin

StrokeThickness="0"
Fill="#FFC325"
Geometry="{x:Static telerikInput:Geometries.Star}" />
 

C#
var mainGrid = new Grid() { ColumnSpacing = 20, RowSpacing = 10};
mainGrid.RowDefinitions.Add(new RowDefinition() { Height = 200 });
mainGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Star });
mainGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Star });

var starPath = new RadPath()


{
Geometry = Geometries.Star,
StrokeThickness = 0,
Fill = new RadSolidColorBrush(Color.FromHex("FFC325"))
};
mainGrid.Children.Add(starPath);
 

In addition to this you need to add the following namespaces:

XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

Creating RadPath with custom geometry


You are free to create a custom geometry which will be visualized by the RadPath control. For that
purpose, you need to create object of type RadPathGeometry and add a RadPathFigure with the
needed segments.

The next example shows a RadPath with an Arc definition:

XAML
<telerikPrimitives:RadPath x:Name="customPath"
Grid.Row="0"
StrokeThickness="4"
Stroke="#2EC262">
<telerikCommon:RadPathGeometry>
<telerikCommon:RadPathFigure StartPoint="0.85, 0.85">
<telerikCommon:RadArcSegment Center = "0.5, 0.5"
Size = "1, 1"
StartAngle = "315"
SweepAngle = "270" />
</telerikCommon:RadPathFigure>
</telerikCommon:RadPathGeometry>
</telerikPrimitives:RadPath>

1350
Telerik UI for Xamarin

C#
var arcPath = new RadPath()
{
StrokeThickness = 4,
Stroke = new RadSolidColorBrush(Color.FromHex("2EC262"))
};
RadPathFigure arc = new RadPathFigure();
arc.StartPoint = new Point(0.85, 0.85);
arc.Segments.Add(new RadArcSegment()
{
Center = new Point(0.5, 0.5),
Size = new Size(1, 1),
StartAngle = 315,
SweepAngle = 270
});

RadPathGeometry geometry = new RadPathGeometry();


geometry.Figures.Add(arc);
arcPath.Geometry = geometry;

mainGrid.Children.Add(arcPath);
 

and add the following namespace:

XAML
xmlns:telerikCommon="clr-namespace:Telerik.XamarinForms.Common;assembly=Telerik.Xamari
nForms.Common"
 

Both RadPath objects appearance can be reviewed in the image below:

1351
Telerik UI for Xamarin

SDK Browser and QSF applications contain different examples that show RadPath's main features.
You can find the applications in the Examples and QSF folders of your local Telerik UI for Xamarin
installation.
 

See Also
 PathGeometry

1352
Telerik UI for Xamarin

PathGeometry
In order to create a specific RadPath, you need to set a RadPathGeometry object to its Geometry
property. The RadPathGeometry object exposes a Figures property which is a collection of
RadPathFigures.

RadPathFigure
Each of the RadPathFigure objects is composed of one or several segments. These can be a
RadArcSegment or a RadLineSegment. Adding several segments in combination with setting up the
StartPoint of the RadPathFigure is enough for you to create the desired figure which should be
added to the figures collection of the geometry.

Each line or arc segment you add to the path figure is drawn consequently - its starting point is the
last point of the previous segment of the Segments collection of the PathFigure object. The first
segment uses the StartPoint of the path figure as starting point.

RadArcSegment
The RadArcSegment represents an elliptical arc between two points. It exposes the following
properties:

 Center: Defines the center point of the arc.


 Size: Sets the x- and y-diameter of the arc as a Size structure.
 StartAngle: Determines the angle from which the arc segment will start.
 SweepAngle: Specifies the length in degrees from the first to the second arc point. Positive
angles are counter clockwise and negative angles clockwise.

The scheme below shows how StartAngle and SweepAngle are applied to the ArcSegment:

1353
Telerik UI for Xamarin

Here is a sample implementation of an RadArcSegment object:

XAML
<telerikPrimitives:RadPath x:Name="simpleArcPath"
StrokeThickness="4"
Stroke="#2EC262">
<telerikCommon:RadPathGeometry>
<telerikCommon:RadPathFigure StartPoint="1, 0.5">
<telerikCommon:RadArcSegment Center = "0.5, 0.5"
Size = "1, 1"
StartAngle = "0"
SweepAngle = "180" />
</telerikCommon:RadPathFigure>
</telerikCommon:RadPathGeometry>
</telerikPrimitives:RadPath>
 

RadLineSegment
Creates a line between two points in a RadPathFigure. The starting point of the line is defined either
by the previous segment's end point or by the StartPoint of the PathFigure object. The end point is
defined by the Point property of the LineSegment object.

The thickness and the color of the line are determined by the StrokeThickness and Stroke properties
of the Path object this line figure is added to.

Check below a simple example of how to create a line PathFigure:

XAML
<telerikPrimitives:RadPath x:Name="simpleLinePath"
StrokeThickness="4"
Stroke="#2EC262">
<telerikCommon:RadPathGeometry>
<telerikCommon:RadPathFigure StartPoint="0.8, 0.1">
<telerikCommon:RadLineSegment Point="0.1, 0.8" />
</telerikCommon:RadPathFigure>
</telerikCommon:RadPathGeometry>
</telerikPrimitives:RadPath>
 

Example
The following example shows how to create a more complex RadPathGeometry object and add a
line with curved edges to its Figures collection.

First you should define the RadPath figure:

XAML
<telerikPrimitives:RadPath x:Name="customLinePath"
Grid.Row="0"

1354
Telerik UI for Xamarin

StrokeThickness="0"
Fill="#3DBAFE"/>
 

And then you set its Geometry to have the following structure:

C#
RadPathFigure customLine = new RadPathFigure();
customLine.StartPoint = new Point(0.8, 0.1);
customLine.Segments.Add(new RadLineSegment(new Point(0.1, 0.8)));

customLine.Segments.Add(new RadArcSegment() { Center = new Point(0.125, 0.825),


StartAngle = 135, SweepAngle = 180, Size = new Size(0.070710678, 0.070710678) });
customLine.Segments.Add(new RadLineSegment(new Point(0.85, 0.15)));
customLine.Segments.Add(new RadArcSegment() { Center = new Point(0.825, 0.125),
StartAngle = 315, SweepAngle = 180, Size = new Size(0.070710678, 0.070710678) });

RadPathGeometry geometry = new RadPathGeometry();


geometry.Figures.Add(customLine);
customLinePath.Geometry = geometry;
 

Check the screenshot below which shows the result after creating the three Paths:

See Also
 MultiPath
 Styling

1355
Telerik UI for Xamarin

MultiPath
RadMultiPath allows you to combine several PathGeometry objects into a single element. The
MultiPath contains a collection of RadPathDefinition objects and each of them provides a Geometry
property as well as the same styling properties as the RadPath.

Here is a an example of RadMultiPath definition:

XAML
<Grid x:Name="root">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<telerikPrimitives:RadMultiPath x:Name="multiPath"
Grid.Row="0"
HorizontalOptions="Center"
VerticalOptions="Center">
<telerikPrimitives:RadPathDefinition Fill="#FF4285F4">
<telerikCommon:RadPathGeometry>
<telerikCommon:RadPathFigure>
<telerikCommon:RadArcSegment Center="0.5, 0.5" SweepAngle="360" Size="0.9, 0.9"
/>
</telerikCommon:RadPathFigure>
</telerikCommon:RadPathGeometry>
</telerikPrimitives:RadPathDefinition>
<telerikPrimitives:RadPathDefinition Fill="#FFEA4335">
<telerikCommon:RadPathGeometry>
<telerikCommon:RadPathFigure>
<telerikCommon:RadArcSegment Center="0.5, 0.5" SweepAngle="360" Size="0.6, 0.6"
/>
</telerikCommon:RadPathFigure>
</telerikCommon:RadPathGeometry>
</telerikPrimitives:RadPathDefinition>
<telerikPrimitives:RadPathDefinition Fill="#FFFBBC05">
<telerikCommon:RadPathGeometry>
<telerikCommon:RadPathFigure>
<telerikCommon:RadArcSegment Center="0.5, 0.5" SweepAngle="360" Size="0.3, 0.3"
/>
</telerikCommon:RadPathFigure>
</telerikCommon:RadPathGeometry>
</telerikPrimitives:RadPathDefinition>
</telerikPrimitives:RadMultiPath>
<telerikPrimitives:RadMultiPath x:Name="path2"
Grid.Row="1"
HorizontalOptions="Center"
VerticalOptions="Center">
<telerikPrimitives:RadPathDefinition Stroke="#FF364781"
StrokeThickness="{StaticResource strokeThickness}">
<telerikCommon:RadPathGeometry>
<telerikCommon:RadPathFigure StartPoint="0.95, 0.95">

1356
Telerik UI for Xamarin

<telerikCommon:RadLineSegment Point="0.75, 0.75" />


</telerikCommon:RadPathFigure>
</telerikCommon:RadPathGeometry>
</telerikPrimitives:RadPathDefinition>
<telerikPrimitives:RadPathDefinition Fill="#FF64B5FF" Stroke="#FF616161"
StrokeThickness="{StaticResource strokeThickness}">
<telerikCommon:RadPathGeometry>
<telerikCommon:RadPathFigure StartPoint="0.75, 0.75">
<telerikCommon:RadArcSegment Center="0.4, 0.4" StartAngle="-45"
SweepAngle="360" Size="0.7, 0.7" />
</telerikCommon:RadPathFigure>
</telerikCommon:RadPathGeometry>
</telerikPrimitives:RadPathDefinition>
<telerikPrimitives:RadPathDefinition Fill="#FFBDE0FF">
<telerikCommon:RadPathGeometry>
<telerikCommon:RadPathFigure StartPoint="0.241, 0.241">
<telerikCommon:RadArcSegment Center="0.4, 0.4" StartAngle="135"
SweepAngle="-90" Size="0.45, 0.45" />
<telerikCommon:RadArcSegment Center="0.541, 0.259" StartAngle="45"
SweepAngle="-180" Size="0.05, 0.05" />
<telerikCommon:RadArcSegment Center="0.4, 0.4" StartAngle="45" SweepAngle="90"
Size="0.35, 0.35" />
<telerikCommon:RadArcSegment Center="0.259, 0.259" StartAngle="-45"
SweepAngle="-180" Size="0.05, 0.05" />
</telerikCommon:RadPathFigure>
</telerikCommon:RadPathGeometry>
</telerikPrimitives:RadPathDefinition>
</telerikPrimitives:RadMultiPath>
</Grid>
 

The image below shows the result:

1357
Telerik UI for Xamarin

See Also
 PathGeometry
 Styling

1358
Telerik UI for Xamarin

Styling
The RadPath element exposes the following properties you can use to customize the look of the
path figures:

 Fill: Used for setting up the color within the figures. You should set an object of type
RadBrush. This can be a RadSolidColorBrush or a RadSweepGradientBrush
 Stroke: You can use this property to set the stroke color.
 StrokeThickness: You can use this property to set the thickness of the stroke.
 BackgroundColor: You can use this property to modify the color of the rectangle which
contains the specific figure.

Here is an example with RadSweepGradientBrush:

XAML
<telerikPrimitives:RadPath x:Name="gradientPath"
StrokeThickness="1"
Stroke="White"
Geometry="{x:Static telerikInput:Geometries.Diamond}">
<telerikPrimitives:RadPath.Fill>
<telerikCommon:RadSweepGradientBrush>
<x:Arguments>
<Point>0.5, 0.5</Point>
</x:Arguments>
<telerikCommon:RadSweepGradientStop>
<x:Arguments>
<Color>#1481FF</Color>
<x:Double>180</x:Double>
</x:Arguments>
</telerikCommon:RadSweepGradientStop>
<telerikCommon:RadSweepGradientStop>
<x:Arguments>
<Color>#BCE1FF</Color>
<x:Double>360</x:Double>
</x:Arguments>
</telerikCommon:RadSweepGradientStop>
</telerikCommon:RadSweepGradientBrush>
</telerikPrimitives:RadPath.Fill>
</telerikPrimitives:RadPath>
 

Below you can check an example with RadSolidColorBrush:

XAML
<telerikPrimitives:RadPath x:Name="solidPath"
Grid.Row="0"
StrokeThickness="2"
Stroke="#1481FF"
Fill="#BCE1FF">

1359
Telerik UI for Xamarin

<telerikCommon:RadPathGeometry>
<telerikCommon:RadPathFigure StartPoint="0, 1">
<telerikCommon:RadLineSegment Point="1, 1" />
<telerikCommon:RadLineSegment Point="0.5, 0" />
<telerikCommon:RadLineSegment Point="0, 1" />
</telerikCommon:RadPathFigure>
</telerikCommon:RadPathGeometry>
</telerikPrimitives:RadPath>
 

And the result is shown below:

See Also
 PathGeometry

1360
Telerik UI for Xamarin

Overview
RadPdfProcessing is part of the Telerik Document Processing libraries. The full documentation for
this component is available at
https://docs.telerik.com/devtools/document-processing/libraries/radpdfprocessing.
 
RadPdfProcessing is a processing library that allows creation, import and export of PDF documents.

The API of RadPdfProcessing contains two different editors, enabling you to choose between editing
in a flow-like manner, or using the much more powerful and flexible fixed document structure and
drawing on the page.

The document model of the library provides support for:

 Pages: Adding, modifying or removing of pages in a document. The properties enable you to
change the size of the page, its rotation and more.
 Automatic layout: Although the PDF format is fixed, sometimes you will need to insert the
content in a way that flows on the page. RadPdfProcessing enables to achieve this easily by
using blocks, tables and lists.
 Images: Decoded on demand to achieve better performance. The API enables you to obtain
the encoded image data. You can also control the image quality when saving the document.
 Geometries: Enable you to describe the geometry of a 2D shape.
 Form XObjects: The Form XObjects enables you to describe composite objects (consisting of
text, images, vector elements, etc.) within a PDF file and reuse this content among the
document, for smaller document size and better rendering performance.
 Interactive Forms: Create and modify PDF files containing textboxes, buttons, listboxes and

1361
Telerik UI for Xamarin

other interactive controls making available for the PDF file user to interactively fill some data in
the PDF document and/or digitally sign the filled document. You can flatten the fields as well.
 Clipping: You can define the outline of other content elements like images and paths.
 Annotations: Associate an object with a location on a page of the PDF document.
 Destinations: Defines a particular view of a document.
 Colors and Color Spaces: Support for different types of both.
 Fonts: Support for the standard PDF fonts, Type0, Type1, CIDFontType2, TrueType and
more.
 Text and Graphic properties: Provide options for changing the properties of the different
elements in the document elements so you can achieve a unique look.
 Password Protection
 Merge documents and document pages.
 PdfFileStream: The API exposes a functionality that provides option for exporting PDF files
with unmatched performance and minimized memory footprint. Extremely useful when you
need to add some content to existing document, merge or split documents.
 Import of PDF and export to PDF and plain text

Required references
You have two options to add the required Telerik references to your Xamarin.Forms app in order to
use RadPdfProcessing:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadPdfProcessing you have to install the Telerik.Documents.Core,
Telerik.Documents.Fixed and Telerik.Zip nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadPdfProcessing:
 Telerik.Documents.Core.dll
 Telerik.Documents.Fixed.dll
 Telerik.Zip.dll

Please keep in mind these assemblies are located in the Portable folder, still, you need to add a
reference to them in the Xamarin.Forms project as well as in each of the platform projects (Android |
iOS | UWP).
 

1362
Telerik UI for Xamarin

Overview
RadPdfViewer for Xamarin is a control that enables you to easily load and display PDF documents
natively in your application. It has been made more than simple with the exposed commands that
can be easily bound to and the full integration with the RadPdfViewerToolbar.

Figure 1: RadPdfViewer Overview

Key Features
 Visualize pdf documents: RadPdfViewer could display pdf documents that include images,
shapes (geometrics), different colors(solid, linear and radial gradients), ordered and bullet
lists, and more.
 Various document source options: You could load the pdf document from a stream, from a
file added as embedded resource or a file located on the device, etc. For more details check
Key Features: Pdf Document Visualization.
 Zooming Functionality: RadPdfViewer provides an option for zoom in and zoom out the
content of the document. For more details on this check Zoom Level Support topic.
 Single page and Continuous Scrolling Support: You can choose between two layout modes
which allow the document to be scrolled in the viewer. Read Viewing Modes for more details.
 Commands Support: RadPdfViewer allows you to extend the default commands, such as
ZoomIn, ZoomOut, NavigateTo (NextPage, PreviousPage, Page), FitToWidth and

1363
Telerik UI for Xamarin

ToggleLayoutMode. For detailed information on the matter check Commands article.


 RadPdf Toolbar (Build-In Commands Operations): You could take advantage of a
pre-defined UI automatically wired with all of the commands provided by the control through
built-in functionality. Check Pdf Toolbar article for more info.

Check out RadPdfViewer Getting Started help article that shows how to use it in a basic scenario.
 

See Also
 Getting Started
 Key Features
 Commands
 Pdf Toolbar

1364
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadPdfViewer control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadPdfViewer control
 Visualize a Pdf Document

1. Setting up the app


Start by setting up the app. See the following articles for detailed instructions:

 Setup app with Telerik UI for Xamarin on Windows.


 Setup app with Telerik UI for Xamarin on Mac.

2. Adding the required Telerik references


To add the required Telerik references to your project, choose one of the three options:

 Add the entire Telerik.UI.for.Xamarin NuGet package.


 Add only the Telerik.UI.for.Xamarin.PdfViewer NuGet package.

The NuGet package manager will automatically add the following dependencies:
Telerik.UI.for.Xamarin.Common, Telerik.UI.for.Xamarin.Primitives,
Telerik.UI.for.Xamarin.SkiaSharp, SkiaSharp and SkiaSharp.Views.Forms.

 Add the references to all required Telerik assemblies manually.

The following table presents the required assemblies for the RadPdfViewer component:

Platform Assemblies
Portable Telerik.Documents.Core.dll
Telerik.Documents.Fixed.dll
Telerik.XamarinForms.PdfViewer.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.SkiaSharp.dll
Android Telerik.Documents.Core.dll
Telerik.Documents.Fixed.dll
Telerik.Xamarin.Android.Primitives.dll
Telerik.Xamarin.Android.Common.dll
Telerik.XamarinForms.PdfViewer.dll
Telerik.XamarinForms.Common.dll

1365
Telerik UI for Xamarin

Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.SkiaSharp.dll
iOS Telerik.Documents.Core.dll
Telerik.Documents.Fixed.dll
Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.PdfViewer.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.SkiaSharp.dll
UWP Telerik.Core.dll
Telerik.Documents.Core.dll
Telerik.Documents.Fixed.dll
Telerik.UI.Xaml.Primitives.UWP.dll
Telerik.XamarinForms.PdfViewer.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives
Telerik.XamarinForms.SkiaSharp.dll
Add a reference to the Telerik.Documents.Core.dll and Telerik.Documents.Fixed.dll assemblies to
each project. The assemblies are located in the \Binaries\Portable folder of your Telerik UI for
Xamarin installation.
 

3. Adding RadPdfViewer control


Use one of the following approaches:

Drag the control from the Toolbox.

Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML.

XAML
<telerikPdfViewer:RadPdfViewer x:Name="pdfViewer" />
 

After you create the control definition, add the following namespace:

XAML
xmlns:telerikPdfViewer="clr-namespace:Telerik.XamarinForms.PdfViewer;assembly=Telerik.
XamarinForms.PdfViewer"
 

4. Visualize a Pdf Document

1366
Telerik UI for Xamarin

To visualize the pdf document, set the Source property of the control:

C#
Func<CancellationToken, Task<Stream>> streamFunc = ct => Task.Run(() =>
{
Assembly assembly = typeof(PdfViewerGettingStartedXaml).Assembly;
string fileName = assembly.GetManifestResourceNames().FirstOrDefault(n =>
n.Contains("pdfviewer-overview.pdf"));
Stream stream = assembly.GetManifestResourceStream(fileName);
return stream;
});
this.pdfViewer.Source = streamFunc;
 

This is the result:

The example below shows a pdf document visualized as an EmbeddedResource. This is one of the
options for loading a pdf with the PdfViewer control. For all available options, see the Key Features
topic.
 

See Also
 Key Features
 Commands
 PdfViewer Toolbar

1367
Telerik UI for Xamarin

Key Features
The purpose of this help article is to show you the key features of the RadPdfViewer control.

Pdf Document Visualization


RadPdfViewer control enables you to visualize Pdf documents through the Source property of type
Telerik.XamarinForms.PdfViewer.DocumentSource.

The Pdf Document could be loaded from:

 RadFixedDocument - it is used to load the pdf document from a stream.

Using this approach you have more control over the loading process, for example, you could modify
the document after it is imported and before it is assigned as a Source to the PdfViewer control. For
more details check RadFixedDocument topic from RadPdfProcessing documentation.
 
Example:

C#
private void ImportFixedDocument()
{
Telerik.Windows.Documents.Fixed.FormatProviders.Pdf.PdfFormatProvider provider =
new Telerik.Windows.Documents.Fixed.FormatProviders.Pdf.PdfFormatProvider();
Assembly assembly = typeof(KeyFeatures).Assembly;
string fileName = assembly.GetManifestResourceNames().FirstOrDefault(n =>
n.Contains("pdfviewer-overview.pdf"));
using (Stream stream = assembly.GetManifestResourceStream(fileName))
{
RadFixedDocument document = provider.Import(stream);
this.pdfViewer.Source = document;
}
}
 

The example shows a pdf document visualized as an EmbeddedResource. This is one of the options
for loading a pdf with the PdfViewer control.
 

 Uri

C#
Uri uri = this.GetUri();
this.pdfViewer.Source = uri;
 

or

1368
Telerik UI for Xamarin

C#
Uri uri = this.GetUri();
this.pdfViewer.Source = new UriDocumentSource(uri);
 

where GetUri() method returns a valid and accessible URL.

 File - you can visualize the pdf document from a file located on a device (available since R1
2019 SP). You just need to pass the file path to the Source property of the PdfViewer control:

C#
this.pdfViewer.Source = filePath;
 

where the filePath variable is a string that contains the path to the file location.

In order to make sure that the file exists on the device you could use the following code:

C#
System.IO.File.OpenRead(filePath);
 

Please make sure that you have granted the app all the permissions needed before the resources
are used. Otherwise, an error will be raised.
 

 Byte Array

C#
byte[] bytes = this.GetBytes();
this.pdfViewer.Source = bytes;
 

or

C#
byte[] bytes = this.GetBytes();
this.pdfViewer.Source = new ByteArrayDocumentSource(bytes, true);
 

 Stream

There are two ways:

C#
Func<CancellationToken, Task<Stream>> streamFunc = ct => Task.Run(() =>
{
Assembly assembly = typeof(KeyFeatures).Assembly;
string fileName = assembly.GetManifestResourceNames().FirstOrDefault(n =>

1369
Telerik UI for Xamarin

n.Contains("pdfviewer-overview.pdf"));
Stream stream = assembly.GetManifestResourceStream(fileName);
return stream;
});
this.pdfViewer.Source = streamFunc;
 

or

C#
Assembly assembly = typeof(KeyFeatures).Assembly;
string fileName = assembly.GetManifestResourceNames().FirstOrDefault(n =>
n.Contains("pdfviewer-overview.pdf"));
Stream stream = assembly.GetManifestResourceStream(fileName);
var streamDocumentSource = new StreamDocumentSource();
streamDocumentSource.Import(stream);
this.pdfViewer.Source = streamDocumentSource;
 

If you choose the second approach with StreamDocumentSource, please keep in mind the stream
must stay open while the PdfViewer is in use, because the pdf import is ReadOnDemand. This
means that you'd need to manually close the stream when no longer using the PdfViewer.
 

ReadOnDemand Loading
RadPdfViewer control provides ReadOnDemand loading of the Pdf document, which means that
each page of the document is loaded dynamically when necessary (when needed to be shown in the
PdfViewer) and it is unloaded once it becomes invisible. The stream that holds the document stays
opened while the document is used in PdfViewer.

Document Reference
Through the Document property of RadPdfViewer you can get a reference to the
RadFixedDocument imported by the DocumentSource. For more details check RadFixedDocument
topic from RadPdfProcessing documentation.

Zoom Level Support


RadPdfViewer exposes properties for applying min and max zoom values.

 MaxZoomLevel(double): Defines the maximum magnification factor at which content could


be maximized. The default value is 3.0
 MinZoomLevel(double): Defines the minimum magnification factor at which content could be
minimized. The default value is 0.3

In order to check how these properties works you should set the ZoomIn and ZoomOut Commmands
of the control. For more details please check the Commands article.
 

1370
Telerik UI for Xamarin

Viewing Modes
You could easily set one of the two layout modes that the control provides through its LayoutMode
property.

The available options are:

 ContinuousScroll: Displays pages in a continuous vertical column.


 SinglePage: Displays one page at a time.

By default the PdfViewer LayoutMode property is set to ContinuousScroll.


 
The RadPdfViewer LayoutMode could be triggered through the ToggleLayoutModeCommand and
the ToggleLayoutModeToolbarItem.
 
Here is how the PdfViewer looks when LayoutMode is set to ContinuousScroll:

And when the LayoutMode property is set to SinglePage:

1371
Telerik UI for Xamarin

Password-protected Pdf Document


Starting with R2 2020 release RadPdfViewer provides SourcePasswordNeeded event which is
useful in cases you need to display a password-protected pdf document.

 SourcePasswordNeeded: Occurs when a user password is needed to load the document in


PdfViewer. The SourcePasswordNeeded event handler receives two parameters:
 The sender argument which is of type object, but can be cast to the RadPdfViewer type.
 A PasswordNeededEventArgs object which provides Password property used to supply
the user password.

Here is a quick example of SourcePasswordNeeded event usage:

XAML
<telerikPdfViewer:RadPdfViewer x:Name="pdfViewer"
SourcePasswordNeeded="pdfViewer_SourcePasswordNeeded" />
 

And add the event handler:


C#
private void pdfViewer_SourcePasswordNeeded(object sender,
Telerik.Windows.Documents.Fixed.FormatProviders.Pdf.Import.PasswordNeededEventArgs e)
{
e.Password = "my_user_password_here";
}
 

1372
Telerik UI for Xamarin

Page Spacing
 PageSpacing(double): Defines the space between the pages of the Pdf Document. The
default value is 20.0

PagesStart Index
 VisiblePagesStartIndex(int): Defines the index at which the document will be displayed. The
default value is 0.

BusyIndicator Template
If the default busy template does not suit your needs, you could easily define a custom template
through the following property:

 BusyIndicatorTemplate(DataTemplate): Specifies the template visualized while the Pdf


Document is loading.

Here is an example how the custom BusyIndicatorTemplate could be defined:

XAML
<telerikPdfViewer:RadPdfViewer x:Name="pdfViewer">
<telerikPdfViewer:RadPdfViewer.BusyIndicatorTemplate>
<DataTemplate>
<telerikPrimitives:RadBusyIndicator AnimationType="Animation10"
AnimationContentHeightRequest="100"
AnimationContentWidthRequest="100"
IsBusy="True" />
</DataTemplate>
</telerikPdfViewer:RadPdfViewer.BusyIndicatorTemplate>
</telerikPdfViewer:RadPdfViewer>
 

Here is how the BusyIndicator Template looks:

1373
Telerik UI for Xamarin

A sample BusyIndicatorTemplate example can be found in the PdfViewer/Features folder of the SDK
Samples Browser application.
 

Example
Here is an example how the above RadPdfViewer features could be applied:

For the example we will visualize a pdf document from file embedded in the application with a
BuildAction:EmbeddedResource.

Then add the following code to load the pdf document from Stream:

C#
Func<CancellationToken, Task<Stream>> streamFunc = ct => Task.Run(() =>
{
Assembly assembly = typeof(KeyFeatures).Assembly;
string fileName = assembly.GetManifestResourceNames().FirstOrDefault(n =>
n.Contains("pdfviewer-overview.pdf"));
Stream stream = assembly.GetManifestResourceStream(fileName);
return stream;
});
this.pdfViewer.Source = streamFunc;
 

Finally, use the following snippet to declare a RadPdfViewer in XAML:

1374
Telerik UI for Xamarin

XAML
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition />
</Grid.RowDefinitions>
<telerikPdfViewer:RadPdfViewerToolbar PdfViewer="{Binding Source={x:Reference
pdfViewer}}"
IsScrollable="True">
<telerikPdfViewer:ZoomInToolbarItem />
<telerikPdfViewer:ZoomOutToolbarItem />
<telerikPdfViewer:ToggleLayoutModeToolbarItem />
</telerikPdfViewer:RadPdfViewerToolbar>
<telerikPdfViewer:RadPdfViewer x:Name="pdfViewer"
Grid.Row="1"
PageSpacing="15"
MinZoomLevel="0.2"
MaxZoomLevel="5" />
</Grid>
 

and add the following namespace:

XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
 

Where the telerikPdfViewer namespace is the following:

XAML
xmlns:telerikPdfViewer="clr-namespace:Telerik.XamarinForms.PdfViewer;assembly=Telerik.
XamarinForms.PdfViewer"
 

A sample Key Features example can be found in the PdfViewer/Features folder of the SDK Samples
Browser application.
 

See Also
 Commands
 PdfViewer Toolbar

1375
Telerik UI for Xamarin

PdfViewer Toolbar
RadPdfToolbar includes all commands that the RadPdfViewer provides. They can be used as a
pre-defined UI toolbar items. You have also the option to include additional toolbar items to the
PdfViewerToolbar with a custom command.

Predefined Toolbar Items


RadPdfToolbar contains the following Toolbar items:

 ZoomInToolbarItem
 ZoomOutToolbarItem
 NavigateToNextPageToolbarItem
 NavigateToPreviousPageToolbarItem
 NavigateToPageToolbarItem
 FitToWidthToolbarItem
 ToggleLayoutModeToolbarItem
 SearchToolbarItem

Example
Here is an example how to use the RadPdfViewer Toolbar:

Use the following snippet to define the RadPdfViewer and RadPdfToolbar:

XAML
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition />
</Grid.RowDefinitions>
<telerikPdfViewer:RadPdfViewerToolbar PdfViewer="{Binding Source={x:Reference
pdfViewer}}"
IsScrollable="True">
<telerikPdfViewer:SearchToolbarItem />
<telerikPdfViewer:ZoomInToolbarItem />
<telerikPdfViewer:ZoomOutToolbarItem />
<telerikPdfViewer:NavigateToNextPageToolbarItem/>
<telerikPdfViewer:NavigateToPreviousPageToolbarItem/>
<telerikPdfViewer:NavigateToPageToolbarItem/>
<telerikPdfViewer:FitToWidthToolbarItem/>
<telerikPdfViewer:ToggleLayoutModeToolbarItem/>
</telerikPdfViewer:RadPdfViewerToolbar>
<telerikPdfViewer:RadPdfViewer x:Name="pdfViewer" Grid.Row="1"/>
</Grid>
 

In addition to this, you need to add the following namespace:

1376
Telerik UI for Xamarin

XAML
xmlns:telerikPdfViewer="clr-namespace:Telerik.XamarinForms.PdfViewer;assembly=Telerik.
XamarinForms.PdfViewer"
 

Then add the following code to visualize the pdf document:

C#
Func<CancellationToken, Task<Stream>> streamFunc = ct => Task.Run(() =>
{
Assembly assembly = typeof(PdfToolbar).Assembly;
string fileName = assembly.GetManifestResourceNames().FirstOrDefault(n =>
n.Contains("pdfviewer-overview.pdf"));
Stream stream = assembly.GetManifestResourceStream(fileName);
return stream;
});
this.pdfViewer.Source = streamFunc;
 

The snippet above shows one of the approaches for loading a pdf document inside RadPdfViewer
just for the purpose of the example. For more details on various ways for loading the document
check Key Features: Pdf Document Visualization topic.
 
This is the result:

A sample PdfViewer Toolbar example is available in PdfViewer -> Features folder of the SDK
Browser application.

1377
Telerik UI for Xamarin

You can directly explore the code in the SDK Samples Browser repository on GitHub.

Custom Toolbar Item


You can easily add custom toolbar items to the PdfToolbar bound with a custom command. This is
implemented by creating a PdfViewerToolbarItemBase object with Text and Command properties
applied and adding it to the PdfViewerToolbar Items collection.

Below you can find an example showing how to add a custom ToolbarItem with a sample command
bound to it. The command is used just to display a message with the PdfDocument file size.

First, add the PdfViewer and the PdfToolbar controls to your page:

XAML
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition />
</Grid.RowDefinitions>
<telerikPdfViewer:RadPdfViewerToolbar PdfViewer="{Binding Source={x:Reference
pdfViewer}}"
IsScrollable="True">
<telerikPdfViewer:PdfViewerToolbarItemBase Text="&#xE815;"
FontFamily="{StaticResource IconsFontFamily}"
Command="{Binding DisplayFileSizeCommand}" />
<telerikPdfViewer:ZoomInToolbarItem />
<telerikPdfViewer:ZoomOutToolbarItem />
<telerikPdfViewer:NavigateToNextPageToolbarItem/>
<telerikPdfViewer:NavigateToPreviousPageToolbarItem/>
<telerikPdfViewer:NavigateToPageToolbarItem/>
<telerikPdfViewer:FitToWidthToolbarItem/>
<telerikPdfViewer:ToggleLayoutModeToolbarItem/>
</telerikPdfViewer:RadPdfViewerToolbar>
<telerikPdfViewer:RadPdfViewer x:Name="pdfViewer" Grid.Row="1"
Document="{Binding Document, Mode=OneWayToSource}" />
</Grid>
 

The text of the custom ToolbarItem is set to one of the provided with Telerik UI for Xamarin font
icons. For more details on this check Telerik Font Icons topic.
 
Then, load a sample pdf document in code-behind:

C#
this.BindingContext = new ViewModel();

Func<CancellationToken, Task<Stream>> streamFunc = ct => Task.Run(() =>


{
Assembly assembly = typeof(CustomToolbarItem).Assembly;

1378
Telerik UI for Xamarin

string fileName = assembly.GetManifestResourceNames().FirstOrDefault(n =>


n.Contains("pdfviewer-overview.pdf"));
Stream stream = assembly.GetManifestResourceStream(fileName);
return stream;
});
this.pdfViewer.Source = streamFunc;
 

As you might notice in the previous snippet, there is a ViewModel class set as BindingContext of the
page. In the ViewModel you can get a reference to the RadFixedDocument instance through the
Document property of the PdfViewer as well as execute the DisplayFileSizeCommand bound to the
Command property of the custom ToolbarItem:

C#
public class ViewModel
{
public ViewModel()
{
this.DisplayFileSizeCommand = new Command(this.DisplayFileSizeCommandExecute);
}

public RadFixedDocument Document { get; set; }


public ICommand DisplayFileSizeCommand { get; set; }

protected void DisplayFileSizeCommandExecute(object para)


{
RadFixedDocument document = this.Document;
if (document != null)
{
using (MemoryStream stream = new MemoryStream())
{
PdfFormatProvider formatProvider = new PdfFormatProvider();
formatProvider.Export(document, stream);
double megabytes = ToKiloBytes(stream.Length);
Application.Current.MainPage.DisplayAlert("", "File Size: " +
megabytes.ToString("N0") + " KB", "OK");
}
}
}

private static double ToKiloBytes(long bytesCount)


{
return (double)bytesCount / 1024;
}
}
 

Check below the result on different platforms:

1379
Telerik UI for Xamarin

A sample Custom ToolbarItem example is available in PdfViewer -> Features folder of the SDK
Browser application.

You can directly explore the code in the SDK Samples Browser repository on GitHub.

See Also
 Key Features
 Telerik Font Icons
 Text Search
 Commands

1380
Telerik UI for Xamarin

Viewport Settings
With R2 2020 SP release of Telerik UI for Xamarin RadPdfViewer provides API for getting and
manipulating its viewport through the Viewport property and ChangeViewport method.

The viewport is the "window" in which the PdfViewer displays its content, users can change the
viewport through zooming, panning and scrolling:

In order to explain how the viewport works, first we need to make clear what's the PdfViewer content
as well as how to define the content size. The PdfViewer content is the pdf document itself, and
more specifically the document pages. RadPdfViewer provides two layout mode (SinglePage or
ContinuousScroll) which use different approaches for arranging the document pages. The way the
content is defined varies according to the selected layout mode.

For detailed information on the available layout modes check Viewing Modes topic.
 

SinglePage LayoutMode

With SinglePage layout mode RadPdfViewer shows one page at a time (the pages are stacked), so
the content is the current page and the content size is the size of that page. In cases there are
pages with different size in the pdf document, the content size is changed accordingly.

1381
Telerik UI for Xamarin

The viewport position is calculated relative to the current page.

ContinuousScroll LayoutMode

With ContinuousScroll layout mode, the content refers to all pages of the document. In this mode the
pages are ordered vertically one below another with space between them and are horizontally
centered (if the document contains pages with different width, some pages will not be at 0 horizontal
position).

The content width is even to the widest page, the content height is calculated as a sum of the
heights of all the pages plus a sum of the distances between the pages (the distance between pages
is controlled by the PageSpacing property of the PdfViewer).

So, the viewport position is calculated relative to the whole content (all pages + distances):

1382
Telerik UI for Xamarin

No matter which layout mode is selected, the viewport is the "window" which moves over the defined
content and renders those pdf elements currently positioned in it.

The Viewport property of the PdfViewer is of type Xamarin.Forms.Rectangle and can be defined by
its top left corner at (x, y) position and width and height values. Keep in mind it's possible to have
negative X and Y values in case the viewport becomes bigger than the content itself.

Example
The example below demonstrates how you can utilize the ChangeViewport method to navigate to
the last page of the document in ContinuousScroll and SinglePage layout modes as well as how to
access the current viewport.

Use the following snippet to define the RadPdfViewer and RadPdfToolbar:

XAML
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition />
</Grid.RowDefinitions>
<telerikPdfViewer:RadPdfViewerToolbar PdfViewer="{Binding Source={x:Reference
pdfViewer}}">
<telerikPdfViewer:ZoomInToolbarItem />
<telerikPdfViewer:ZoomOutToolbarItem />
<telerikPdfViewer:NavigateToNextPageToolbarItem/>
<telerikPdfViewer:NavigateToPreviousPageToolbarItem/>

1383
Telerik UI for Xamarin

<telerikPdfViewer:NavigateToPageToolbarItem/>
<telerikPdfViewer:FitToWidthToolbarItem/>
<telerikPdfViewer:ToggleLayoutModeToolbarItem/>
</telerikPdfViewer:RadPdfViewerToolbar>
<telerikPdfViewer:RadPdfViewer x:Name="pdfViewer" Grid.Row="1"/>
</Grid>
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikPdfViewer="clr-namespace:Telerik.XamarinForms.PdfViewer;assembly=Telerik.
XamarinForms.PdfViewer"
 

In order to get the current viewport position and size, use the snippet below:

C#
var viewport = this.pdfViewer.Viewport;
var viewportMessage = String.Format("Current viewport with Width: {0:0.00}, Height:
{1:0.00}, Left: {2:0.00}, Top: {3:0.00}", viewport.Width, viewport.Height, viewport.X,
viewport.Y);
Application.Current.MainPage.DisplayAlert("Current Viewport", viewportMessage, "OK");
 

The next snippets demonstrates how you can manipulate the viewport of the PdfViewer:

C#
RadFixedDocument document = this.pdfViewer.Document;
var currentViewport = this.pdfViewer.Viewport;

if (this.pdfViewer.LayoutMode == LayoutMode.ContinuousScroll)
{
double pagesHeight = 0;

for (int i = 0; i < document.Pages.Count - 1; i++)


{
pagesHeight += document.Pages[i].Size.Height;
pagesHeight += this.pdfViewer.PageSpacing;
}
this.pdfViewer.ChangeViewport(new Rectangle(0, pagesHeight, currentViewport.Width,
currentViewport.Height));
}
else
{
this.pdfViewer.NavigateToPage(document.Pages.Count - 1);
this.pdfViewer.ChangeViewport(new Rectangle(0, 0, currentViewport.Width,
currentViewport.Height));
}
 

1384
Telerik UI for Xamarin

See Also
 Key Features
 Commands

1385
Telerik UI for Xamarin

Link Annotations
RadPdfViewer supports Link annotations, which means that if you open a PDF file that includes
hyperlinks to absolute URIs, you can tap any of them and have a browser open, navigated to the
respective address. In addition, if there are links pointing to bookmarks in the same document, the
view port will be scrolled to the destination specified in the link.

RadPdfViewer provides the following LinkAnnotationTapped event which allows implementing


custom logic related to links in the pdf document:

 LinkAnnotationTapped: Occurs when you click on an annotation such as a hyperlink. It


comes handy when you want to detect or even cancel the opening of a web page. The
LinkAnnotationTapped event handler receives two parameters:
 The sender argument which is of type object, but can be cast to the RadPdfViewer type.
 A LinkAnnotationTappedEventArgs object which provides the link the user tapped on via
the LinkAnnotation property and a cancellation option via the Handled boolean property.
The LinkAnnotation has information of its Action, i.e if it is a UriAction or GoToAction (link
to a position in the sampe document).

Example
The example below demonstrates how you could detect whether the link annotation leads to a URI
or a concrete position in the document, and cancel the navigation in the first case.

Then, you could implement additional logic for requesting a confirmation from the end user whether
to navigate outside of the app in the case of a hyperlink.

1386
Telerik UI for Xamarin

First, add the PdfViewer definition with the event:

XAML
<telerikPdfViewer:RadPdfViewer x:Name="pdfViewer"
LinkAnnotationTapped="LinkTapped" />
 

And here is the LinkAnnotationTapped event handler:

C#
private void LinkTapped(object sender,
Telerik.XamarinForms.PdfViewer.Annotations.LinkAnnotationTappedEventArgs e)
{
if(e.LinkAnnotation.Action is UriAction uriAction)
{
e.Handled = true;

Application.Current.MainPage.DisplayAlert("Confirm", "Are you sure you want to


navigate", "Yes", "No").ContinueWith(t =>
{
bool shouldNavigateAway = t.Status == TaskStatus.RanToCompletion ? t.Result :
false;
if (shouldNavigateAway)
{
Device.BeginInvokeOnMainThread(() =>
{
Launcher.OpenAsync(uriAction.Uri);
});
}
});
}
}
 

Here is the result on different platforms after tapping on a hyperlink:

1387
Telerik UI for Xamarin

A sample Link Annotations example can be found in the PdfViewer/Features folder of the SDK
Samples Browser application.
 

See Also
 PdfViewer Toolbar

1388
Telerik UI for Xamarin

Text Selection
With R3 2019 release of Telerik UI for Xamarin RadPdfViewer supports text selection functionality -
the end user can initiate a selection action through the hold gesture over the text. The selected text
is marked with a different background color and two drag handles are available to the user to make it
easier to modify the current selection. In addition, as soon as the selection is made, PdfViewer
displays a customizable SelectionMenu with a default Copy command to allow the user to retrieve
the selected text.

On UWP the text selection is initialized through mouse click and drag actions - continuous drag
extends the current selection. SelectionMenu can be displayed on UWP through right-click over the
selected text.
 

This topic will go through the text selection feature in details as well as the customization options it
provides.

Selection Settings
Through the SelectionSettings property of RadPdfViewer control you can modify the colors applied
to the selected text as well as to completely customize the displayed selection menu. This section
lists the properties of the SelectionSettings, so you could configure it to best suit your needs.

 IsSelectionEnabled: Boolean property that defines whether the text selection feature is
turned on. By default it is True, so you need to set it only to disable text selection;
 SelectionFill: Specifies the background color applied to the selected text;
 SelectionIndicatorColor: Sets the color of both handles around the selected text used to

1389
Telerik UI for Xamarin

modify the selection;


 SelectionMenuControlTemplate: Defines the selection menu template;
 MenuItems: Specifies a collection of menu items of type SelectionMenuItem that are
displayed in the SelectionMenu. By default PdfViewer provides "Copy" menu item used to
copy the selected text into the clipboard.

Through the MenuItems collection you could modify the listed in the selection menu options and the
commands related to them. Each SelectionMenuItem object that is added to the MenuItems
collection provides the following properties:

 Text: Sets the text shown in the SelectionMenu;


 Command: Defines the Command that is executed when tapping on that menu item. The
parameter that you will receive in the Execute method will be of type
SelectionCommandContext and through it you can retrieve the selected text.

On UWP you cannot customize the look of the SelectionMenu as it is the default UWP context menu.
Still, you can modify the menu items inside it.
 

Example
The example below demonstrates all the available customization options related to text selection
feature of PdfViewer control.

First, let's add the PdfViewer with the SelectionSettings applied:

XAML
<telerikPdfViewer:RadPdfViewer x:Name="pdfViewer">
<telerikPdfViewer:RadPdfViewer.SelectionSettings>
<telerikPdfViewer:SelectionSettings SelectionFill="#3332CD32"
SelectionIndicatorColor="#32CD32"
SelectionMenuControlTemplate="{StaticResource CustomSelectionMenuTemplate}">
<telerikPdfViewer:SelectionSettings.MenuItems>
<telerikPdfViewer:SelectionMenuItemCollection>
<telerikPdfViewer:SelectionMenuItem Text="Get Text" Command="{Binding
GetSelectedTextCommand}" />
</telerikPdfViewer:SelectionMenuItemCollection>
</telerikPdfViewer:SelectionSettings.MenuItems>
</telerikPdfViewer:SelectionSettings>
</telerikPdfViewer:RadPdfViewer.SelectionSettings>
</telerikPdfViewer:RadPdfViewer>
 

There is a reference to a CustomSelectionMenuTemplate StaticResource, so add it to the


Resources of the page:

XAML
<ResourceDictionary>
<Style TargetType="telerikPdfViewer:SelectionMenu">
<Setter Property="Fill" Value="#32CD32" />

1390
Telerik UI for Xamarin

<Setter Property="TextColor" Value="White" />


</Style>

<telerikCommon:ColorToRadBrushConverter x:Key="colorToRadBrushConverter" />


<telerikPdfViewer:SelectionMenuArrowPositionToGridRowConverter
x:Key="arrowPositionToRowConverter" />

<ControlTemplate x:Key="CustomSelectionMenuTemplate">
<Grid RowSpacing="0">
<Grid.RowDefinitions>
<RowDefinition Height="7" />
<RowDefinition Height="*" />
<RowDefinition Height="7" />
</Grid.RowDefinitions>
<telerikPdfViewer:SelectionMenuArrow Position="{TemplateBinding ArrowPosition}"
Grid.Row="{TemplateBinding ArrowPosition, Converter={StaticResource
arrowPositionToRowConverter}}"
Fill="{TemplateBinding Fill, Converter={StaticResource
colorToRadBrushConverter}}"
WidthRequest="9"
HeightRequest="7"
HorizontalOptions="Center" />
<telerikPrimitives:RadBorder BackgroundColor="{TemplateBinding Fill}"
Grid.Row="1"
CornerRadius="2"
BorderThickness="0">
<telerikPdfViewer:SelectionMenuToolbar Margin="8, 5, 8, 5"
OverflowButtonTextColor="{TemplateBinding TextColor}"
OverflowPopupBackgroundColor="{TemplateBinding Fill}"
IsScrollable="True"
MenuItems="{TemplateBinding MenuItems}" />
</telerikPrimitives:RadBorder>
</Grid>
</ControlTemplate>
</ResourceDictionary>
 

The CustomSelectionMenuTemplate defined above is similar to the original SelectionMenu template,


the only difference is the RadBorder CornerRadius as well as the Fill and TextColor of the
SelectionMenu.
 
Then, create a ViewModel class and define the GetSelectedTextCommand there. Check how the
selected text is retrieve through the SelectionCommandContext:

C#
public class ViewModel : NotifyPropertyChangedBase
{
public ViewModel()
{
this.GetSelectedTextCommand = new DisplaySelectedTextCommand();
}

public ICommand GetSelectedTextCommand { get; set; }

1391
Telerik UI for Xamarin

class DisplaySelectedTextCommand : ICommand


{
public event EventHandler CanExecuteChanged;

public bool CanExecute(object parameter)


{
SelectionCommandContext context = parameter as SelectionCommandContext;
return context != null;
}

public void Execute(object parameter)


{
SelectionCommandContext context = (SelectionCommandContext)parameter;
var selection = context.PdfViewer.Document.Selection;
Application.Current.MainPage.DisplayAlert("Selected Text",
selection.GetSelectedText(), "OK");

lock (selection)
{
selection.Clear();
}
}
}
}
 

All that is left is to set the ViewModel as the BindingContext:

C#
this.BindingContext = new ViewModel();
 

Here is how the text selection looks after the applied modifications:

1392
Telerik UI for Xamarin

The screenshots below show the result after selecting the "Get Text" item:

A sample Text Selection example can be found in the PdfViewer/Features folder of the SDK Samples
Browser application.
 

1393
Telerik UI for Xamarin

See Also
 PdfViewer Toolbar

1394
Telerik UI for Xamarin

Text Search
With R3 2020 PdfViewer for Xamarin comes with text search functionality which allows users to find
and highlight text inside the pdf document.

You can take advantage of the PdfViewerToolbar built-in search UI or search programmatically
through the provided methods. With the built-in search UI users can easily enter text and browse
through the search results within the PdfViewer toolbar. In addition, there is a small toast message
showing the count of the search results or a localizable message in case no results are found.

This topic will go through the search text feature in details as well as the customization options it
provides.

PdfViewerToolbar Search UI
PdfViewerToolbar exposes a new SearchToolbarItem which enables the search feature inside the
loaded in the viewer pdf document. You can add the SearchToolbarItem at any location inside the
toolbar, check below a sample definition of RadPdfViewerToolbar:

XAML
<telerikPdfViewer:RadPdfViewerToolbar PdfViewer="{Binding Source={x:Reference
pdfViewer}}">
<telerikPdfViewer:SearchToolbarItem />
<telerikPdfViewer:ZoomInToolbarItem />
<telerikPdfViewer:ZoomOutToolbarItem />
</telerikPdfViewer:RadPdfViewerToolbar>

1395
Telerik UI for Xamarin

When the user clicks the search toolbar item, all of the the current toolbar items are hidden and new
child items are displayed - back button along with an input for entering search. This way when the
user has finished searching they can easily go back.

As soon as the user types into the entry, a clear button is shown to enable quickly clear the entered
text and reset the search.

If the text in the entry is cleared, the search results will be cleared as well.
 
By default, search is performed when the user clicks the Search button of the keyboard (or the Enter
key of the physical keyboard in UWP). You can modify this behavior through the SearchTrigger
property of the SearchToolbarItem. SearchTrigger is of enum
Telerik.XamarinForms.PdfViewer.SearchTrigger and is used to define when a search operation
should be performed. The available values are:

 None - only programmatic calls will start a search operation.


 TextChanged - a search is triggered every time the Text is changed.
 Completed (default) - a search operation is triggered when the corresponding entry
completes (by pressing Enter/Return key).

SearchToolbarItem provides ToastStyle property used to style the toast message showing the count
of the search results or a message in case no results are found.

The snippet below shows how you can modify the SearchTrigger and the ToastStyle of a
SearchToolbarItem:

XAML
<telerikPdfViewer:RadPdfViewerToolbar PdfViewer="{Binding Source={x:Reference
pdfViewer}}">
<telerikPdfViewer:SearchToolbarItem TextSearchTrigger="TextChanged"
ToastStyle="{StaticResource MyToastStyle}" />
</telerikPdfViewer:RadPdfViewerToolbar>
 

Where MyToastStyle is defined like this:

XAML
<Style x:Key="MyToastStyle" TargetType="telerikPdfViewer:SearchToast">
<Setter Property="Fill" Value="#FF7F7F" />
<Setter Property="TextColor" Value="White" />
</Style>
 

Check the result below:

1396
Telerik UI for Xamarin

Text Search Configuration


RadPdfViewer exposes SearchSettings property which you can use to configure the search
functionality, such as search criteria, commands, highlight colors, etc.

This section lists the properties of the SearchSettings, so you can customize it per your needs.

Search Text
Through the Text property of the SearchSettings you can retrieve or explicitly set the search text (in
case you prefer not using the built-in search UI).

Search Options
SearchOptions is of type Telerik.Windows.Documents.Fixed.Search.TextSearchOptions and is used to
define some search criteria as listed below:

 UseRegularExpression - specifies whether a regular expression should be used for


searching.
 CaseSensitive - indicates whether the search should be case sensitive.
 WholeWordsOnly - indicates whether only whole words should be matched.

Highlight Colors
SearchSettings exposes two Color properties - MainSearchResultFill and SearchResultsFill. When a
search is initiated, the found search results are highlighted. Two highlight colors are needed, as
exactly one of all results has the MainSearchResultFill and is considered to be the main-result. This

1397
Telerik UI for Xamarin

is for navigation purposes, so that a user will be able to navigate to previous and next results and
keep track. The rest of the results are colored in the SearchResultsFill.

Here is an example of how you can customize SearchOptions as well as highlight colors:

First, let's add the PdfViewer together with PdfViewerToolbar with the SearchSettings applied:

XAML
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<telerikPdfViewer:RadPdfViewerToolbar PdfViewer="{Binding Source={x:Reference
pdfViewer}}"
IsScrollable="True">
<telerikPdfViewer:SearchToolbarItem TextSearchTrigger="TextChanged"
ToastStyle="{StaticResource MyToastStyle}" />
<telerikPdfViewer:ZoomInToolbarItem />
<telerikPdfViewer:ZoomOutToolbarItem />
<telerikPdfViewer:FitToWidthToolbarItem/>
<telerikPdfViewer:ToggleLayoutModeToolbarItem/>
</telerikPdfViewer:RadPdfViewerToolbar>
<telerikPdfViewer:RadPdfViewer x:Name="pdfViewer" Grid.Row="1">
<telerikPdfViewer:RadPdfViewer.SearchSettings>
<telerikPdfViewer:SearchSettings MainSearchResultFill="#99FF7F7F"
SearchResultsFill="#997FC9FF">
<telerikPdfViewer:SearchSettings.SearchOptions>
<telerikTextSearch:TextSearchOptions>
<telerikTextSearch:TextSearchOptions.WholeWordsOnly>
<x:Boolean>True</x:Boolean>
</telerikTextSearch:TextSearchOptions.WholeWordsOnly>
</telerikTextSearch:TextSearchOptions>
</telerikPdfViewer:SearchSettings.SearchOptions>
</telerikPdfViewer:SearchSettings>
</telerikPdfViewer:RadPdfViewer.SearchSettings>
</telerikPdfViewer:RadPdfViewer>
</Grid>
 

Add the needed namespaces:

XAML
xmlns:telerikPdfViewer="clr-namespace:Telerik.XamarinForms.PdfViewer;assembly=Telerik.
XamarinForms.PdfViewer"
xmlns:telerikTextSearch="clr-namespace:Telerik.Windows.Documents.Fixed.Search;assembly
=Telerik.Documents.Fixed"
 

Here is how the text selection looks after the applied modifications:

1398
Telerik UI for Xamarin

A sample Text Search example can be found in the PdfViewer/Features folder of the SDK Samples
Browser application.
 

Search Results
TextSearchResult property of the SearchSettings retrieves the current search result. It contains all
the results that are found and as well as the main result. Main result is highlighted differently from
the other search results and is used for navigation purposes, so that the user will be able to navigate
to previous and next results and keep track.

TextSearchResult exposes the following properties:

 static TextSearchResult.NotFound property - returned in case there are no results per


the search criteria;
 SearchResults collection - contains all the search results of type
Telerik.Windows.Documents.Fixed.Search.SearchResult.
 MainSearchResult - a reference to the search result considered as main result.

Commands for browsing the search results


SearchSettings exposes NavigateToPreviousSearchResultCommand and
NavigateToNextSearchResultCommand used to browse between the search results. You can bind
these commands in case you'd like to implement browse previous/next search results actions from a
custom UI, for example:

XAML

1399
Telerik UI for Xamarin

<Button Text="Previous" Command="{Binding Source={x:Reference pdfViewer},


Path=SearchSettings.NavigateToPreviousSearchResultCommand}" />
<Button Text="Next" Command="{Binding Source={x:Reference pdfViewer},
Path=SearchSettings.NavigateToNextSearchResultCommand}" />
 

Manual Search
You can use the SearchAsync method of the SearchSettings to manually initiate an async search
operation with the provided text and search options:

C#
pdfViewer.SearchSettings.SearchAsync("viewer");
 

Custom Search
You can extend the search functionality by implementing a custom TextSearchWorker.
TextSearchWorker object performs the actual search according to the search criteria.

The example below implements a custom search by multiple words - any word that is entered into
the input is considered as a separate search text.

First, create a custom class that derives from TextSearchWorker - you'd need to override the
Search method that returns TextSearchResult object:

C#
public class MultipleWordsSearchWorker : TextSearchWorker
{
protected override TextSearchResult Search(SearchContext context)
{
string regex = GetMultiWordRegex(context.Text);
TextSearchOptions regexOptions = new TextSearchOptions { UseRegularExpression =
true };
SearchContext newContext = new SearchContext(context.PdfViewer,
context.Document, regex, regexOptions, context.SearchProgress,
context.CancellationToken);

return base.Search(newContext);
}

private static string GetMultiWordRegex(string text)


{
string[] words = text.Split(new string[] { " " },
StringSplitOptions.RemoveEmptyEntries);
StringBuilder sb = new StringBuilder();

for (int i = 0; i < words.Length; i++)


{
if (i > 0)
{

1400
Telerik UI for Xamarin

sb.Append("|");
}

string expr = string.Format(@"({0})", words[i]);


sb.Append(expr);
}

return sb.ToString();
}
}
 

Then you need to apply the MultipleWordsSearchWorker object to the TextSearchWorker


property of the SearchSettings of RadPdfViewer:

XAML
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition />
</Grid.RowDefinitions>
<telerikPdfViewer:RadPdfViewerToolbar PdfViewer="{Binding Source={x:Reference
pdfViewer}}"
IsScrollable="True">
<telerikPdfViewer:SearchToolbarItem TextSearchTrigger="TextChanged" />
<telerikPdfViewer:ZoomInToolbarItem />
<telerikPdfViewer:ZoomOutToolbarItem />
<telerikPdfViewer:FitToWidthToolbarItem/>
<telerikPdfViewer:ToggleLayoutModeToolbarItem/>
</telerikPdfViewer:RadPdfViewerToolbar>
<telerikPdfViewer:RadPdfViewer x:Name="pdfViewer" Grid.Row="1">
<telerikPdfViewer:RadPdfViewer.SearchSettings>
<telerikPdfViewer:SearchSettings>
<telerikPdfViewer:SearchSettings.TextSearchWorker>
<local:MultipleWordsSearchWorker />
</telerikPdfViewer:SearchSettings.TextSearchWorker>
</telerikPdfViewer:SearchSettings>
</telerikPdfViewer:RadPdfViewer.SearchSettings>
</telerikPdfViewer:RadPdfViewer>
</Grid>
 

See Also
 PdfViewer Toolbar
 Text Selection

1401
Telerik UI for Xamarin

Fonts
RadPdfViewer has a support for standard and embedded fonts.

Standard Fonts
There are 14 standard fonts that are not embedded in the document when you use them. As our
Xamarin PdfViewer works with the RadPdfProcessing model, these fonts can be accessed through
the PdfProcessing FontsRepository class.

You can find a full list of the provided standard fonts below:

 Helvetica
 Helvetica-Bold
 Helvetica-Oblique
 Helvetica-BoldOblique
 Courier
 Courier-Bold
 Courier-Oblique
 Courier-BoldOblique
 Times-Roman
 Times-Bold
 Times-Italic
 Times-BoldItalic
 Symbol
 ZapfDingbats

Embedded Fonts
All fonts, which are not included in the 14 standard ones should be embedded in the PDF document.
Otherwise, the result when the document is rendered is unpredictable as the PdfViewer renderer will
fallback to the default fonts.

Registering a Font
As RadPdfViewer for Xamarin works with RadPdfProcessing library model, you can utilize the
PdfProcessing's FontsRepository RegisterFont static method to embed various fonts, including
TrueType fonts. RegisterFont requires four parameters - FontFamily, FontStyle and FontWeight
objects describing the font and a byte array containing the raw font data.

Here are the needed steps to embed a non-standard font with PdfProcessing library:

Step 1: Add the .ttf file containing the font data to your Xamarin.Forms project, in the example below
it is placed inside Resources folder:

1402
Telerik UI for Xamarin

Make sure to update the Build Action of the .ttf file to Embedded resource.
 
Step 2: Add a sample implementation for reading the font data from a stream, for example:

C#
private static byte[] ReadAllBytes(Stream input)
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
 

Step 3: Embed the font through the RegisterFont method, here you need to use the above
mentioned ReadAllBytes method to read the font data and return it as a byte array:

C#
Assembly assembly = typeof(MainPage).Assembly;
Stream stream =
assembly.GetManifestResourceStream("SampleApp.Resources.SampleFont.ttf");
var fontData = ReadAllBytes(stream);
Telerik.Windows.Documents.Fixed.Model.Fonts.FontsRepository.RegisterFont(
new FontFamily("Verdana"), FontStyles.Normal, FontWeights.Normal, fontData);
 

Add the missing namespace related to the PdfProcessing library:

1403
Telerik UI for Xamarin

C#
using Telerik.Documents.Core.Fonts;
 

Result: RadPdfViewer will use thus registered font data when rendering text with the same font set.

See Also
 RadPdfProcessing library

1404
Telerik UI for Xamarin

Localization
PdfViewer for Xamarin provides language localization. In short, you can translate the used across
the PdfViewer control phrases to other languages, so that your app can be adapted to different
regions.

To learn in details about the localization process of Telerik UI for Xamarin components, please go
through the common Localization and Globalization topic.
 
In RadPdfViewer you can localize the following strings related to Text Search and Source Exception
Handling features:

Localization Key Default Value


PdfViewer_CopySelection Copy
PdfViewer_SearchedTextNotFound Not found
PdfViewer_Searching Searching
PdfViewer_SearchPlaceholder Find in document
PdfViewer_SourceExceptionMessage An error occurred while loading the document.

See Also
 Localization and Globalization
 Text Search
 Source Exception Handling

1405
Telerik UI for Xamarin

Source Exception Handling


In certain cases RadPdfViewer will not be able to load the passed Pdf document - it can be due to
invalid stream/inaccessible URL or some invalid data in the document itself. RadPdfViewer provides
a way to catch these cases through its SourceException event. In addition, you could show a
user-friendly message to the users through SourceExceptionTemplate.

Check the example below which shows how to use the RadPdfViewer API for handling source
exceptions.

First, define RadPdfViewer control and apply a SourceExceptionTemplate. The snippet below
demonstrates a sample template with only one Label which holds the message.

XAML
<telerikPdfViewer:RadPdfViewer x:Name="pdfViewer"
SourceException="PdfViewerSourceException">
<telerikPdfViewer:RadPdfViewer.SourceExceptionTemplate>
<DataTemplate>
<Label Text="Sorry, something with loading the pdf document went wrong."
TextColor="#404040"
HorizontalTextAlignment="Center"
VerticalTextAlignment="Center"
LineBreakMode="WordWrap" />
</DataTemplate>
</telerikPdfViewer:RadPdfViewer.SourceExceptionTemplate>
</telerikPdfViewer:RadPdfViewer>
 

Where the telerikPdfViewer namespace is the following:

XAML
xmlns:telerikPdfViewer="clr-namespace:Telerik.XamarinForms.PdfViewer;assembly=Telerik.
XamarinForms.PdfViewer"
 

And here is the SourceException event handler:

C#
private void PdfViewerSourceException(object sender, SourceExceptionEventArgs e)
{
var error = e.Exception.Message;
}
 

Check below how the defined SourceTemplateException looks:

1406
Telerik UI for Xamarin

A sample SourceExceptionTemplate example can be found in the PdfViewer/Features folder of the


SDK Samples Browser application.
 

See Also
 PdfViewer Toolbar

1407
Telerik UI for Xamarin

Commands
RadPdfViewer provides the following commands of type ICommand:

 ZoomInCommand
 ZoomOutCommand
 NavigateToNextPageCommand
 NavigateToPreviousPageCommand
 NavigateToPageCommand
 ToggleLayoutModeCommand: Triggers the RadPdfViewer LayoutModes (ContinuousScroll
and SinglePage)
 FitToWidthCommand: There are two options when executing FitToWidth command:
 FitDocumentToWidthCommand(the default one): Refers to the whole document; it would
lookup the widest of all pages and set a zoom level, so that this page is fit to width.

If the document has pages with different width, as a side effect, when you are currently
viewing a page that is not the widest, this page will not occupy the whole horizontal
space.
 

 FitPageToWidthCommand: It would execute fit to width on the current page disregarding


the width of other pages from the document.
 DoubleTappedCommand: This command is different from the above listed as it is triggered
from within the PdfViewer on double-tap action. On the first double-tap the document is
zoomed 2.5 times at the tapped location, another double-tap triggers FitToWidth command.

RadPdfViewer Toolbar exposes some of the commands built-in. For more information please check
the PdfViewer Toolbar article.
 

Example
Following is an example how the RadPdfViewer commands could be called on a button click action.
For the example we will visualize a pdf document from stream.

The snippet below shows one of the approaches for loading a pdf document inside RadPdfViewer
just for the purpose of the example. For more details on various ways for loading the document
check Key Features: Pdf Document Visualization topic.
 
First, add a pdf document to the project and set its build action to be EmbeddedResource.

Then, add the following code to visualize the document:

C#
Func<CancellationToken, Task<Stream>> streamFunc = ct => Task.Run(() =>
{
Assembly assembly = typeof(Commands).Assembly;

1408
Telerik UI for Xamarin

string fileName = assembly.GetManifestResourceNames().FirstOrDefault(n =>


n.Contains("pdfviewer-overview.pdf"));
Stream stream = assembly.GetManifestResourceStream(fileName);
return stream;
});
this.pdfViewer.Source = streamFunc;
 

Finally, use the following snippet to declare a RadPdfViewer in XAML and add a few buttons that will
execute the pdf viewer commands:

XAML
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<telerikCommon:RadUniformGrid>
<Button Text="Zoom In"
Command="{Binding Source={x:Reference pdfViewer}, Path=ZoomInCommand}" />
<Button Text="Zoom Out"
Command="{Binding Source={x:Reference pdfViewer}, Path=ZoomOutCommand}" />
<Button Text="Fit To Width"
Command="{Binding Source={x:Reference pdfViewer}, Path=FitToWidthCommand}" />
<Button Text="Previous Page"
Command="{Binding Source={x:Reference pdfViewer},
Path=NavigateToPreviousPageCommand}" />
<Button Text="Next Page"
Command="{Binding Source={x:Reference pdfViewer},
Path=NavigateToNextPageCommand}" />
</telerikCommon:RadUniformGrid>
<telerikPdfViewer:RadPdfViewer x:Name="pdfViewer"
Grid.Row="1"
MinZoomLevel="0.3"
MaxZoomLevel="4"/>
</Grid>
 

Where the telerikPdfViewer namespace is the following:

XAML
xmlns:telerikPdfViewer="clr-namespace:Telerik.XamarinForms.PdfViewer;assembly=Telerik.
XamarinForms.PdfViewer"
xmlns:telerikCommon="clr-namespace:Telerik.XamarinForms.Common;assembly=Telerik.Xamari
nForms.Common"
 

By default FitToWidth command of the PdfViewer is assigned to "Fit Document to Width" option. You
can easily switch to "Fit Page to Width" option by setting FitToWidthCommand property of
RadPdfViewer to FitPageToWidthCommand, check the snippet below:

C#

1409
Telerik UI for Xamarin

this.pdfViewer.FitToWidthCommand = new FitPageToWidthCommand();


 

In this way, calling the FitToWidthCommand on a button click action, as in the example above, will
execute "Fit Page to Width" on the current page.

A sample Commands example can be found in the PdfViewer/Features folder of the SDK Samples
Browser application.

You can directly explore the code in the SDK Samples Browser repository on GitHub.

See Also
 Key Features
 PdfViewer Toolbar

1410
Telerik UI for Xamarin

Overview
With Telerik Popup for Xamarin you could easily add modal popups to your application in order to
draw attention to important information or receive user input.

RadPopup lets you display content of your choice on top of existing view. The component provides a
flexible API to easily control its behavior and makes possible the implementation of complex logic for
a wide range of scenarios.

Key features
 Modal popups: You could define whether the popup will be modal or not; in both cases the UI
behind the popup gets inactive and cannot be used until the popup is closed. When you have
a modal popup, it will not be automatically closed when the user clicks outside. For more
details go to Modal Popup Support.
 Placement configuration: You could place the popup control at any position through various
settings such as placement mode, placement target and horizontal/vertical offsets. For more
information on this check Key Features: Placement Configuration section.
 Animation settings: RadPopup provides sleek customizable animation played while the
control is displayed/hidden, for additional info go to Key Features: Animation Settings.

Check out RadPopup Getting Started help article that shows how to use it in a basic scenario.

1411
Telerik UI for Xamarin

See Also
 Modal Popup Support
 Placement Configuration
 Animation Settings

1412
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadPopup control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadPopup control

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadPopup control you have to install the
Telerik.UI.for.Xamarin.Primitives nuget package. This nuget will automatically refer the
Telerik.UI.for.Xamarin.Common and Telerik.UI.for.Xamarin.SkiaSharp nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadPopup component:

Platform Assemblies
Portable Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Android Telerik.Xamarin.Android.Common.dll
Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
UWP Telerik.Core.dll
Telerik.UI.Xaml.Primitives.UWP.dll
Telerik.XamarinForms.Common.dll

1413
Telerik UI for Xamarin

Telerik.XamarinForms.Primitives.dll

3. Adding RadPopup control


You could use one of the following approaches:

Drag the control from the Toolbox.

Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML or C#.

The next example shows a sample RadPopup attached to a Button control. The purpose of the
Popup in this scenario is to receive user input - it contains RadRating control for allowing the user to
select a rating and a button for closing the popup.

Check below the Popup definition in XAML and in code-behind:

XAML
<Button HorizontalOptions="Center"
VerticalOptions="Start"
Text="Click here to rate"
Clicked="ShowPopup">
<telerikPrimitives:RadPopup.Popup>
<telerikPrimitives:RadPopup x:Name="popup"
IsModal="True"
OutsideBackgroundColor="#6F000000">
<telerikPrimitives:RadBorder CornerRadius="8"
BackgroundColor="Wheat">
<Grid Padding="20">
<Grid.RowDefinitions>
<RowDefinition Height="30" />
<RowDefinition Height="20" />
<RowDefinition Height="40" />
</Grid.RowDefinitions>
<Label Text="Please rate your experience" />
<telerikInput:RadShapeRating Grid.Row="1" />
<Button Grid.Row="2"
Padding="2"
HorizontalOptions="End"
Text="Send"
Clicked="ClosePopup" />
</Grid>
</telerikPrimitives:RadBorder>
</telerikPrimitives:RadPopup>
</telerikPrimitives:RadPopup.Popup>
</Button>

1414
Telerik UI for Xamarin

C#
var showPopupBtn = new Button { HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Start, Text = "Click here to rate" };
showPopupBtn.Clicked += ShowPopup;

popup = new RadPopup { IsModal = true, OutsideBackgroundColor =


Color.FromHex("#6F000000") };
popup.PlacementTarget = showPopupBtn;

var containerGrid = new Grid { Padding = 20 };


containerGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(30) });
containerGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(20) });
containerGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(40) });
containerGrid.Children.Add(new Label { Text = "Please rate your experience" });

var rating = new RadShapeRating();


rating.SetValue(Grid.RowProperty, 1);
containerGrid.Children.Add(rating);

var hidePopupBtn = new Button { Padding = new Thickness(2), HorizontalOptions =


LayoutOptions.End, Text = "Send" };
hidePopupBtn.SetValue(Grid.RowProperty, 2);
hidePopupBtn.Clicked += ClosePopup;
containerGrid.Children.Add(hidePopupBtn);

var border = new RadBorder { CornerRadius = new Thickness(8), BackgroundColor =


Color.Wheat };
border.Content = containerGrid;
popup.Content = border;
 

And here are the referenced event handlers:

C#
private void ClosePopup(object sender, EventArgs e)
{
popup.IsOpen = false;
}
private void ShowPopup(object sender, EventArgs e)
{
popup.IsOpen = true;
}
 

In addition to this, you need to add the following namespaces (telerikInput namespace is needed for
the Rating control used in the example, in general it's not required for RadPopup):

XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF

1415
Telerik UI for Xamarin

orms.Input"
 

C#
using Telerik.XamarinForms.Primitives;
using Telerik.XamarinForms.Input;
 

This is the result:

The presented example is available in Popup -> Getting Started folder of the SDK Browser application
.

You can directly explore the code in the SDKBrowser Examples repository on GitHub.

See Also
 Modal Popup Support
 Placement Configuration
 Animation Settings

1416
Telerik UI for Xamarin

Key Features
The purpose of this help article is to show you the key features of the RadPopup control.

Open / Close the popup


In order to show the RadPopup control you would need to set IsOpen property to True. By default
the popup stays open until the IsOpen property is set to False or the user taps outside in case of a
non-modal popup.

Setting Content
To host content inside RadPopup control you can either add it directly as a child element or use the
popup’s ContentTemplate property.

The example below demonstrates how you could create a sample DataTemplate and set it as
RadPopup ContentTemplate.

First, add the needed DataTemplate to the page Resources:

XAML
<ResourceDictionary>
<DataTemplate x:Key="PopupTemplate">
<telerikPrimitives:RadBorder CornerRadius="8"
BackgroundColor="#93D7FF"
WidthRequest="250"
Padding="10">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="30" />
<RowDefinition Height="50" />
<RowDefinition Height="30" />
</Grid.RowDefinitions>
<Label Text="ACCEPT TERMS" />
<Label Grid.Row="1"
Text="By checking this, you agree to the Terms of Service and Privacy Policy."
/>
<Button Grid.Row="2"
Padding="2"
HorizontalOptions="Start"
Text="Agree &amp; Continue"
Clicked="ClosePopup"
CornerRadius="6"
BackgroundColor="#7A9BFF"
TextColor="White"/>
</Grid>
</telerikPrimitives:RadBorder>
</DataTemplate>

1417
Telerik UI for Xamarin

</ResourceDictionary>
 

Then, when defining the RadPopup control either in XAML or code-behind, apply ContentTemplate
property:

XAML
<StackLayout Orientation="Horizontal" VerticalOptions="Start">
<telerikPrimitives:RadCheckBox x:Name="checkbox"
IsCheckedChanged="Checkbox_IsCheckedChanged">
<telerikPrimitives:RadPopup.Popup>
<telerikPrimitives:RadPopup x:Name="popup"
Placement="Bottom"
ContentTemplate="{StaticResource PopupTemplate}" />
</telerikPrimitives:RadPopup.Popup>
</telerikPrimitives:RadCheckBox>
<Label Text="Agree to the Terms &amp; Conditions"/>
</StackLayout>
 

Add the events as shown below:

C#
private void ClosePopup(object sender, EventArgs e)
{
popup.IsOpen = false;
}
private void Checkbox_IsCheckedChanged(object sender, IsCheckedChangedEventArgs e)
{
if (e.NewValue == true)
popup.IsOpen = true;
}
 

Here is the result:

1418
Telerik UI for Xamarin

Modal popup
You could define whether the popup will be modal or not through the IsModal Boolean property. In
both cases, the UI behind the popup gets inactive and cannot be used until the popup is closed. For
non-modal popups, however, you could easily focus on the content behind, by just clicking outside
the popup, thus hiding it.

Applying overlay color


OutsideBackgroundColor property lets you customize the color outside the popup. In most cases this
is used for modal popups to indicate the user cannot interact with the UI behind. The default value is
Color.Transparent.

The transparency of the overlay could be applied through the alpha channel of the chosen color. If
you're using a hexadecimal code, its format should be #AARRGGBB, where the first pair of letters,
the AA, represents the alpha channel.
 
Below is an example on how you could apply OutsideBackgroundColor to a modal popup.

XAML
<Button HorizontalOptions="Center"
VerticalOptions="Start"
BackgroundColor="#7A9BFF"
TextColor="White"
Text="Show modal popup"
Clicked="ShowPopup"
x:Name="button">

1419
Telerik UI for Xamarin

<telerikPrimitives:RadPopup.Popup>
<telerikPrimitives:RadPopup x:Name="popup"
IsModal="True"
OutsideBackgroundColor="#B3FFF493">
<telerikPrimitives:RadBorder
CornerRadius="6"
BackgroundColor="#93D7FF"
Padding="10">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="26" />
</Grid.RowDefinitions>
<Label Text="Telerik RadPopup for Xamarin" />
<Button Grid.Row="1"
Padding="2"
HorizontalOptions="Center"
Text="Close"
Clicked="ClosePopup"
CornerRadius="6"
BackgroundColor="#7A9BFF"
TextColor="White" />
</Grid>
</telerikPrimitives:RadBorder>
</telerikPrimitives:RadPopup>
</telerikPrimitives:RadPopup.Popup>
</Button>
 

And the needed event handlers used to show/hide the popup:

C#
private void ClosePopup(object sender, EventArgs e)
{
popup.IsOpen = false;
}
private void ShowPopup(object sender, EventArgs e)
{
popup.IsOpen = true;
}
 

Check the Popup with applied overlay color on different platforms below:

1420
Telerik UI for Xamarin

Placement Configuration
RadPopup provides a few useful properties which will help you position it per your preferences.

 PlacementTarget: Defines an element relative to which the popup is positioned when it is


open;
 Placement: Specifies the way the popup aligns to its placement target. Placement property is
of type PlacementMode and can be set to any of the Top, Right, Left, Bottom, Center or
Relative options where:
 Top, Right, Left, Bottom: aligns the popup control to the corresponding corner of the
placement target;
 Center: aligns the popup at the middle of the PlacementTarget;
 Relative: a position that aligns the top left corner of the popup with the top left corner of
the placement target.
 HorizontalOffset / VerticalOffset: Specifies the horizontal/vertical distance between the
placement target and the alignment point.

XAML
<Button HorizontalOptions="Center"
VerticalOptions="Start"
BackgroundColor="#7A9BFF"
TextColor="White"
Text="Show popup"
Clicked="ShowPopup"
x:Name="button">
<telerikPrimitives:RadPopup.Popup>
<telerikPrimitives:RadPopup x:Name="popup"
Placement="Bottom"

1421
Telerik UI for Xamarin

HorizontalOffset="20"
VerticalOffset="20">
<telerikPrimitives:RadBorder
WidthRequest="180"
CornerRadius="6"
BackgroundColor="#93D7FF"
BorderColor="#7A9BFF"
Padding="10">
<Label Text="With Telerik Popup for Xamarin you could easily add modal popups
to your application in order to draw attention to important information or receive
user input." />
</telerikPrimitives:RadBorder>
</telerikPrimitives:RadPopup>
</telerikPrimitives:RadPopup.Popup>
</Button>
 

C#
var myButton = new Button()
{
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.StartAndExpand,
BackgroundColor = Color.FromHex("#7A9BFF"),
TextColor = Color.White,
Text = "Show popup",
};

var popup = new RadPopup()


{
Placement = PlacementMode.Bottom,
HorizontalOffset = 20,
VerticalOffset = 20,
PlacementTarget = myButton
};

myButton.Clicked += ((sender, args) => { popup.IsOpen = true; });

popup.Content = new RadBorder()


{
WidthRequest = 180,
CornerRadius = new Thickness(6),
BackgroundColor = Color.FromHex("#93D7FF"),
BorderColor = Color.FromHex("#7A9BFF"),
Padding = new Thickness(10),
Content = new Label() { Text= "With Telerik Popup for Xamarin you could easily add
modal popups to your application in order to draw attention to important information
or receive user input."}
};

this.Content = new Grid()


{
Margin = new Thickness(10),
Children = { myButton }
};

1422
Telerik UI for Xamarin

Here is the Button Clicked event handler:

C#
private void ShowPopup(object sender, EventArgs e)
{
popup.IsOpen = true;
}
 

In the XAML example RadPopup is defined inline through RadPopup.Popup attached property
applied to the Button control, so the Button is considered as PlacementTarget of the popup. If you
create the Popup with code, PlacementTarget property should be explicitly set.
 
Here is the result:

If you need to center the popup when it is declared in XAML, attach it to the Page element and set
its Placement property to "Center".
 

Animation Settings
RadPopup provides two built-in animations played when the popup is shown/hidden. You could
apply the animation through AnimationType property which exposes the following options:

 None (use it to disable the animation)

1423
Telerik UI for Xamarin

 Fade
 Zoom

The default AnimationType is Fade.

You could also customize the duration and easing (acceleration over time) through
AnimationDuration (in ms) and AnimationEasing (of type Xamarin.Forms.Easing) properties. The
default duration is 300ms and the default easing is Easing.Linear.

See Also
 Getting Started

1424
Telerik UI for Xamarin

Overview
RadRating is UI component that allows users to intuitively rate by selecting number of items [stars]
from a predefined number of items.

Figure 1: RadRating Overview

Key features
 Predefined rating shapes: RadRating provides several simple shapes such as star, circle and
diamond, that can be used for rating items out of the box. Read Shape Rating topic for
additional info.
 Customizing shapes: You could take advantage of the control’s flexible API for customizing
the appearance of the predefined shapes.
 Custom items template support: The Rating component for Xamarin provides two templates
options for normal state and selected state, allowing you to achieve the desired look and
feel. For more details go to the Templated Rating topic.

See Also
 Getting Started

1425
Telerik UI for Xamarin

Getting Started
This example will guide you through the steps needed to add a basic RadRating control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadRating control

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadShapeRating control you have to install the
Telerik.UI.for.Xamarin.Input nuget package. This nuget will automatically refer the
Telerik.UI.for.Xamarin.Primitives, Telerik.UI.for.Xamarin.Common, and
Telerik.UI.for.Xamarin.DataControls nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadRating component:

Platform Assemblies
Portable Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.SkiaSharp.dll
Android Telerik.Xamarin.Android.Common.dll
Telerik.Xamarin.Android.Data.dll
Telerik.Xamarin.Android.Input.dll
Telerik.Xamarin.Android.List.dll
Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.SkiaSharp.dll
iOS Telerik.XamarinForms.Common.dll

1426
Telerik UI for Xamarin

Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.SkiaSharp.dll
UWP Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.SkiaSharp.dll
RadRating is rendered via the SkiaSharp graphics library so you need to install also
SkiaSharp.Views.Forms in all projects of the Xamarin solution (.Net Standard/Shared, Android, iOS,
etc).
 

3. Adding RadRating control


If your app is correctly set, you are ready to add a RadRating control within your page.

The simplest and fastest way to include the control is by simply defining it like this in XAML /
code-behind:

XAML
<telerikInput:RadShapeRating x:Name="rating" />
 

C#
var layout = new StackLayout();
layout.Children.Add(new RadShapeRating());
this.Content = layout;
 

In addition to this you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

C#
using Telerik.XamarinForms.Input;
 

By default the control is defined in a way that five stars will be visualized and none of them will be
selected. The screenshot below shows the control with selection applied:

1427
Telerik UI for Xamarin

SDK Browser and QSF applications contain different examples that show RadRating's main
features. You can find the applications in the Examples and QSF folders of your local Telerik UI for
Xamarin installation.
 

See Also
 Key Features

1428
Telerik UI for Xamarin

Key Features
RadRating is presented by two components named RadShapeRating and RadTemplatedRating in
order to provide various visualizations of the rating functionality.

This topic gives and overview of the key features of the Rating component that are common for both
RadShapeRating and RadTemplatedRating.

RadShapeRating and RadTemplatedRating inherit from the RatingBase abstract class that provides
their common features.
 

Rating Value
RadRating exposes a Value property that is used to set and read the number of the selected rating
items.

XAML
<telerikInput:RadShapeRating Value="4" />
 

Read-only Mode
RadRating supports read-only mode in which the end user cannot change its Value (the number of
the selected items). You could enable the read-only mode through IsReadOnly property:

XAML
<telerikInput:RadShapeRating Value="4"
IsReadOnly="True" />
 

Configuration Settings
 ItemsCount: Defines the number of the items that are visualized in the rating control. The
default value is 5 items;
 ItemsSpacing: Specifies the distance between the separate items in pixels. Default value is
10px;

XAML
<telerikInput:RadShapeRating Value="4"
ItemsCount="7"
ItemsSpacing="20" />
 

Events

1429
Telerik UI for Xamarin

RadRating provides the following event:

 ValueChanged: Occurs whenever Value property is changed. The ValueChanged event


handler receives two parameters:
 The sender argument which is of type object, but can be cast to RadShapeRating or
RadTemplatedRating type;
 А ValueChangedEventArgs object which exposes both old and new values of the Value
property.

See Also
 RadShapeRating
 RadTemplatedRating

1430
Telerik UI for Xamarin

Shape Rating
RadShapeRating component is designed to be used in the simplest scenarios where an ordinary
rating component is required. This control allows easy customization of the colors and shape of the
default rating item.

Shape Types
RadShapeRating exposes ItemShape property of type RadPathGeometry which is used to define the
shape of the rating items.

For easy and fast setup RadRating includes several simple shapes that can be used for rating items
out of the box. This is accomplished through the static Geometries class which resides in the
Telerik.XamarinForms.Primitives.SkiaSharp.Rating namespace. This class exposes static properties
that return predefined shapes.

For more details on RadPath and RadPathGeometry check the documentation here: RadPath
Overview.
 
Here is how each of the geometries can be used:

 Star (default)

XAML
<telerikInput:RadShapeRating x:Name="rating1" />
 

 Circle

XAML
<telerikInput:RadShapeRating ItemShape="{x:Static telerikInput:Geometries.Circle}"
x:Name="rating2" />
 

 Diamond

XAML
<telerikInput:RadShapeRating ItemShape="{x:Static telerikInput:Geometries.Diamond}"
x:Name="rating3" />
 

1431
Telerik UI for Xamarin

 Heart

XAML
<telerikInput:RadShapeRating ItemShape="{x:Static telerikInput:Geometries.Heart}"
x:Name="rating4" />
 

 Custom RadPathGeometry Shape:

XAML
<telerikInput:RadShapeRating x:Name="rating5">
<telerikInput:RadShapeRating.ItemShape>
<telerikCommon:RadPathGeometry>
<telerikCommon:RadPathFigure StartPoint="0, 1">
<telerikCommon:RadLineSegment Point="1, 1" />
<telerikCommon:RadLineSegment Point="0.5, 0" />
<telerikCommon:RadLineSegment Point="0, 1" />
</telerikCommon:RadPathFigure>
</telerikCommon:RadPathGeometry>
</telerikInput:RadShapeRating.ItemShape>
</telerikInput:RadShapeRating>
 

where telerikCommon namespace is defined like this:

XAML
xmlns:telerikCommon="clr-namespace:Telerik.XamarinForms.Common;assembly=Telerik.Xamari
nForms.Common"
 

Shapes Styling
You can control the visual appearance of the predefined shapes through the following styling
settings:

 ItemFill (Color): Specifies the color used to fill the rating item.
 ItemStroke (Color): Defines the color used by the border around the geometry.
 ItemStrokeThickness (double): Sets the width of the border around the geometry.
 SelectedItemFill (Color): Defines the color used to fill the selected rating item.
 SelectedItemStroke (Color): Sets the color used by the border around the selected geometry.

1432
Telerik UI for Xamarin

 SelectedItemStrokeThickness (double): Specifies the width of the border around the selected
geometry.

XAML
<telerikInput:RadShapeRating x:Name="rating"
ItemFill="YellowGreen"
ItemStroke="YellowGreen"
SelectedItemFill="Pink"
SelectedItemStroke="Red" />
 

See Also
 Key Features
 Templated Rating

1433
Telerik UI for Xamarin

Templated Rating
RadTemplatedRating component is designed to be used in the cases where it is easier to provide a
template (e.g. just an image) for the rating items instead of creating custom RadPathGeometry. On
top of the common Rating API this component adds the following members:

 ItemTemplate (DataTemplate): Defines the template used in the rating item.


 SelectedItemTemplate (DataTemplate): Specifies the template used in the selected rating
item.

Both templates should be set in order the control to function as expected.


 
Here is how the rating component can be setup:

XAML
<telerikInput:RadTemplatedRating ValueChanged="RadTemplatedRating_ValueChanged">
<telerikInput:RadTemplatedRating.ItemTemplate>
<DataTemplate>
<Image Source="unread.png" />
</DataTemplate>
</telerikInput:RadTemplatedRating.ItemTemplate>
<telerikInput:RadTemplatedRating.SelectedItemTemplate>
<DataTemplate>
<Image Source="success.png" />
</DataTemplate>
</telerikInput:RadTemplatedRating.SelectedItemTemplate>
</telerikInput:RadTemplatedRating>
 

Check the result in the image below:

See Also
 Key Features
 Shape Rating

1434
Telerik UI for Xamarin

Overview
Telerik RichTextEditor for Xamarin enables users to create rich textual content through a
What-You-See-Is-What-You-Get (WYSIWYG) interface. It delivers a set of tools for creating, editing,
and formatting of text, paragraphs, lists, hyperlinks and more, and outputs the modified content as
standard HTML.

Figure 1: RadRichTextEditor Overview

Key Features
 Visualize HTML content: RadRichTextEditor can display HTML content that includes
paragraphs, formatted text, images, tables, ordered and unordered lists, and more.
 Rich text editing features: The control comes with various editing capabilities:
 Text formatting such as bold, italic, underline and strikethrough;
 Font manipulations such as size, family, text color and text background color;
 Bulleted and numbered lists;
 Text selection;
 Hyperlinks manipulations - create, edit and remove hyperlinks;
 Subscript and superscript formatting;
 Indentation and content alignment;
 Undo/Redo editing actions.

1435
Telerik UI for Xamarin

 Various HTML source options: You can load the HTML source from a string as well as from a
stream. Read more about this in the Key Features article.
 Commands Support: RichTextEditor exposes commands, such as ToggleBoldCommand,
ToggleBulletingCommand, AlignRightCommand, etc, that allow you to execute rich text
editing actions over the loaded into the editor content. For detailed information on the matter
check Commands article.
 Insert and Edit Images Support: You can easily insert images and use the built-in edit
images operations like resize, cut, copy, paste, remove. Read more about this in Working
with Images article.
 RichTextEditor Toolbar: Take advantage of a pre-defined UI automatically wired with all of
the commands provided by the control through built-in functionality. For more details check
the RadRichTextEditor Toolbar article.
 Custom Toolbar: The RadRichTextEditor Toolbar can be fully customized. You could
populate the toolbar with the ToolbarItems needed for editing the HTML content. Read more
about this in RichTextEditor Custom Toolbar.
 Customizable Context Menu: RichTextEditor comes with a built-in context menu support
which shows common operations such as Copy and Paste for sharing data between the
apps or within the app. For more details check Context Menu topic.
 Flexible Styling API: You can easily modify the visual appearance of RadRichTextEditor as
well as the toolbar items through various styling properties such as BackgroundColor, Border
Color and Thickness, CornerRadius, and more. Go to RichTextEditor Styling and
RichTextEditor Toolbar Styling topics for detailed information on this.

Check out RadRichTextEditor Getting Started help article that shows how to use it in a basic
scenario.
 

See Also
 Getting Started

1436
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RichTextEditor control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RichTextEditor control
 Loading HTML Content

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the complete Telerik.UI.for.Xamarin nuget package, you have the option to
add a separate nuget package. For RichTextEditor control you have to install the
Telerik.UI.for.Xamarin.RichTextEditor nuget package. This nuget will automatically refer the
Telerik.UI.for.Xamarin.Common, Telerik.UI.for.Xamarin.DataControls and
Telerik.UI.for.Xamarin.Primitives nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadRichTextEditor component:

Platform Assemblies
Portable Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.RichTextEditor.dll
Telerik.XamarinForms.SkiaSharp.dll
Android Telerik.Xamarin.Android.Common.dll
Telerik.Xamarin.Android.Data.dll
Telerik.Xamarin.Android.List.dll
Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataControls.dll

1437
Telerik UI for Xamarin

Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.RichTextEditor.dll
Telerik.XamarinForms.SkiaSharp.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.RichTextEditor.dll
Telerik.XamarinForms.SkiaSharp.dll
UWP Telerik.Core.dll
Telerik.Data.dll
Telerik.UI.Xaml.Controls.Data.UWP.dll
Telerik.UI.Xaml.Input.UWP.dll
Telerik.UI.Xaml.Primitives.UWP.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.RichTextEditor.dll
Telerik.XamarinForms.SkiaSharp.dll

3. Adding RichTextEditor control


You could use one of the following approaches:

Drag the control from the Toolbox.

Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML.

The snippet below shows how you can add RadRichTextEditor together with RichTextEditorToolbar:

XAML
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<telerikRichTextEditor:RadRichTextEditorToolbar x:Name="richTextToolbar"
RichTextEditor="{x:Reference richTextEditor}" />
<telerikRichTextEditor:RadRichTextEditor x:Name="richTextEditor" Grid.Row="1" />
</Grid>
 

In addition to this, you need to add the following namespace:

1438
Telerik UI for Xamarin

XAML
xmlns:telerikRichTextEditor="clr-namespace:Telerik.XamarinForms.RichTextEditor;assembl
y=Telerik.XamarinForms.RichTextEditor"
 

RadRichTextEditor relies on WebView for rendering HTML content. There are some limitations for
placing WebView on the page which are valid for RichTextEditor as well:

 Nesting RadRichTextEditor inside ScrollView control is not supported. RadRichTextEditor


provides its own scrolling mechanism.
 When the RadRichTextEditor is placed inside a StackLayout, you would need to set explicitly
its WidthRequest and HeightRequest properties, otherwise the control will not render. This is
due to the fact that StackLayout usually wants to size itself according to its children, but a
WebView (since it does scrolling) wants to size itself to its parent. You can learn more about
this in the Xamarin.Forms WebView documentation.

You should either use a Grid as a parent container or define explicitly the size of the RichTextEditor
control.

4. Loading HTML Content


With RichTextEditor users can create and edit HTML content. In some cases you may need to load
formatted text in advance - this can be achieved through the Source property of the control:

C#
var htmlSource = @"<h4>One of the Most Beautiful Islands on Earth - Tenerife</h4>
<p><strong>Tenerife</strong> is the largest and most populated island of the
eight <a href='https://en.wikipedia.org/wiki/Canary_Islands' target='_blank'>Canary
Islands</a>.</p>
<p style='color:#808080'>It is also the most populated island of
<strong>Spain</strong>, with a land area of <i>2,034.38 square kilometers</i> and
<i>904,713</i> inhabitants, 43% of the total population of the <strong>Canary
Islands</strong>.</p>";
this.richTextEditor.Source = RichTextSource.FromString(htmlSource);
 

This is the result:

1439
Telerik UI for Xamarin

See Also
 Key Features
 Commands
 RichTextEditor Toolbar

1440
Telerik UI for Xamarin

Key Features
The purpose of this help article is to show you the key features of the RadRichTextEditor control.

HTML Source options


RichTextEditor exposes Source property of type RichTextSource used to load HTML content into the
editor from a string as well as from a stream.

You can directly assign a string (containing HTML) as a Source of the editor - RadRichTextEditor
will properly display the HTML content through the implemented in RichTextSource implicit
converter. Check a simple example on this below:

C#
this.richTextEditor.Source = "<b>Hello World!</b>";
 

Load HTML from a string


You can easily load the HTML content from a string by using the static FromString method of the
RichTextSource class and assigning the result to the Source property of RadRichTextEditor:

C#
var htmlSource = @"<h4>One of the Most Beautiful Islands on Earth - Tenerife</h4>
<p><strong>Tenerife</strong> is the largest and most populated island of the
eight <a href='https://en.wikipedia.org/wiki/Canary_Islands' target='_blank'>Canary
Islands</a>.</p>
<p style='color:#808080'>It is also the most populated island of
<strong>Spain</strong>, with a land area of <i>2,034.38 square kilometers</i> and
<i>904,713</i> inhabitants, 43% of the total population of the <strong>Canary
Islands</strong>.</p>";
this.richTextEditor.Source = RichTextSource.FromString(htmlSource);
 

Alternatively, you can create a RichTextHtmlStringSource object and assign it to the Source property
of the RichTextEditor.

Load HTML from a stream


Another option to preload HTML is by retrieving it from a stream through the static FromStream
method of the RichTextSource and again, assign the result to the Source property of the
RichTextEditor:

C#
Func<CancellationToken, Task<Stream>> streamFunc = ct => Task.Run(() =>
{
Assembly assembly = typeof(KeyFeatures).Assembly;

1441
Telerik UI for Xamarin

string fileName = assembly.GetManifestResourceNames().FirstOrDefault(n =>


n.Contains("richtexteditor-htmlsource.html"));
Stream stream = assembly.GetManifestResourceStream(fileName);
return stream;
});

this.richTextEditor.Source = RichTextSource.FromStream(streamFunc);
 

In the example the HTML file is loaded as an EmbeddedResource


 
Alternatively, you can create a RichTextHtmlStreamSource object and set it as the Source of the
RichTextEditor.

Retrieving HTML Content


Through GetHtmlAsync method of RadRichTextEditor you can obtain the created and updated inside
the editor HTML content:

C#
var htmlString = await this.richTextEditor.GetHtmlAsync();
 

RichText Editing Capabilities


RichTextEditor will help app users create and edit HTML content. You can apply provided by
RichTextEditor editing features through the built-in UI, namely RadRichTextEditorToolbar, or you can
create custom UI and manually execute the RadRichTextEditor Commands.

In addition, RichTextEditor provides flexible API to apply formatting at the current caret position or on
the selected text inside the editing area.

 TextFormatting (of type RichTextFormatting): Defines the text formatting, such as heading,
paragraph or quotation of the text at the current position or selection.
 TextColor: Specifies the color of the text at the current position or selection;
 HighlightTextColor: Defines the text background color at the current position or selection;
 SelectionRange (of type RichTextSelectionRange): Specifies the start and end position of the
currently selected inside the editor text.
 FontSize: Sets the font size of the text at the current caret position or selection;
 FontAttributes (of type RichTextFontAttributes): Defines the font attributes, such as bold, italic,
subscript and superscript at the current position or selection;
 TextDecorations (of type RichTextDecorations): Specifies text decorations, such as underline
and strikethrough at the current position or selection;
 HorizontalTextAlignment (of type RichTextHorizontalAlignment): Specifies the text alignment,
such as left, right, center or justify at the current position or selection;
 ListType (of type RichTextListType): Specifies the list type, such as numbered or bulleted list
at the current position or selection.

Text Selection

1442
Telerik UI for Xamarin

RichTextEditor supports text selection functionality - the end user can initiate a selection action
through the tap and hold gesture over the text. The selected text is marked with a different
background color and two drag handles are available to the user to make it easier to modify the
current selection.

In addition, as soon as the selection is made on Android and iOS, RichTextEditor displays a
customizable ContextMenu with a few default commands. For more details on this go to Context
Menu topic.

You can take advantage of the following API related to text selection:

 GetSelectionAsync method - returns asynchronously a RichTextSelection object which


defines the current text selection inside the editor (null if there is no text selection). The
RichTextSelection object contains the Text itself as well as the Start and End position of
the text characters;

Hyperlink Support
RichTextEditor provides built-in support for creating and managing hyperlinks (hyperlinks are
presented with the RichTextHyperlink class). Through the exposed commands related to hyperlinks,
namely ApplyHyperlinkCommand, RemoveHyperlinkCommand, and OpenHyperlinkCommand, users
can manipulate the hyperlinks inside the RichTextEditor content.

In addition, RichTextEditorToolbar exposes predefined toolbar items wired to the hyperlink


commands. For more details on this check RichTextEditor Custom Toolbar topic.

You can also take advantage of the following API related to hyperlinks:

 GetHyperlinkAsync method - returns asynchronously a RichTextHyperlink under the caret in


the editor (or null in case there is no hyperlink). The RichTextHyperlink object contains
the Url and Title of the link;

Hyperlink Error Handling


In case users try to open invalid urls (for example, the url is not absolute, the domain does not exist
or is incomplete, etc) the following message is shown by default indicating there is an error with the
url:

You can override the default behavior by handling the RichTextEditor's OpenHyperlinkError event:

 OpenHyperlinkError event - raised when users try to open invalid urls in the editor. The

1443
Telerik UI for Xamarin

OpenHyperlinkError event handler receives two parameters:


 The Sender which is the RichTextEditor control;
 OpenHyperlinkErrorEventArgs provides the following properties:
 Error - of type System.Exception, can be used to get the exact error message;
 Url - of type string, defining the url of the hyperlink;
 Handled - boolean property indicating whether the event is handled.

Subscribe to the event, set Handled property of the event args to True to prevent the default
message and add custom implementation.

Here is a quick example on the OpenHyperlinkError event usage:

XAML
<telerikRichTextEditor:RadRichTextEditor x:Name="richTextEditor"
OpenHyperlinkError="RichTextEditor_OpenHyperlinkError"
Grid.Row="1" />
 

And the event handler which shows a custom message:

C#
private void RichTextEditor_OpenHyperlinkError(object sender,
OpenHyperlinkErrorEventArgs e)
{
e.Handled = true;
Application.Current.MainPage.DisplayAlert(string.Format("Error opening {0}",
e.Url), e.Error.Message, "Ok");
}
 

Here is the custom message:

Working With Images


You can easily add insert, delete, copy, paste, cut, edit images in the editor using the predefined
toolbar items. For more details please check Workin with Images article.

Read-Only State
IsReadOnly(bool) property of the RichTextEditor indicating whether the control is in a read-only

1444
Telerik UI for Xamarin

mode. Setting IsReadOnly="True" means that the Toolbar Items will be disabled, the content of
the document cannot be changed and no selection can be performed. The default the value is
False.

Example
For the example we will trigger the IsReadOnly State using a Switch. Here is the XAML Definition:

XAML
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<StackLayout VerticalOptions="Center" HorizontalOptions="Center"
Orientation="Horizontal">
<Label Text="IsReadOnly State:" TextColor="Black" FontSize="20"/>
<Switch IsToggled="{Binding IsReadOnly, Source={x:Reference richTextEditor}}"/>
</StackLayout>
<telerikRichTextEditor:RadRichTextEditor x:Name="richTextEditor"
IsReadOnly="True"
Grid.Row="1" />
<telerikRichTextEditor:RadRichTextEditorToolbar x:Name="richTextToolbar"
IsVisible="{Binding IsReadOnly, Source={x:Reference richTextEditor},
Converter={StaticResource invertedBooleanConverter}}"
RichTextEditor="{x:Reference richTextEditor}"
Grid.Row="2" />
</Grid>
 

For the example we will use a converter to hide the Toolbar when the control is in read-only state:

XAML
<telerikCommon:InvertedBooleanConverter x:Key="invertedBooleanConverter" />
 

defining the Source of the RichTextEditor:

C#
Func<CancellationToken, Task<Stream>> streamFunc = ct => Task.Run(() =>
{
Assembly assembly = typeof(ReadOnlyState).Assembly;
string fileName = assembly.GetManifestResourceNames().FirstOrDefault(n =>
n.Contains("richtexteditor-htmlsource.html"));
Stream stream = assembly.GetManifestResourceStream(fileName);
return stream;
});

this.richTextEditor.Source = RichTextSource.FromStream(streamFunc);
 

1445
Telerik UI for Xamarin

The richtexteditor-htmlsource.html file is visualized in the Editor as an EmbeddedResource.


 
The sample Read-Only State demo can be found in our SDK Browser Application.

See Also
 RichTextEditor Toolbar
 Commands
 Context Menu

1446
Telerik UI for Xamarin

RichTextEditor Toolbar
RadRichTextEditor control comes with various editing capabilities and with the help of the
RadRichTextEditorToolbar you can provide to the users easy and quick way to edit their HTML
content. The default toolbar include items for all the available text formatting options, alternatively
you could customize the shown editing options according to your needs.

By default the RadRichTextEditorToolbar Items are auto-populated. You could change this by setting
the RadRichTextEditorToolbar boolean AutoGenerateItems property to False. In this case you will
need to manually define the available editing options, for more details check Custom Toolbar article.

In order to attach the RichTextEditor control to the RadRichTextEditorToolbar control you need to set
the RichTextEditor (from type RadRichTextEditor) property. All toolbar items execute their actions
against the specified richtext editor.

XAML
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<telerikRichTextEditor:RadRichTextEditorToolbar x:Name="richTextToolbar"
RichTextEditor="{x:Reference richTextEditor}" />
<telerikRichTextEditor:RadRichTextEditor x:Name="richTextEditor" Grid.Row="1" />
</Grid>
 

RadRichTextEditorToolbar is horizontally scrollable, so that the toolbar items can be easily accessed
- you can control this by setting IsScrollable boolean property (by default it is True).

In addition, an OverflowButton is available in the toolbar on the right to enable opening a menu area
with additional toolbar items. If you'd like to customize the toolbar and manually define the toolbar
items, you can define what toolbar items should be located in that menu area.

1447
Telerik UI for Xamarin

RichTextEditor Toolbar Placement


There are some specifics you'd need to take into account when placing RichTextEditorToolbar on
the page:

 On Android - when you place the RichTextEditor Toolbar below the RichTextEditor, you will
need to set the Application WindowSoftInputModeAdjust to Resize - this setting causes the
page to resize when the keyboard is shown and in this way if the RichTextEditorToolbar is on
the bottom of the page it will be displayed over the keyboard when it appears.

You can apply it on application level like this:

C#
App.Current.On<Android>().UseWindowSoftInputModeAdjust(WindowSoftInputModeAdjust.Resiz
e);
 

For more details on the matter check the Soft Keyboard Input Mode on Android from Xamarin
documentation.
 

 on iOS - if the RadRichTextEditorToolbar is positioned under the keyboard, when the


keyboard shows, the control is translated over the keyboard, so users can access it without a
problem. Due to Xamarin.Forms implementation, it is important that the
RadRichTextEditorToolbar is placed in a container which bounds would still contain it after
the control is translated over the keyboard. Otherwise, the Tap and Pan gestures on the
RadRichTextEditorToolbar will not work until the keyboard is hidden and the control is
translated back to its original place.

See Also
 Key Features
 Commands

1448
Telerik UI for Xamarin

RichTextEditor Custom Toolbar


By default the RadRichTextEditorToolbar Items are auto-populated. You could change this by setting
the RadRichTextEditorToolbar boolean AutoGenerateItems property to False. In this case you will
need to manually define and arrange the toolbar items per your needs.

RichTextEditor ToolbarItem
All predefined toolbar items derive from a common RichTextEditorToolbarItem which exposes
some useful configuration as well as styling properties, such as:

 Text and Description - when the toolbar is placed inside the main toolbar area only the Text
is shown, but when in the menu area – both Text and Description are shown.
 IsOverflowItem (bool): Identifies a toolbar item as an OverflowButton. In case you'd like to
add some toolbar items inside additional area that can be open from an overflow button,
create a RichTextEditorToolbarItem instance, set its IsOverflowItem to True and add
toolbar items to it.
 IsChecked (bool): Indicates whether the toolbar item is checked; more toolbar items can be
checked at the same time, for example, both ItalicToolbarItem and BoldToolbarItem can be
checked;
 IsSelected (bool): Indicates whether the toolbar item is selected, only one toolbar item can
be selected at a time;

Predefined Toolbar Items


RadRichTextEditorToolbar contains a bunch of predefined toolbar items used to execute the editing
features over the content. Below you will find a complete list of the predefined toolbar items grouped
according to their type:

 Checkable Toolbar items - these items remain checked and apply the formatting over the
text under the caret or the selected text:
 AlignCenterToolbarItem
 AlignJustifyToolbarItem
 AlignLeftToolbarItem
 AlignRightToolbarItem
 BoldToolbarItem
 BulletingToolbarItem
 ItalicToolbarItem
 NumberingToolbarItem
 StrikethroughToolbarItem
 SubscriptToolbarItem
 SuperscriptToolbarItem
 UnderlineToolbarItem
 Action Toolbar items - execute the concrete action over the current position or selection:
 ClearFormattingToolbarItem
 IndentToolbarItem
 OutdentToolbarItem

1449
Telerik UI for Xamarin

 RedoToolbarItem
 UndoToolbarItem
 CutToolbarItem
 CopyToolbarItem
 PastePlainTextToolbarItem
 Picker Toolbar items - open picker controls for choosing color, font, etc and apply it at the
current position or selection:
 ColorPickerToolbarItem
 FontFamilyToolbarItem
 FontSizeToolbarItem
 HighlightTextColorToolbarItem
 TextColorToolbarItem
 TextFormattingToolbarItem

Check below how the ColorPickerToolbarItem, for example, looks when the picker is open:

 Hyperlink Toolbar item - toolbar item for managing hyperlinks:


 AddHyperlinkToolbarItem - used to create hyperlinks; in addition contains child toolbar
items for editing, removing and opening hyperlinks, namely EditHyperlinkToolbarItem,
RemoveHyperlinkToolbarItem and OpenHyperlinkToolbarItem;

In order to create hyperlinks, users need to select text and use the AddHyperlinkToolbarItem - a
popup with a field for entering URL will be displayed:

1450
Telerik UI for Xamarin

If the caret is over an existing hyperlink, tapping on the AddHyperlinkToolbarItem will replace the
current toolbar items with the AddHyperlinkToolbarItem child items:

BackButton is shown inside the RichTextEditorToolbar whenever there is a


RichTextEditorToolbarItem with nested toolbar items to provide a way to return to the main toolbar.

OpenHyperlink toolbar item opens a browser and navigates to the respective URL address.

 Add Image Toolbar item - toolbar item for adding images:


 AddImageToolbarItem: used for adding images.
 EditImage Toolbar item
 EditImageToolbarItem: used for image resizing. In addition the toolbar allows you to pick
an image if you haven't selected one.
 RemoveImage Toolbar item
 RemoveImageToolbarItem: used for removing the currently selected image from the
editor.

For more details review Insert and Edit Images article.

Example

1451
Telerik UI for Xamarin

If you'd like to choose what toolbar items to be shown inside the toolbar as well as their order and
arrangement, you would need to set AutoGenerateItems to False and add the items manually:

XAML
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<telerikRichTextEditor:RadRichTextEditor x:Name="richTextEditor" />
<telerikRichTextEditor:RadRichTextEditorToolbar x:Name="richTextToolbar"
Grid.Row="1"
RichTextEditor="{x:Reference richTextEditor}"
AutoGenerateItems="False">
<telerikRichTextEditor:FontFamilyToolbarItem />
<telerikRichTextEditor:FontSizeToolbarItem />
<telerikRichTextEditor:BoldToolbarItem />
<telerikRichTextEditor:AlignLeftToolbarItem />
<telerikRichTextEditor:TextColorToolbarItem />
<telerikRichTextEditor:BulletingToolbarItem />
<telerikRichTextEditor:NumberingToolbarItem />
<telerikRichTextEditor:IndentToolbarItem />
<telerikRichTextEditor:OutdentToolbarItem />
<telerikRichTextEditor:TextFormattingToolbarItem />
<telerikRichTextEditor:ClearFormattingToolbarItem />
<telerikRichTextEditor:RichTextEditorToolbarItem IsOverflowItem="true"
Description="More Text Formatting">
<telerikRichTextEditor:RichTextEditorToolbarItem.Items>
<telerikRichTextEditor:BoldToolbarItem HorizontalOptions="Start"/>
<telerikRichTextEditor:ItalicToolbarItem HorizontalOptions="Start" />
<telerikRichTextEditor:UnderlineToolbarItem HorizontalOptions="Start" />
<telerikRichTextEditor:SubscriptToolbarItem HorizontalOptions="Start" />
<telerikRichTextEditor:SuperscriptToolbarItem HorizontalOptions="Start" />
<telerikRichTextEditor:StrikethroughToolbarItem HorizontalOptions="Start" />
</telerikRichTextEditor:RichTextEditorToolbarItem.Items>
</telerikRichTextEditor:RichTextEditorToolbarItem>
<telerikRichTextEditor:AddHyperlinkToolbarItem IsOverflowItem="True"/>
</telerikRichTextEditor:RadRichTextEditorToolbar>
</Grid>
 

And here is the result:

1452
Telerik UI for Xamarin

See Also
 Key Features
 Commands

1453
Telerik UI for Xamarin

Overview
From R3 2021 release of Telerik UI for Xamarin the RichTextEditor control allows you to add(insert),
cut, copy, paste, resize and delete images using built-in toolbar items.

1454
Telerik UI for Xamarin

 AddImageToolbarItem(RichTextEditorToolbarItem): allows you to add an image - the


RichTextEditor PickImage event is fired, so you can handle the logic for selecting an image.
 EditImageToolbarItem(InsertImageToolbarItem): allows you to resize the image. In
addition the toolbar allows you to pick an image (the RichTextEditor.PickImage event is
fired) if you haven't selected one. Check Edit Image ToolbarItem for more details.
 CutToolbarItem(RichTextEditorToolbarItem): allows you to cut the selected HTML/image
to the clipboard.
 CopyToolbarItem(RichTextEditorToolbarItem): allows you to copy the selected
HTML/image to the clipboard.
 PasteHtmlToolbarItem(RichTextEditorToolbarItem): allows you to paste HTML/image
from the clipboard.
 RemoveImageToolbarItem(RichTextEditorToolbarItem): allows you to remove the currently
selected image from the document.

1455
Telerik UI for Xamarin

You can insert images from Uri, Data(byte []), Stream, File. The image source is of type
RichTextImageSource.

 RichTextImageSource FromData(byte[] data, RichTextImageType type)


 RichTextImageSource FromFile(string path)
 RichTextImageSource FromFile(string path, RichTextImageType type)
 RichTextImageSource FromStream(Stream stream, RichTextImageType type)
 RichTextImageSource FromStream(Func<Stream> stream, RichTextImageType
type)
 RichTextImageSource FromStream(Func<Task<Stream>> stream,
RichTextImageType type)
 RichTextImageSource FromStream(Func<CancellationToken, Task<Stream>>
stream, RichTextImageType type)
 RichTextImageSource FromUrl(string uri)

Also you have to point out the image format type. The supported image format types(of type
RichTextImageType) are:

 Gif
 Jpeg
 Png
 Svg
 Webp

Permissions if adding images from gallery


If you want to work with images from the device gallery, then you have to grant permissions. Check
below for more details about the needed permissions per platform.
 
Add images using the predefined toolbar items - AddImageToolbarItem and
EditImageToolbarItem. Both toolbar items provide a way to pick an image - with
AddImageToolbarItem directly, while with EditImageToolbarItem users have the option to
select a new image from the additional dialog (go to Edit Image ToolbarItem for more details) - in both
cases the RichTextEditor PickImage event is fired. You need to manually implement the logic for
selecting an image inside the PickImage event handler.

Check below a sample implementation of handling the PickImage event and providing the option for
the end user to select an image from the device gallery.

The RichTextEditor definition in XAML and the Toolbar definition:

XAML
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<telerikRichTextEditor:RadRichTextEditorToolbar x:Name="richTextToolbar"
RichTextEditor="{x:Reference richTextEditor}" />

1456
Telerik UI for Xamarin

<telerikRichTextEditor:RadRichTextEditor x:Name="richTextEditor" Grid.Row="1"


PickImage="OnPickImage"/>
</Grid>
 

The PickImage event handler with implementation to get permissions to access photos and media
on the device:

C#
private async void OnPickImage(object sender, PickImageEventArgs eventArgs)
{
var mediaPlugin = CrossMedia.Current;

if (mediaPlugin.IsPickPhotoSupported)
{
if (!await PermissionsHelper.RequestPhotosAccess())
{
return;
}

if (!await PermissionsHelper.RequestStorrageAccess())
{
return;
}

var mediaFile = await mediaPlugin.PickPhotoAsync();

if (mediaFile != null)
{
var imageSource = RichTextImageSource.FromFile(mediaFile.Path);
eventArgs.Accept(imageSource);
return;
}
}
 

The PermissionHelper class definition:

C#
internal static class PermissionsHelper
{
internal static async Task<bool> RequestStorrageAccess()
{
var currentStatus = await
CrossPermissions.Current.CheckPermissionStatusAsync<StoragePermission>();
if (currentStatus != PermissionStatus.Granted)
{
var status = await
CrossPermissions.Current.RequestPermissionAsync<StoragePermission>();
return status == PermissionStatus.Granted;
}
else
{

1457
Telerik UI for Xamarin

return true;
}
}

internal static async Task<bool> RequestPhotosAccess()


{
var currentStatus = await
CrossPermissions.Current.CheckPermissionStatusAsync<PhotosPermission>();
if (currentStatus != PermissionStatus.Granted)
{
var status = await
CrossPermissions.Current.RequestPermissionAsync<PhotosPermission>();
return status == PermissionStatus.Granted;
}
else
{
return true;
}
}
}
 

The Plugin.Permission NuGet package is requred.

Load HTML file:

C#
Func<CancellationToken, Task<Stream>> streamFunc = ct => Task.Run(() =>
{

Assembly assembly = typeof(InsertImages).Assembly;


string fileName = assembly.GetManifestResourceNames().FirstOrDefault(n =>
n.Contains("PickYourHoliday.html"));
Stream stream = assembly.GetManifestResourceStream(fileName);
return stream;
});

this.richTextEditor.Source = RichTextSource.FromStream(streamFunc);
 

1458
Telerik UI for Xamarin

The demo uses the Xam.Plugin.Media nuget package for all projects - .NET Standard, Android, iOS,
UWP. In addition for .NET Standard and Android projects - Plugin.Permissions NuGet package is
installed.

Permissions for Android


In MainActivity.cs inside the OnCreate method initialize the Plugin.Media:

C#
Plugin.Media.CrossMedia.Current.Initialize();
 

In MainActivity.cs override the OnRequestPermissionsResult method

C#
public override void OnRequestPermissionsResult(int requestCode, string[] permissions,
[GeneratedEnum] Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions,
grantResults);

1459
Telerik UI for Xamarin

Plugin.Permissions.PermissionsImplementation.Current.OnRequestPermissionsResult(reques
tCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
 

Permissions for iOS


Inside the Info.plist file add the following code to grant permissions to access the device gallery

xml
<key>NSPhotoLibraryUsageDescription</key>
<string>This app needs access to photos.</string>
<key>NSPhotoLibraryAddUsageDescription</key>
<string>This app needs access to the photo gallery.</string>
 

Events
 PickImage: Raised when the user has requested to pick an image in the RadRichTextEditor.
The PickImage event handler receives two parameters:
 The sender which is the RichTextEditor control;
 PickImageEventArgs provides the following methods:
 Accept - Invoke this method when the user has picked an image. Recieves one
paramerter imagesource of type RichTextImageSource (Specifies the
RichTextImageSource for the picked image);
 Cancel - Invoke this method when the user has cancelled the operation;
 InsertImageError: Raised when trying to insert an image in the RadRichTextEditor. The
InsertImageError event handler receives two parameters:
 The sender which is the RichTextEditor control;
 InsertImageErrorEventArgs provides the following methods:
 Source - of type RichTextImageSource. The property allows you to get the source of
the image (read-only property).
 Error - of type Exception. Specifies the exception that is raised when image cannot
be inserted.
 IsImageSelectedChanged: Raised when an image inside the editor is selected. The
IsImageSelectedChanged event handler receives two parameters:
 The sender which is the RichTextEditor control;
 RadValueChangedEventArgs<bool> provides NewValue and OldValue properties of
type bool, indicating the IsImageSelected property change.

Methods
 GetImageAsync method returns asynchronously an object of type RichTextImage which
represents the current selected image (or null in case there is no image). The RichTextImage
object contains the Source, Title, Width and Height of the image;

1460
Telerik UI for Xamarin

Commands
 InsertImageCommand(ICommand): uses for inserting images in the editor. The command
takes a single parameter of type RichTextImage. The RichTextImage object contains the
source, title, width, height of the image. If you do not set width and height explicitly, the
image will be added with its original size.
 RemoveImageCommand(ICommand): uses for removing images from the editor.

See Also
 Key Features
 RadRichTextEditor Toolbar
 Commands

1461
Telerik UI for Xamarin

Toolbar Items for Working With Images


In this article we will review the built-in toolbar items for insert and edit images.

Insert Images
 AddImageToolbarItem

Default look of the AddImageToolbarItem:

Built-in Toolbar Items for editing images


The following Built-in Toolbar itema are displayed in the RichTextEditorToolbar when image is
selected:

 EditImageToolbarItem(InsertImageToolbarItem): allows you to resize the image. In


addition the toolbar allows you to pick an image (using the PickButton) if you haven't
selected one.
 CutToolbarItem(RichTextEditorToolbarItem): allows you to cut the selected HTML/image
to the clipboard.
 CopyToolbarItem(RichTextEditorToolbarItem): allows you to copy the selected
HTML/image to the clipboard.
 PasteHtmlToolbarItem(RichTextEditorToolbarItem): allows you to paste HTML/image
from the clipboard.
 RemoveImageToolbarItem(RichTextEditorToolbarItem): allows you to remove the currently
selected image from the document.

1462
Telerik UI for Xamarin

How the editing toolbar looks when image is selected:

Edit Image ToolbarItem


EditImageToolbarItem allows you to resize the image and pick an image. When tapping on the
EditImageToolbarItem, a dialog is displayed.

 Text(string): Defines the Edit Icon Text


 HeaderText(string): Defines the header text value. Default string Image
 PickButtonText(string): Defines the text of the button that allows you to pick images. Note
that PickImage event is raised when PickButton(of type Xamarin.Forms.Button) is
pressed.
 ResizeLabelText(string): Defines the text of the Resize Xamarin.Forms.Label. Default value

1463
Telerik UI for Xamarin

Resize:
 MinimumLabelText(string): Defines the text of the Minimum Xamarin.Forms.Label. Default
value 0%
 MaximumLabelText(string): Defines the text of the Maximum Xamarin.Forms.Label. Default
value 100%
 OkButtonText(string): Defines the text for Ok button. Default value Ok
 CancelButtonText(string): Defines the text for Cancel button. Default value: Cancel
 PopupContentStyle(Style): Defines the Style applied to the popup content.
 PopupOutsideBackgroundColor(Color): Defines the backgrounf color applied outside of the
popup content.
 PopupContentTemplate(ControlTemplate): Defines the control template of the popup.

Insert Images example can be found inside the SDK Browser App - RichTextEditor/Features folder
 

ImagePickerToolbar Item
 ImagePickerToolbarItem(Telerik.XamarinForms.RichTextEditor.PickerToolbarItem): Allows
you to pick an image from a collection of pre-defined images.

1464
Telerik UI for Xamarin

Example
RichTextEditor Definition in XAML and the Toolbar definition:

XAML
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<telerikRichTextEditor:RadRichTextEditor x:Name="richTextEditor"/>
<telerikRichTextEditor:RadRichTextEditorToolbar x:Name="richTextToolbar"
Grid.Row="1"
RichTextEditor="{x:Reference richTextEditor}"
AutoGenerateItems="False">
<telerikRichTextEditor:ImagePickerToolbarItem x:Name="imagePicker"/>
<telerikRichTextEditor:FontFamilyToolbarItem />
<telerikRichTextEditor:FontSizeToolbarItem />
<telerikRichTextEditor:BoldToolbarItem />
<telerikRichTextEditor:ItalicToolbarItem/>

1465
Telerik UI for Xamarin

<telerikRichTextEditor:UnderlineToolbarItem />
</telerikRichTextEditor:RadRichTextEditorToolbar>
</Grid>
 

Add the namespace:

XAML
xmlns:telerikRichTextEditor="clr-namespace:Telerik.XamarinForms.RichTextEditor;assembl
y=Telerik.XamarinForms.RichTextEditor"
 

Add Images inside the ImagePickerToolbarItem ItemsSource:

C#
private void InitializeImages()
{
var resourceNames = this.currentAssembly.GetManifestResourceNames();
var imageSources = new List<RichTextImageSource>();

foreach (var resourceName in resourceNames)


{
if (resourceName.Contains("emoji"))
{
var imageSource = RichTextImageSource.FromStream(() =>
this.currentAssembly.GetManifestResourceStream(resourceName),
RichTextImageType.Png);

imageSources.Add(imageSource);
}
}

this.imagePicker.ItemsSource = imageSources;
}
 

Call the InitializeImages inside the page's constructor:

C#
InitializeImages();
 

Set the RichTextEditor Source:

C#
Func<CancellationToken, Task<Stream>> streamFunc = ct => Task.Run(() =>
{
string fileName = this.currentAssembly.GetManifestResourceNames().FirstOrDefault(n
=> n.Contains("pick-image-demo.html"));
Stream stream = this.currentAssembly.GetManifestResourceStream(fileName);
return stream;

1466
Telerik UI for Xamarin

});

this.richTextEditor.Source = RichTextSource.FromStream(streamFunc);
 

Custom Image Picker example can be found inside the SDK Browser App - RichTextEditor/Features
folder
 

See Also
 Key Features
 RadRichTextEditor Toolbar
 Commands

1467
Telerik UI for Xamarin

Context Menu
With R1 2021 release RichTextEditor comes with a built-in context menu support which shows
common operations such as Copy and Paste for sharing data between the apps or within the app.
The context menu is triggered on tap and hold gesture (right-button click on UWP) over the editor
content. On Android and iOS it is also displayed as soon as the user performs selection.

The default context menu shows the following options:

 Cut - cuts the selected content and saves it in the system clipboard;
 Copy - copies the selected content and saves it in the clipboard;
 Paste - pastes the content from the clipboard into the editor;
 Paste as Plain Text - pastes the content from the clipboard stripping any additional
formatting;
 Select All - selects all of the content in the editor;

What options are available in the context menu depends on the current content selection or caret
position in the editor.

Check below a few examples of the RichTextEditor Context Menu.

 in case of content selection, all the default options are available:

 in case the context menu is shown over the current caret position (through tap and hold
gesture on empty space inside the editor), only Paste, Paste as Plan Text and Select All
options are available:

1468
Telerik UI for Xamarin

Custom Context Menu


You can easily modify the RichTextEditor default Context Menu and add or remove some of the
provided options. Just need to set AutoGenerateContextMenu property of the RichTextEditor to
False and manually define the ContextMenuItems. You can choose from the predefined
ContextMenuItems or create a CustomContextMenuItem instance and define its Title and
Command (the Command can be bound to any of the RadRichTextEditor's Commands or to a
custom command).

Here is a list of the predefined ContextMenuItems:

 BoldContextMenuItem
 CopyContextMenuItem
 CutContextMenuItem
 ItalicContextMenuItem
 OpenHyperlinkContextMenuItem
 PasteContextMenuItem
 PastePlainTextContextMenuItem
 SelectAllContextMenuItem

Following is an example how the RichTextEditor Context Menu can be customized by using some of
the predefined items as well as adding two CustomContextMenuItem instances - the first wired to
the RichTextEditor's ToggleUnderlineCommand and the second wired to a custom command
imlemented in the ViewModel:

XAML
<telerikRichTextEditor:RadRichTextEditor x:Name="richTextEditor"
AutoGenerateContextMenu="False"
Grid.Row="1">
<telerikRichTextEditor:RadRichTextEditor.ContextMenuItems>
<telerikRichTextEditor:BoldContextMenuItem />
<telerikRichTextEditor:ItalicContextMenuItem />
<telerikRichTextEditor:OpenHyperlinkContextMenuItem Title="Navigate" />

1469
Telerik UI for Xamarin

<telerikRichTextEditor:CustomContextMenuItem Title="Underline"
Command="{Binding Source={x:Reference richTextEditor},
Path=ToggleUnderlineCommand}"/>
<telerikRichTextEditor:CustomContextMenuItem Title="Info"
Command="{Binding Source={x:Reference richTextEditor},
Path=BindingContext.CustomInfoCommand}"
CommandParameter="{Binding Source={x:Reference richTextEditor},
Path=SelectionRange}"/>

</telerikRichTextEditor:RadRichTextEditor.ContextMenuItems>
</telerikRichTextEditor:RadRichTextEditor>
 

Add the required namespace:

XAML
xmlns:telerikRichTextEditor="clr-namespace:Telerik.XamarinForms.RichTextEditor;assembl
y=Telerik.XamarinForms.RichTextEditor"
 

Add the ViewModel class with the CustomInfoCommand:

C#
public class ViewModel
{
public ViewModel()
{
this.CustomInfoCommand = new Command(this.CustomInfoCommandExecute);
}

private void CustomInfoCommandExecute(object param)


{
var selectionRange = (RichTextSelectionRange) param;
Application.Current.MainPage.DisplayAlert("Info", string.Format("Selection
starts at {0} to {1} position.", selectionRange.Start, selectionRange.End), "Ok");
}

public ICommand CustomInfoCommand { get; set; }


}
 

And set it as a BindingContext of the page:

C#
this.BindingContext = new ViewModel();
 

Here is the result:

1470
Telerik UI for Xamarin

A sample CustomContextMenu example can be found in the RichTextEditor/Features folder of the


SDK Samples Browser application.
 

See Also
 Commands
 RadRichTextEditor Toolbar

1471
Telerik UI for Xamarin

Localization
RichTextEditor for Xamarin provides language localization. In short, you can translate the used
across the RichTextEditor Toolbar Items texts to other languages, so that your app can be adapted
to different regions.

To learn in details about the localization process of Telerik UI for Xamarin components, please go
through the common Localization and Globalization topic.
 

Common RichTextEditor Localization strings


Localization Key Default Value
RichTextEditor_AddHyperlink Hyperlink
RichTextEditor_AddImage Image
RichTextEditor_AlignCenter Center Text
RichTextEditor_AlignJustify Justify Text
RichTextEditor_AlignLeft Align to Left
RichTextEditor_AlignRight Align to Right
RichTextEditor_Bold Bold
RichTextEditor_ClearFormatting Clear Formatting
RichTextEditor_Copy Copy
RichTextEditor_Cut Cut
RichTextEditor_DecreaseIndent Decrease Indent
RichTextEditor_EditHyperlink Edit Hyperlink
RichTextEditor_EditImage Edit Image
RichTextEditor_FontColor Font color
RichTextEditor_FontFamily Font
RichTextEditor_FontSize Font Size
RichTextEditor_FontStyles Styles
RichTextEditor_Heading1 Heading 1
RichTextEditor_Heading2 Heading 2
RichTextEditor_Heading3 Heading 3
RichTextEditor_Heading4 Heading 4

1472
Telerik UI for Xamarin

RichTextEditor_Heading5 Heading 5
RichTextEditor_Heading6 Heading 6
RichTextEditor_HighlightColor Highlight color
RichTextEditor_HyperlinkCancelButtonText Cancel
RichTextEditor_HyperlinkHeaderText Link
RichTextEditor_HyperlinkOkButtonText Ok
RichTextEditor_HyperlinkTitleLabelText Link Title:
RichTextEditor_HyperlinkTitlePlaceholderText Additional Info
RichTextEditor_HyperlinkUrlLabelText URL:
RichTextEditor_HyperlinkUrlPlaceholderText http://www....
RichTextEditor_ImageCancelButtonText Cancel
RichTextEditor_ImageHeaderText Image
RichTextEditor_ImageMaximumLabelText 100%
RichTextEditor_ImageMinimumLabelText 0%
RichTextEditor_ImageOkButtonText Ok
RichTextEditor_ImageResizeLabelText Resize:
RichTextEditor_IncreaseIndent Increase Indent
RichTextEditor_InsertImageErrorHeaderText Error
RichTextEditor_InsertImageErrorOKButtonTex OK
t
RichTextEditor_InsertImageErrorText Cannot insert image from the specified
location.
RichTextEditor_Italic Italic
RichTextEditor_OpenHyperlink Open Hyperlink
RichTextEditor_OrderedList Ordered Indent
RichTextEditor_Paragraph Paragraph
RichTextEditor_Quotation Quotation
RichTextEditor_Paste Paste
RichTextEditor_PastePlainText Paste as Plain Text
RichTextEditor_Redo Redo
RichTextEditor_RemoveHyperlink Remove Hyperlink
RichTextEditor_RemoveImage Remove Image
RichTextEditor_PickImage Pick Image

1473
Telerik UI for Xamarin

RichTextEditor_Strike Strike
RichTextEditor_Subscript Subscript
RichTextEditor_Superscript Superscript
RichTextEditor_Underline Underline
RichTextEditor_Undo Undo
RichTextEditor_UnorderedList Unordered List

See Also
 Localization and Globalization

1474
Telerik UI for Xamarin

Commands
RadRichTextEditor provides the following commands of type ICommand:

 UndoCommand
 RedoCommand
 CutCommand
 CopyCommand
 PasteCommand
 ToggleBoldCommand
 ToggleItalicCommand
 ToggleUnderlineCommand
 ToggleStrikethroughCommand
 ToggleSubscriptCommand
 ToggleSuperscriptCommand
 ToggleBulletingCommand
 ToggleNumberingCommand
 SelectAllCommand
 ClearFormattingCommand
 AlignLeftCommand
 AlignRightCommand
 AlignCenterCommand
 AlignJustifyCommand
 IndentCommand
 OutdentCommand
 ApplyHyperlinkCommand
 RemoveHyperlinkCommand
 OpenHyperlinkCommand
 InsertImageCommand
 RemoveImageCommand

RadRichTextEditor Toolbar exposes some of the commands built-in. For more information please
check the RadRichTextEditor Toolbar article.
 

Example
Through the provided commands you can execute the corresponding actions over RichTextEditor
(for example apply bold text formatting) from a custom UI other than the RichTextEditor toolbar.

Following is an example how the RadRichTextEditor commands could be called on a button click
action.

Let's add the RichTextEditor definition together with a few sample buttons wired to the editor's
commands:

XAML

1475
Telerik UI for Xamarin

<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<telerikCommon:RadUniformGrid>
<Button Text="Bold"
Command="{Binding Source={x:Reference richTextEditor}, Path=ToggleBoldCommand}"
/>
<Button Text="Italic"
Command="{Binding Source={x:Reference richTextEditor},
Path=ToggleItalicCommand}" />
<Button Text="Underline"
Command="{Binding Source={x:Reference richTextEditor},
Path=ToggleUnderlineCommand}" />
<Button Text="Bullet List"
Command="{Binding Source={x:Reference richTextEditor},
Path=ToggleBulletingCommand}" />
<Button Text="Numbered List"
Command="{Binding Source={x:Reference richTextEditor},
Path=ToggleNumberingCommand}" />
</telerikCommon:RadUniformGrid>
<telerikRichTextEditor:RadRichTextEditor x:Name="richTextEditor" Grid.Row="1" />
</Grid>
 

Add the required namespaces:

XAML
xmlns:telerikCommon="clr-namespace:Telerik.XamarinForms.Common;assembly=Telerik.Xamari
nForms.Common"
xmlns:telerikRichTextEditor="clr-namespace:Telerik.XamarinForms.RichTextEditor;assembl
y=Telerik.XamarinForms.RichTextEditor"
 

Now text formatting and creating lists can be executed over the editor through the sample buttons:

A sample Commands example can be found in the RichTextEditor/Features folder of the SDK
Samples Browser application.
 

See Also
 RadRichTextEditor Toolbar

1476
Telerik UI for Xamarin

Events
RadRichTextEditor component exposes the following events:

 OpenHyperlinkError: Raised when users try to open invalid urls in the editor. The
OpenHyperlinkError event handler receives two parameters:
 The Sender which is the RichTextEditor control;
 OpenHyperlinkErrorEventArgs provides the following properties:
 Error - of type System.Exception, can be used to get the exact error message;
 Url - of type string, defining the url of the hyperlink;
 Handled - boolean property indicating whether the event is handled.
 IsReadOnlyChanged: Raised when read-only mode of the RichTextEditor is switched. The
IsReadOnlyChanged event receives two parameters:
 The Sender which is the RichTextEditor control;
 RadValueChangedEventArgs<bool> provides NewValue and OldValue properties of
type bool, indicating the IsReadOnly property change.
 FontFamilyChanged: Raised when the FontFamily property of the RichTextEditor is
modified. The FontFamilyChanged event handler receives two parameters:
 The Sender which is the RichTextEditor control;
 RadValueChangedEventArgs<string> provides NewValue and OldValue properties of
type string, indicating the FontFamily property change.
 FontSizeChanged: Raised when the FontSize property of the RichTextEditor is modified.
The FontSizeChanged event handler receives two parameters:
 The Sender which is the RichTextEditor control;
 RadValueChangedEventArgs<RichTextUnit> provides NewValue and OldValue
properties of type RichTextUnit, indicating the FontFamily property change.
 FontAttributesChanged: Raised when the FontAttributes, such as bold, italic, subscript
and superscript is modified. The FontAttributesChanged event handler receives two
parameters:
 The Sender which is the RichTextEditor control;
 RadValueChangedEventArgs<RichTextFontAttributes> provides NewValue and
OldValue properties of type RichTextFontAttributes, indicating the FontAttributes
property change.
 TextDecorationsChanged: Raised when the TextDecorations, such as underline and
strikethrough is modified. The TextDecorationsChanged event handler receives two
parameters:
 The Sender which is the RichTextEditor control;
 RadValueChangedEventArgs<RichTextDecorations> provides NewValue and OldValue
properties of type RichTextDecorations, indicating the TextDecorations property change.
 TextFormattingChanged: Raised when the TextFormatting, such as such as heading,
paragraph or quotation is modified. The TextFormattingChanged event handler receives two
parameters:
 The Sender which is the RichTextEditor control;
 RadValueChangedEventArgs<RichTextFormatting> provides NewValue and OldValue
properties of type RichTextFormatting, indicating the TextFormatting property change.
 HorizontalTextAlignmentChanged: Raised when the HorizontalTextAlignment, such as
left, right, center or justify is modified. The HorizontalTextAlignmentChanged event handler

1477
Telerik UI for Xamarin

receives two parameters:


 The Sender which is the RichTextEditor control;
 RadValueChangedEventArgs<RichTextHorizontalAlignment> provides NewValue and
OldValue properties of type RichTextHorizontalAlignment, indicating the
HorizontalTextAlignment property change.
 ListTypeChanged: Raised when the ListType, such as numbered or bulleted list is
modified. The ListTypeChanged event handler receives two parameters:
 The Sender which is the RichTextEditor control;
 RadValueChangedEventArgs<RichTextListType> provides NewValue and OldValue
properties of type RichTextListType, indicating the ListType property change.
 TextColorChanged: Raised when the TextColor property of the RichTextEditor is updated.
The TextColorChanged event handler receives two parameters:
 The Sender which is the RichTextEditor control;
 RadValueChangedEventArgs<Color> provides NewValue and OldValue properties of
type Color, indicating the TextColor property change.
 HighlightTextColorChanged: Raised when the HighlightTextColor property of the
RichTextEditor is updated. The HighlightTextColorChanged event handler receives two
parameters:
 The Sender which is the RichTextEditor control;
 RadValueChangedEventArgs<Color> provides NewValue and OldValue properties of
type Color, indicating the HighlightTextColor property change.
 SelectionRangeChanged: Raised when the SelectionRange, which defines the start and
end position of the currently selected inside the editor text, is updated. The
SelectionRangeChanged event handler receives two parameters:
 The Sender which is the RichTextEditor control;
 RadValueChangedEventArgs<RichTextSelectionRange> provides NewValue and
OldValue properties of type RichTextSelectionRange, indicating the SelectionRange
property change.
 IsHyperlinkSelectedChanged: Raised when a hyperlink inside the editor is selected. The
IsHyperlinkSelectedChanged event handler receives two parameters:
 The Sender which is the RichTextEditor control;
 RadValueChangedEventArgs<bool> provides NewValue and OldValue properties of
type bool, indicating the IsHyperlinkSelected property change.

See Also
 Key Features
 RadRichTextEditor Toolbar
 Commands

1478
Telerik UI for Xamarin

RichTextEditor Styling
RadRichTextEditor provides means for modifying its visual appearance, so that it matches the style
of the app.

You can take advantage of the following styling properties:

 BackgroundColor(Color): Specifies background color of the editor area.


 BorderColor(Color): Defines the border color around the editor.
 BorderThickness(Thickness): Defines the border thickness around the editor.
 CornerRadius (Thickness): Defines corner radius of the border.

Example
Here is a quick example how you can apply the listed properties:

XAML
<telerikRichTextEditor:RadRichTextEditor x:Name="richTextEditor"
BackgroundColor="#FFFFEA"
BorderThickness="1"
BorderColor="#007F0E"
CornerRadius="15" />
 

This is the result:

1479
Telerik UI for Xamarin

See Also
 RichTextEditor Toolbar Styling
 Custom Toolbar

1480
Telerik UI for Xamarin

RichTextEditor Toolbar Styling


Through the provided flexible styling API you can completely customize the lоок & feel of the
RichTextEditor Toolbar and its toolbar items, so that the toolbar matches the style of your app.

RadRichTextEditorToolbar exposes the following styling properties:

 ItemSpacing(double): Specifies the extra spacing between items horizontal direction. The
default value is 4.
 BackgroundColor: Defines the background color of the toolbar;
 BorderThickness and BorderColor: Set the toolbar border styling;

To customize the OverflowButton used to open additional menu area, use the following properties of
RadRichTextEditorToolbar:

 OverflowButtonText
 OverflowButtonTextColor
 OverflowButtonBorderColor
 OverflowButtonBorderThickness
 OverflowButtonFontFamily
 OverflowButtonTemplate(DataTemplate): Specifies the template of the overflow button;
 OpenOverflowButtonTextColor: Specifies the text color of the overflow button when it is
tapped and the additional menu area is shown;
 OpenOverflowButtonBackgroundColor: Sets the background color of the overflow button
when it is tapped and the menu area is shown.
 OverflowPopupBackgroundColor: Defines the background color of the menu area that is
shown when the overflow button is tapped;

Here is a screenshot showing styled OverflowButton:

RadRichTextEditorToolbar provides the option to create a RichTextEditorToolbarItem with


nested toolbar items - in this case tapping on the RichTextEditorToolbarItem will replace the current
toolbar items with its nested toolbar items. In addition, there is a BackButton added on the left to
provide easy access to the main toolbar. You can customize the BackButton through the following
properties of the RichTextEditorToolbar:

 BackButtonFontFamily
 BackButtonTextColor

1481
Telerik UI for Xamarin

 BackButtonText

Check below an example of toolbar item with nested items and BackButton:

RichTextEditor Toolbar Items Styling


RichTextEditorToolbarItem exposes the following styling properties:

 TextColor, CheckedColor, SelectedColor: Define the toolbar item text color according to the
item state;
 BackgroundColor, CheckedBackgroundColor and SelectedBackgroundColor: Define the
toolbar item background color according to the item state;
 Font settings - FontSize, FontFamily and FontAttributes;

You can also customize the PickerToolbarItems used in the toolbar such as ColorPickerToolbarItem,
FontFamilyToolbarItem, etc. PickerToolbarItem provides the following styling properties:

 ItemStyle and SelectedItemStyle: Modify the picker items' style in regular and selected state,
accordingly. You would need to use
telerikDataControls:NonVirtualizedItemsControlItemContainer as the TargetType of the
ItemStyle properties;
 PopupContentSyle and PopupContentHeight: Allow you to customize the popup that is
displayed when tapping on a PickerToolbarItem. The TargetType of PopupContentSyle
should be telerikRichTextEditor:PopupContentView.

In addition, hyperlink toolbar items provide customization options, such as:

 PopupContentStyle: Defines the style of the popup for creating/editing hyperlinks. The target
type of this Style should be telerikRichTextEditor:HyperlinkPopupContentView;
 PopupOutsideBackgroundColor: Sets the background behind the popup, so that it is clear
the content outside is currently inactive.

When creating a Style for the AddHyperlinkToolbarItem, you should set as target type
telerikRichTextEditor:InsertHyperlinkToolbarItem - this is needed as AddHyperlinkToolbarItem
contains nested toolbar items, all of the derive from InsertHyperlinkToolbarItem and in this way the
style will affect the nested items as well.

Example
You will need to declare Styles in the ResourceDictionary of the page and set TargetType properties
to be of type telerikRichTextEditor:RadRichTextEditorToolbar for the toolbar and
telerikRichTextEditor:RichTextEditorToolbarItem - for the items.

1482
Telerik UI for Xamarin

In order to apply the style to all toolbar items you should set the Style.ApplyToDerivedTypes property
to True. In this way each style with target type RichTextEditorToolbarItem will affect the
predefined toolbar items.
 
The example below uses Telerik Font Icons as Text for some of the toolbar items - this requires to
include into the application the Telerik Font ttf file and use it as a reference to the FontFamily
properties. For detailed instructions on this check Telerik Font Icons topic.
 
The example below shows how you can customize the RichTextEditorToolbar as well as the
RichTextEditorToolbarItems.

First, let's add the RichTextEditorToolbar definition:

XAML
<telerikRichTextEditor:RadRichTextEditorToolbar RichTextEditor="{x:Reference
richTextEditor}"
Grid.Row="1"
AutoGenerateItems="False">
<telerikRichTextEditor:FontFamilyToolbarItem />
<telerikRichTextEditor:FontSizeToolbarItem />
<telerikRichTextEditor:BoldToolbarItem />
<telerikRichTextEditor:AlignLeftToolbarItem />
<telerikRichTextEditor:TextColorToolbarItem />
<telerikRichTextEditor:BulletingToolbarItem />
<telerikRichTextEditor:NumberingToolbarItem />
<telerikRichTextEditor:IndentToolbarItem />
<telerikRichTextEditor:OutdentToolbarItem />
<telerikRichTextEditor:TextFormattingToolbarItem />
<telerikRichTextEditor:ClearFormattingToolbarItem />
<telerikRichTextEditor:RichTextEditorToolbarItem IsOverflowItem="true"
Text="&#xE808;"
FontFamily="{StaticResource IconsFont}"
Description="More Text Formatting">
<telerikRichTextEditor:RichTextEditorToolbarItem.Items>
<telerikRichTextEditor:BoldToolbarItem HorizontalOptions="Start"/>
<telerikRichTextEditor:ItalicToolbarItem HorizontalOptions="Start" />
<telerikRichTextEditor:UnderlineToolbarItem HorizontalOptions="Start" />
<telerikRichTextEditor:SubscriptToolbarItem HorizontalOptions="Start" />
<telerikRichTextEditor:SuperscriptToolbarItem HorizontalOptions="Start" />
<telerikRichTextEditor:StrikethroughToolbarItem HorizontalOptions="Start" />
</telerikRichTextEditor:RichTextEditorToolbarItem.Items>
</telerikRichTextEditor:RichTextEditorToolbarItem>
<telerikRichTextEditor:AddHyperlinkToolbarItem IsOverflowItem="True"/>
</telerikRichTextEditor:RadRichTextEditorToolbar>
 

Then add the Styles in the Resources of the page :

XAML
<ResourceDictionary>
<OnPlatform x:TypeArguments="x:String" x:Key="IconsFont">
<On Platform="iOS">telerikfontexamples</On>

1483
Telerik UI for Xamarin

<On Platform="Android">Fonts/telerikfontexamples.ttf#telerikfontexamples</On>
<On
Platform="UWP">/Assets/Fonts/telerikfontexamples.ttf#telerikfontexamples</On>
</OnPlatform>
<Color x:Key="ToolbarColor">#007F0E</Color>
<Style TargetType="telerikRichTextEditor:RichTextEditorToolbarItem"
x:Key="RichTextEditorToolbarItemStyle">
<Setter Property="TextColor" Value="{StaticResource ToolbarColor}"/>
<Setter Property="SelectedBackgroundColor" Value="{StaticResource
ToolbarColor}"/>
<Setter Property="SelectedColor" Value="White"/>
<Setter Property="CheckedBackgroundColor" Value="{StaticResource
ToolbarColor}"/>
<Setter Property="CheckedColor" Value="White"/>
</Style>
<Style TargetType="telerikRichTextEditor:PickerToolbarItem"
BasedOn="{StaticResource RichTextEditorToolbarItemStyle}" ApplyToDerivedTypes="True">
<Setter Property="ItemStyle">
<Setter.Value>
<Style
TargetType="telerikDataControls:NonVirtualizedItemsControlItemContainer">
<Setter Property="TextColor" Value="{StaticResource ToolbarColor}"/>
</Style>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="telerikRichTextEditor:RichTextEditorToolbarItem"
BasedOn="{StaticResource RichTextEditorToolbarItemStyle}" ApplyToDerivedTypes="True"/>
<Style TargetType="telerikRichTextEditor:RadRichTextEditorToolbar">
<Setter Property="OverflowButtonTextColor" Value="{StaticResource
ToolbarColor}"/>
<Setter Property="OpenOverflowButtonTextColor" Value="White"/>
<Setter Property="OpenOverflowButtonBackgroundColor" Value="{StaticResource
ToolbarColor}"/>
<Setter Property="OverflowButtonFontFamily" Value="{StaticResource
IconsFont}"/>
<Setter Property="OverflowButtonText" Value="&#xE808;"/>
<Setter Property="BackButtonTextColor" Value="{StaticResource ToolbarColor}"/>
</Style>
<Style TargetType="Button" x:Key="HyperlinkPopupContentViewButtonStyle">
<Setter Property="TextColor" Value="{StaticResource ToolbarColor}"/>
</Style>
<Style TargetType="telerikRichTextEditor:HyperlinkPopupContentView"
x:Key="HyperlinkPopupContentViewStyle">
<Setter Property="OkButtonStyle" Value="{StaticResource
HyperlinkPopupContentViewButtonStyle}"/>
<Setter Property="CancelButtonStyle" Value="{StaticResource
HyperlinkPopupContentViewButtonStyle}"/>
<Setter Property="CornerRadius" Value="15"/>
<Setter Property="BorderColor" Value="{StaticResource ToolbarColor}"/>
<Setter Property="BorderThickness" Value="1"/>
</Style>
<Style TargetType="telerikRichTextEditor:InsertHyperlinkToolbarItem"
BasedOn="{StaticResource RichTextEditorToolbarItemStyle}" ApplyToDerivedTypes="True">
<Setter Property="PopupContentStyle" Value="{StaticResource
HyperlinkPopupContentViewStyle}"/>

1484
Telerik UI for Xamarin

</Style>
</ResourceDictionary>
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikRichTextEditor="clr-namespace:Telerik.XamarinForms.RichTextEditor;assembl
y=Telerik.XamarinForms.RichTextEditor"
xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te
lerik.XamarinForms.DataControls"
 

This is the result:

See Also
 RichTextEditor Styling
 Custom Toolbar
 Telerik Font Icons

1485
Telerik UI for Xamarin

Overview
RadSegmentedControl for Xamarin allows you to display a list of horizontally aligned, mutually
exclusive options, which can be selected by the user. Each option is a button that can display a text
or an image.

Figure 1: RadSegmentedControl Overview

Key features

 Selection: RadSegmentedControl exposes a few useful properties that can help you work
with the items selection. For additional info on this read here.
 Disabling segments: You can disable the interactions with a specific segment and also set a
specific color for this state. Read here for more details on the matter.
 Customizable segment colors: You can customize the colors of the segments in the different
states - normal, selected, disabled. Check here for more info on this.

See Also

 Getting Started

1486
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadSegmentedControl control in
your application.

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadSegmentedControl you have to install the
Telerik.UI.for.Xamarin.Input nuget package. This nuget will automatically refer the
Telerik.UI.for.Xamarin.Primitives, Telerik.UI.for.Xamarin.Common, and
Telerik.UI.for.Xamarin.DataControls nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadSegmentedControl component:

Platform Assemblies
Portable Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll
Android Telerik.Xamarin.Android.Common.dll
Telerik.Xamarin.Android.Input.dll
Telerik.Xamarin.Android.Primitives.dll
Telerik.Xamarin.Android.List.dll
Telerik.Xamarin.Android.Data.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll
UWP Telerik.Core.dll
Telerik.Data.dll
Telerik.UI.Xaml.Input.UWP.dll

1487
Telerik UI for Xamarin

Telerik.UI.Xaml.Controls.Data.UWP.dll
Telerik.UI.Xaml.Primitives.UWP.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll

3. Adding RadSegmentedControl control


If your app is setup, you are ready to add a RadSegmentedControl control.

RadSegmentedControl allows you to work with two types of data - string and image. You can use the
ItemsSource property of RadSegmentedControl to provide IEnumerable collection of strings or
image sources. The control will display a segment for each item in the items source.

Populate with string data


Here is an example how to set the control's ItemsSource property and populate it with some data.

XAML
<telerikInput:RadSegmentedControl x:Name="segmentControlText"
HeightRequest="60"
VerticalOptions="Start">
<telerikInput:RadSegmentedControl.ItemsSource>
<x:Array Type="{x:Type x:String}">
<x:String>Popular</x:String>
<x:String>Library</x:String>
<x:String>Playlists</x:String>
<x:String>Friends</x:String>
</x:Array>
</telerikInput:RadSegmentedControl.ItemsSource>
</telerikInput:RadSegmentedControl>
 

C#
RadSegmentedControl segmentControlText = new RadSegmentedControl()
{
VerticalOptions = LayoutOptions.Start, HeightRequest = 60,
ItemsSource = new List<string>() { "Popular", "Library", "Playlists", "Friends" },
};
 

You also have to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

C#
using Telerik.XamarinForms.Input;

1488
Telerik UI for Xamarin

Populate with image sources


XAML
<telerikInput:RadSegmentedControl x:Name="segmentControlImages"
HeightRequest="60"
VerticalOptions="Start" Grid.Row="1">
<telerikInput:RadSegmentedControl.ItemsSource>
<x:Array Type="{x:Type FileImageSource}">
<FileImageSource>available.png</FileImageSource>
<FileImageSource>away.png</FileImageSource>
<FileImageSource>busy.png</FileImageSource>
</x:Array>
</telerikInput:RadSegmentedControl.ItemsSource>
</telerikInput:RadSegmentedControl>
 

C#
RadSegmentedControl segmentControlImages = new RadSegmentedControl()
{
VerticalOptions = LayoutOptions.Start,
HeightRequest = 60,
ItemsSource = new List<FileImageSource>() { "available.png", "away.png",
"busy.png" },
};
 

This is the result:

1489
Telerik UI for Xamarin

4. Setting segment colors


You can set the background of the segments via the SegmentBackgroundColor property. The color
will be applied to all segments except the selected one. To change the background of the selected
item you can set the SelectedSegmentBackgroundColor

To set the text color of the strings in the items via the SegmentTextColor property. The color of the
selected segment can be set via the SelectedSegmentTextColor property.

You can find an example with the selected color properties in the Selection article.

SDK Browser and QSF applications contain different examples that show RadSegmentedControl's
main features. You can find the applications in the Examples and QSF folders of your local Telerik UI
for Xamarin installation.
 

See Also

 Selection
 Disable segment

1490
Telerik UI for Xamarin

Selection
RadSegmentedControl control exposes few useful properties which can help you work with the items
selection.

Setting the selected segment


The segment control has a SelectedIndex property which you can use to set the selected item.

Setting selection colors


You can define custom colors for the text and the background of the selected segment. You can do
that via the the following properties of RadSegmentedControl:

 SelectedSegmentBackgroundColor
 SelectedSegmentTextColor

Selection changed
RadSegmentedControl exposes a SelectionChanged event which is fired when the selected item is
updated.

 SelectionChanged: Occurs when the selected item is changed programatically or due to user
interaction. The SelectionChanged event handler receives two parameters:
 The sender argument which is of type object, but can be cast to the
RadSegmentedControl type.
 A ValueChangedEventArgs<int> object which provides old and new value of the
SelectedIndex.

Example
This example demonstrates how you could utilize the selection feature of RadSegmentedControl.

First, let's create a ViewModel class containing the SegmentedControl items and int property for
defining the SelectedIndex:

C#
public class ViewModel
{
public ViewModel()
{
this.Categories = new ObservableCollection<string>() { "Popular", "Library",
"Playlists", "Friends" };
this.SelectedCategory = 2;
}

public ObservableCollection<string> Categories { get; set; }

1491
Telerik UI for Xamarin

public int SelectedCategory { get; set; }


}
 

Then, add the SegmentedControl definition and apply ItemsSource, SelectedIndex as well as
selection colors properties:

XAML
<telerikInput:RadSegmentedControl x:Name="segmentControl"
ItemsSource="{Binding Categories}"
SelectedIndex="{Binding SelectedCategory}"
SelectedSegmentTextColor="White"
SelectedSegmentBackgroundColor="CornflowerBlue"
HeightRequest="60"
VerticalOptions="Start">
</telerikInput:RadSegmentedControl>
 

Lastly, define the ViewModel as BindingContext of the control:

C#
this.segmentControl.BindingContext = new ViewModel();
 

The screenshot below shows the result on different platforms:

See Also

 Getting Started

1492
Telerik UI for Xamarin

 Customize Segment Colors

1493
Telerik UI for Xamarin

Disable a Segment
RadSegmentedControl allows you to disable each of its segments individually.

To disable a segment you can use the SetSegmentEnabled method. The method accepts two
arguments index that determines the index of the segment. And isEnabled that determines whether
the item is enabled or not.

You can also check if an item is enabled via the IsSegmentEnabled method. The method accepts a
single argument - index.

Setting a text color


You can set the text color of the disabled segment through the DisabledSegmentTextColor.

Example
The following example shows how to disable a segment and define a color.

XAML
<telerikInput:RadSegmentedControl x:Name="segmentControl"
DisabledSegmentTextColor="#CA5100"
HeightRequest="60"
VerticalOptions="Start">
<telerikInput:RadSegmentedControl.ItemsSource>
<x:Array Type="{x:Type x:String}">
<x:String>Popular</x:String>
<x:String>Library</x:String>
<x:String>Playlists</x:String>
<x:String>Friends</x:String>
</x:Array>
</telerikInput:RadSegmentedControl.ItemsSource>
</telerikInput:RadSegmentedControl>
 

C#
this.segmentControl.SetSegmentEnabled(2, false);
 

Figure 1: Disabled segment

1494
Telerik UI for Xamarin

See Also

 Project Wizard
 Getting Started
 Customize Segment Colors

1495
Telerik UI for Xamarin

Customize Segment Colors


RadSegmentedControl has several properties which you can use to customize the text and
background colors of the segments.

List of color properties


There are different colors applied to the segments in their different states. The control exposes the
following properties:

 SegmentBackgroundColor: This is the background color applied to the unselected segments.


 SegmentTextColor: This is the text color applied to the unselected segments.
 SelectedSegmentBackgroundColor: This is the background color applied to the selected
segment.
 SelectedSegmentTextColor: This is the text color applied to the selected segment.
 DisabledSegmentTextColor: This is the text color applied to the disabled segments.

Example
This example shows setting the different segment colors.

XAML
<telerikInput:RadSegmentedControl x:Name="segmentControl"
Margin="10"
DisabledSegmentTextColor="#C2C3C9"
HeightRequest="60"
SegmentBackgroundColor="#FFFFFF"
SegmentTextColor="#3A9BFD"
SelectedSegmentBackgroundColor="#3A9BFD"
SelectedSegmentTextColor="#FFFFFF"
VerticalOptions="Start">
<telerikInput:RadSegmentedControl.ItemsSource>
<x:Array Type="{x:Type x:String}">
<x:String>Popular</x:String>
<x:String>Library</x:String>
<x:String>Playlists</x:String>
<x:String>Friends</x:String>
</x:Array>
</telerikInput:RadSegmentedControl.ItemsSource>
</telerikInput:RadSegmentedControl>
 

C#
this.segmentControl.SetSegmentEnabled(2, false);
 

Figure 1: Customized segment colors

1496
Telerik UI for Xamarin

See Also

 Getting Started
 Selection
 Disable segment

1497
Telerik UI for Xamarin

Overview
Shadows are commonly used to create depth in the interface and help users differentiate UI
elements. Telerik RadShadow for Xamarin component gives you the option to put highly
customizable shadow effect around any UI you have. With the help of RadShadow you can elevate
some elements and thus achieve modern look & feel for your app.

Figure 1: RadShadow Overview

Key features
 Setting Shadow Color: Although in most cases shadows are of black color, RadShadow
exposes a Color property, so you can easily add color to the shadow effect.
 Defining Transparency: Through the ShadowOpacity property you can set the
transparency-level of the shadows you’re using.
 Defining Shadow Position: RadShadow provides OffsetX and OffsetY properties used to
define its position relative to the UI it wraps around. You can practically place the shadow in
every direction according to the design requirements you have.
 Applying Corner Radius: You can apply a corner radius to the shadow to make it consistent
to the view it wraps around. With the help of CornerRadius property you can soften the

1498
Telerik UI for Xamarin

view’s edges and make them look more natural.


 Applying Blur Radius: Through the BlurRadius property you can adjust the blur level to make
the shadow look softer.

See Also
 Getting Started

1499
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadShadow control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadShadow control

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadShadow control you have to install the
Telerik.UI.for.Xamarin.Primitives nuget package. This nuget will automatically refer the
Telerik.UI.for.Xamarin.Common and Telerik.UI.for.Xamarin.SkiaSharp nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadShadow component:

Platform Assemblies
Portable Telerik.XamarinForms.Primitives.dll
Android Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.SkiaSharp.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.SkiaSharp.dll
UWP Telerik.Core.dll
Telerik.UI.Xaml.Primitives.UWP.dll
Telerik.XamarinForms.Common.dll

1500
Telerik UI for Xamarin

Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.SkiaSharp.dll

3. Adding RadShadow control


You could use one of the following approaches:

Drag the control from the Toolbox.

Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML or C#.

The snippet below shows a simple RadShadow definition. In the example RadShadow wraps around
a Xamarin.Forms Button:

XAML
<telerikPrimitives:RadShadow CornerRadius="10">
<telerikPrimitives:RadShadow.BackgroundColor>
<OnPlatform x:TypeArguments="Color" Default="Default">
<On Platform="UWP" Value="#F1F2F5"/>
</OnPlatform>
</telerikPrimitives:RadShadow.BackgroundColor>
<Button Text="Click me"
BackgroundColor="#D6D7D7"
BorderColor="#B5B6B8"
BorderWidth="1"
HeightRequest="44"
Padding="24, 0"
CornerRadius="10"/>
</telerikPrimitives:RadShadow>
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
 

C#
using Telerik.XamarinForms.Primitives;
 

Here is the result:

1501
Telerik UI for Xamarin

SDK Browser and Telerik Xamarin Samples applications contain different examples that show
RadShadow's main features. For detailed information on this go to Xamarin Demos Applications topic.
 

See Also
 Key Features

1502
Telerik UI for Xamarin

Key Features
The purpose of this help article is to show you the key features of the RadShadow control.

Setting Shadow Color


Through the Color property you can paint the shadow that wraps around your views – you can make
it consistent with the colors of the surrounded controls, or you can just use a softer color to make the
shadow look more natural.

Here is a quick example of a colored shadow around RadButton:

XAML
<telerikPrimitives:RadShadow Color="#4488F6"
ShadowOpacity="0.7"
OffsetX="4"
OffsetY="4">
<telerikInput:RadButton Text="Click me"
TextColor="White"
BackgroundColor="#4488F6"
HeightRequest="44"/>
</telerikPrimitives:RadShadow>
 

Check the result below:

Defining Transparency
Through ShadowOpacity you can control the color transparency level of the RadShadow. The
defined value should be between 0 and 1, by default ShadowOpacity is set to 0.26.

XAML
<telerikPrimitives:RadShadow ShadowOpacity="0.7">
<telerikInput:RadButton Text="Click me"
TextColor="White"
BackgroundColor="#4488F6"
HeightRequest="44"/>
</telerikPrimitives:RadShadow>
 

1503
Telerik UI for Xamarin

And how it looks:

Defining Shadow Position


RadShadow exposes OffsetX and OffsetY properties used to specify the shadow’s position relative
to the position of the view that is casting it. Positive x/y offsets will shift the shadow to the right and
down, while negative offsets shift the shadow to the left and up.

By default, OffsetX and OffsetY are set to 0.00, so that the shadow appears on all sides of the View
it surrounds.

XAML
<telerikPrimitives:RadShadow OffsetX="20"
OffsetY="20">
<telerikInput:RadButton Text="Click me"
TextColor="White"
BackgroundColor="#4488F6"
HeightRequest="44"/>
</telerikPrimitives:RadShadow>
 

Check the result below:

Applying Corner Radius


The CornerRadius property represents the degree to which the corners of the Shadow are rounded-
this is useful in cases RadShadow wraps around a view with rounded edges.

Check below a quick example with RadButton with CornerRadius applied:

XAML
<telerikPrimitives:RadShadow CornerRadius="20"
OffsetX="4"
OffsetY="4">

1504
Telerik UI for Xamarin

<telerikPrimitives:RadShadow.BackgroundColor>
<OnPlatform x:TypeArguments="Color" Default="Default">
<On Platform="UWP" Value="#F1F2F5"/>
</OnPlatform>
</telerikPrimitives:RadShadow.BackgroundColor>
<telerikInput:RadButton Text="Click me"
TextColor="White"
BackgroundColor="#4488F6"
HeightRequest="44"
CornerRadius="20"/>
</telerikPrimitives:RadShadow>
 

In this way the shadow looks consistent with the rounded button:

Applying Blur Radius


Through the BlurRadius property you can specify the shadow blur-level - the higher the number, the
more blurred it will be, and the further out the shadow will extend.

By default, the BlurRadius is 10.

XAML
<telerikPrimitives:RadShadow BlurRadius="3"
OffsetX="4"
OffsetY="4">
<telerikInput:RadButton Text="Click me"
TextColor="White"
BackgroundColor="#4488F6"
HeightRequest="44"/>
</telerikPrimitives:RadShadow>
 

You may notice some differences in blur effect depending on the target platform. This is due to the
different native implementations of the Shadow BlurRadius – on iOS it is implemented as a Gaussian

1505
Telerik UI for Xamarin

blur, while on Android and UWP the shadow blur effect is determined by the elevation of the
surrounded view.
 

See Also
 Getting Started

1506
Telerik UI for Xamarin

Overview
RadSideDrawer for Xamarin is designed to enable users to visualize a hidden view in their
applications. That view can host navigation UI, common settings or any other UI of your choice. It
can be visualized using a flick gesture and can be shown from all four sides of the screen.

Figure 1: RadSideDrawer Overview

Key features
 Drawer positions: The drawer can be shown from any of the four edges of the screen. You
can define its position through the DrawerLocation property. For more details on this read
Properties topic.
 Effects and transitions: RadSideDrawer supports transition animations that are applied to the
opening and closing view. We provide several predefined animations that can be easily set
or changed at runtime to meet our customers’ requirements. Read Transitions topic for more
information.
 Commands: RadSideDrawer allows you to attach commands that will be executed when
certain actions, such as Opening and Closing occur. For detailed information on the matter
go to Commands article.

See Also

1507
Telerik UI for Xamarin

 Getting Started
 Properties
 Commands

1508
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadSideDrawer control in your
application.

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadSideDrawer control you have to install the
Telerik.UI.for.Xamarin.Primitives nuget package. This nuget will automatically refer the
Telerik.UI.for.Xamarin.Common and Telerik.UI.for.Xamarin.SkiaSharp nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadSideDrawer component:

Platform Assemblies
Portable Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Android Telerik.Xamarin.Android.Common.dll
Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
UWP Telerik.Core.dll
Telerik.UI.Xaml.Primitives.UWP.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll

3. Adding RadSideDrawer control

1509
Telerik UI for Xamarin

If your app is setup, you are ready to add a RadSideDrawer control.

You can proceed with defining the component. The DrawerContent represents the hidden view (in it
you could place navigational UI, any common setting, etc), while the MainContent hosts the main
View of your app.

XAML
<telerikPrimitives:RadSideDrawer x:Name="drawer" DrawerLength="200">
<telerikPrimitives:RadSideDrawer.MainContent>
<Label Text="Main content" />
</telerikPrimitives:RadSideDrawer.MainContent>
<telerikPrimitives:RadSideDrawer.DrawerContent>
<StackLayout>
<Button Text="Mail" />
<Button Text="Calendar" />
<Button Text="People" />
<Button Text="Tasks" />
</StackLayout>
</telerikPrimitives:RadSideDrawer.DrawerContent>
</telerikPrimitives:RadSideDrawer>
 

C#
var drawerContent = new StackLayout();
drawerContent.Children.Add(new Button { Text = "Mail" });
drawerContent.Children.Add(new Button { Text = "Calendar" });
drawerContent.Children.Add(new Button { Text = "People" });
drawerContent.Children.Add(new Button { Text = "Tasks" });

var sideDrawer = new RadSideDrawer


{
MainContent = new Label { Text = "Main content" },
DrawerContent = drawerContent,
DrawerLength = 200
};
 

You also have to add the following namespace:

XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
 

C#
using Telerik.XamarinForms.Primitives;
 

Finally, set the drawer as content of your page.

Here is the result when you set IsOpen="True":

1510
Telerik UI for Xamarin

SDK Browser and QSF applications contain different examples that show RadSideDrawer's main
features. You can find the applications in the Examples and QSF folders of your local Telerik UI for
Xamarin installation.
 

See Also
 Properties and Events
 Transitions

1511
Telerik UI for Xamarin

Properties
RadSideDrawer control exposes the following properties:

 DrawerContent (View): Specifies the drawer (initially hidden) content.


 MainContent (View) Specifies the (initially visible) content of the component.
 IsOpen (bool): Specifies a value indicating if the drawer content is visible.
 DrawerLength (double): Defines how much the drawer content should be extended over the
main content in opened position.
 DrawerLocation (SideDrawerLocation): Specifies the location from which the drawer will be
opened. The following options are available:
 Left
 Right
 Top
 Bottom
 DrawerTransitionDuration (double): Defines the duration of the chosen transition.
 DrawerTransitionType (of type Telerik.XamarinForms.Primitives SideDrawerTransitionType):
Defines the transition of the component. This property can be set to one of the following
values:
 Fade, Push, Reveal, ReverseSlideOut, ScaleUp, SlideAling, SlideInOnTop, Custom
 DrawerTransitionFadeOpacity (double): Defines the opacity of the fade layer of the
component. This controls the fade layer opacity on Android or the dim opacity on iOS.
 AreGesturesEnabled (bool): Specifies ability for gestures to open and close the drawer.
 TouchTargetThreshold (double): Defines the touchable area (number of pixels from the
screen edges) that will allow to open the DrawerContent.

A sample Location example can be found in the SideDrawer/Features folder of the SDK Samples
Browser application.
 

See Also
EventsCommands

1512
Telerik UI for Xamarin

Transitions
Transitions are the animation effects applied to the side drawer while it is being opened and closed.

Built-in Transitions
RadSideDrawer exposes several predefined transitions that can be used by customers. The desired
transition can be set through DrawerTransitionType property of the SideDrawer.

DrawerTransitionType is enumeration which exposes the following members:

 Push (the default one)


 Fade
 Reveal
 ReverseSlideOut
 ScaleUp
 SlideAlong
 SlideInOnTop
 Custom

Here is a sample snippet on how you can set DrawerTransitionType property of RadSideDrawer:

XAML
<telerikPrimitives:RadSideDrawer x:Name="sideDrawer"
DrawerTransitionType="SlideInOnTop">
<telerikPrimitives:RadSideDrawer.MainContent>
<StackLayout Orientation="Horizontal">
<Label Text="Transition Type:" />
<Label Text="SlideInOnTop" />
</StackLayout>
</telerikPrimitives:RadSideDrawer.MainContent>
<telerikPrimitives:RadSideDrawer.DrawerContent>
<Grid WidthRequest="220">
<ListView x:Name="drawerList">
<ListView.ItemsSource>
<x:Array Type="{x:Type x:String}">
<x:String>Inbox</x:String>
<x:String>Drafts</x:String>
<x:String>Sent Items</x:String>
</x:Array>
</ListView.ItemsSource>
</ListView>
</Grid>
</telerikPrimitives:RadSideDrawer.DrawerContent>
</telerikPrimitives:RadSideDrawer>
 

Add the following namespace:

1513
Telerik UI for Xamarin

XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
 

In addition to the transition type, you can also control the transition duration and opacity value
through DrawerTransitionDuration and DrawerTransitionFadeOpacity properties, respectively. For
more details on this go to Properties topic.
 

Examples
Check below some of the predefined transitions of RadSideDrawer:

 Default Push transition:

 SlideInOnTop transition - the drawer goes over the main content:

1514
Telerik UI for Xamarin

 ReverseSlideOut transition:

1515
Telerik UI for Xamarin

A sample Transitions examples can be found in the SideDrawer/Features folder of the SDK Samples
Browser application.
 

Create Custom Transition


If however, non of these predefined transitions fits users' scenario they are allowed to create custom
animation effect. Next is a demonstration of how customers can create their own transition.

1. Set the DrawerTransitionType property to Custom.


2. Create custom SideDrawerRenderer (in both Android and iOS platforms) which will allow
customers to apply custom transition.
3. Create a class for each platform and register your custom renderer using the
ExportRenderer assembly level attribute.

Create Custom Transition in Android


Creating custom renderer is simple. Just create a class and derive it from the SideDrawerRenderer.
Furthermore, customers should override the CreateFadeLayer() and CreateCustomTransition()

1516
Telerik UI for Xamarin

methods. Those methods are the necessary extensibility points for such customization. Here is a
sample implementation of a custom renderer:

C#
public class CustomSideDrawerRenderer : SideDrawerRenderer
{
protected override Native.IDrawerFadeLayer CreateFadeLayer()
{
return new Native.BlurFadeLayer(Forms.Context,
RenderScript.Create(Forms.Context))
{
Background = new Drawables.ColorDrawable(Color.FromRgb(255, 200,
255).ToAndroid())
};
}

protected override Native.IDrawerTransition CreateCustomTransition()


{
return new FallDownTransition();
}
}
 

BlurFadeLayer requires reference to Xamarin.Android.Support.v8.RenderScript


 
Once users have this class created, they need to register the renderer:

C#
[assembly: ExportRenderer(typeof(RadSideDrawer), typeof(CustomSideDrawerRenderer))]
 

This must replace the registration of our SideDrawerRenderer

Create Custom Transition in iOS


In iOS the creation of custom animation effect is very similar to the process in Android. The steps are
the same but are executed in a bit different way.

Create a class and derive it from the SideDrawerRenderer

When creating the custom renderer users should override only the CreateCustomTransition()
method. Here is a sample implementation:

C#
public class CustomSideDrawerRenderer : SideDrawerRenderer
{
protected override TKSideDrawerTransition CreateCustomTransition(TKSideDrawer
drawer)
{
return new CustomTransition(drawer);
}

1517
Telerik UI for Xamarin

}
 

Once users have this class created, they need to register the renderer:

C#
[assembly: ExportRenderer(typeof(RadSideDrawer), typeof(CustomSideDrawerRenderer))]
 

See Also
 Properties
 Commands

1518
Telerik UI for Xamarin

Events
RadSideDrawer exposes the following events:

 DrawerOpening: Raised when the drawer starts opening.


 DrawerOpened: Raised when the drawer is already opened.
 DrawerClosing: Raised when the drawer starts closing.
 DrawerClosed: Raised when the drawer is already closed.

where the event handlers listed above recieves two paameters:

 sender - which is of type object, but can be cast to the RadSideDrawer type.
 EventArgs

See Also
 Properties
 Transitions

1519
Telerik UI for Xamarin

Overview
The RadSideDrawer control exposes a Commands collection that allows you toregister custom
commands with each control’s instance. The commands allow the user to easily change and extend
the control default behavior.

Each element in the Commands collection should inherit from the SideDrawerCommandBase class,
and can override the CanExecute() and Execute() methods. Each command is associated with a
certain event, which is represented by the command Id property. You should set this property to one
of the values listed below, otherwise the command service of the control will not execute the
command.

 Opening: Executed when the side drawer is being visualized on the device screen.
 Opened: Executed when the side drawer is already visualized on the device screen.
 Closing: Executed when the side drawer is being hidden.
 Closed: Executed when the side drawer is already closed.
 Unknown

For your convenience we have created a special SideDrawerUserCommand class that also exposes
a Command dependency property which can be set to an instance of type that implements the
ICommand interface.

Examples
The following examples will demonstrate how to use the RadSideDrawer commands in different
scenarios.

Inheriting from the SideDrawerCommandBase class


You can create a class deriving from the SideDrawerCommandBase class and set its Id property to
the desired command trigger event. Furthermore, you can override its CanExecute() and Execute()
methods. A sample implementation is shown below:

C#
public class CustomDrawerCommand : SideDrawerCommandBase
{
public CustomDrawerCommand()
{
this.Id = SideDrawerCommandId.Closed;
}

public override bool CanExecute(object parameter)


{
return true;
}

public override void Execute(object parameter)

1520
Telerik UI for Xamarin

{
// implement your custom logic here
}
}
 

Once such command is created it can be used in XAML like this:

XAML
<telerikPrimitives:RadSideDrawer>
<telerikPrimitives:RadSideDrawer.Commands>
<local:CustomDrawerCommand/>
</telerikPrimitives:RadSideDrawer.Commands>
<telerikPrimitives:RadSideDrawer.MainContent>
<Label Text="Main content" />
</telerikPrimitives:RadSideDrawer.MainContent>
<telerikPrimitives:RadSideDrawer.DrawerContent>
<Label Text="Drawer content" />
</telerikPrimitives:RadSideDrawer.DrawerContent>
</telerikPrimitives:RadSideDrawer>
 

You will need to add the following namespaces:

XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
 

Where the local alias points to the namespace where the CustomUserCommand is defined.

Using the SideDrawerUserCommand class


You can define a class that implements the ICommand interface:

C#
public class CustomCommand : ICommand
{
public event EventHandler CanExecuteChanged;

public bool CanExecute(object parameter)


{
return true;
}

public void Execute(object parameter)


{
// implement your custom logic here
}
}
 

1521
Telerik UI for Xamarin

After thet you can use this class with the SideDrawerUserCommand in XAML like this:

XAML
<telerikPrimitives:RadSideDrawer>
<telerikPrimitives:RadSideDrawer.Commands>
<sidedrawer:SideDrawerUserCommand Id="Opening">
<sidedrawer:SideDrawerUserCommand.Command>
<local:CustomCommand/>
</drawer:SideDrawerUserCommand.Command>
</drawer:SideDrawerUserCommand>
</telerikPrimitives:RadSideDrawer.Commands>
</telerikPrimitives:RadSideDrawer>
 

You will need to add the following namespaces:

XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
xmlns:sidedrawer="clr-namespace:Telerik.XamarinForms.Primitives.SideDrawer;assembly=Te
lerik.XamarinForms.Primitives"
 

and the local alias points to the namespace where the CustomCommand is defined.

Binding to a ViewModel
You can also use the SideDrawerUserCommand to bind its Command property to a view model.

Here is how the ViewModel is defined:

C#
public class ViewModel
{
public ViewModel()
{
this.Command = new CustomCommand();
}

public ICommand Command { get; set; }


}
 

C#
public class CustomCommand : ICommand
{
public event EventHandler CanExecuteChanged;

public bool CanExecute(object parameter)


{

1522
Telerik UI for Xamarin

return true;
}

public void Execute(object parameter)


{
// implement your custom logic here
}
}
 

XAML
<telerikPrimitives:RadSideDrawer x:Name="drawer" DrawerLength="200">
<telerikPrimitives:RadSideDrawer.BindingContext>
<local:ViewModel/>
</telerikPrimitives:RadSideDrawer.BindingContext>
<telerikPrimitives:RadSideDrawer.Commands>
<sidedrawer:SideDrawerUserCommand Command="{Binding Command}" Id="Opening"/>
</telerikPrimitives:RadSideDrawer.Commands>
<telerikPrimitives:RadSideDrawer.MainContent>
<Label Text="Main content" />
</telerikPrimitives:RadSideDrawer.MainContent>
<telerikPrimitives:RadSideDrawer.DrawerContent>
<StackLayout>
<Button Text="Mail" />
<Button Text="Calendar" />
<Button Text="People" />
<Button Text="Tasks" />
</StackLayout>
</telerikPrimitives:RadSideDrawer.DrawerContent>
</telerikPrimitives:RadSideDrawer>
 

You will need to add the following namespaces:

XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
xmlns:sidedrawer="clr-namespace:Telerik.XamarinForms.Primitives.SideDrawer;assembly=Te
lerik.XamarinForms.Primitives"
 

and the local alias points to the namespace where the CustomCommand and ViewModel are
defined.

1523
Telerik UI for Xamarin

Overview
Telerik UI for Xamarin SignaturePad control gives you the option to capture a signature in your
desktop and mobile applications, and fully customize signature's stroke and color. In addition you
can easily save the signature as Png or Jpeg with additional saving settings using the flexible Saving
API of the SignaturePad.

Key Featrues
 Display signature in your mobile and desktop application.
 Configure the stroke thickness and stroke color of the signature to achieve the desired look.
 Save the signature as an image in different formats (Png or Jpeg). In addition the Saving API
allows you to set the image's quality and scale factor. Also you have the option to change the
stroke color and thickness of the signature when saving it as an image.
 Exhaustive number of events that are raised when a new stroke is started, completed and an
event fired when the surface is cleared.
 Commands Support: Easily clear the signature from the surface using the exposed command.

See Also
 Getting Started with SignaturePad for Xamarin

1524
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadSignaturePad control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadSignaturePad control

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadSignaturePad control you have to install the
Telerik.UI.for.Xamarin.Input nuget package. This nuget will automatically refer the
Telerik.UI.for.Xamarin.Common, Telerik.UI.for.Xamarin.Primitives,
Telerik.UI.for.Xamarin.DataControls and Telerik.UI.for.Xamarin.SkiaSharp nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadSignaturePad component:

Platform Assemblies
Portable Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.SkiaSharp.dll
Android Telerik.XamarinForms.Input.dll
Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.SkiaSharp.dll
iOS Telerik.Xamarin.iOS.dll

1525
Telerik UI for Xamarin

Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.SkiaSharp.dll
UWP Telerik.Core.dll
Telerik.UI.Xaml.Input.UWP.dll
Telerik.UI.Xaml.Primitives.UWP.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.SkiaSharp.dll
RadSignaturePad is rendered via the SkiaSharp graphics library so you need to install also
SkiaSharp.Views.Forms in all projects of the Xamarin solution (.Net Standard/Shared, Android, iOS,
etc).
 

3. Adding RadSignaturePad control


You could use one of the following approaches:

Drag the control from the Toolbox.

Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML or C#.

The snippet below shows a simple RadSignaturePad definition.

XAML
<telerikInput:RadSignaturePad BorderThickness="1" BorderColor="LightGray"/>
 

C#
var signaturePad = new RadSignaturePad
{
BorderColor = Color.LightGray,
BorderThickness = new Thickness(1)
};
 

In addition to this, you need to add the following namespace:

XAML

1526
Telerik UI for Xamarin

xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

C#
using Telerik.XamarinForms.Input;
 

Here is the result:

SDK Browser and Telerik Xamarin Samples applications contain different examples that show
RadSignaturePad's main features. For detailed information on this go to Xamarin Demos Applications
topic.
 

See Also
 Signature Configuration
 Events
 Commands
 Saving Options

1527
Telerik UI for Xamarin

Configuration
SignaturePad provides means for customizing the appearance of the plot area as well as the
signature itself. You can modify the signature stroke color and thickness.

Here is a list of the configuration properties you can apply on the SignaturePad:

 StrokeColor: Sets the color of the signature stroke;


 StrokeThickness: Defines the width of the stroke;
 BorderColor: Defines the color of the border around the plot area;
 BorderThickness: Sets the width of the border around the plot area;
 CornerRadius: Applies a corner radius of the border around the plot area;
 BackgroundColor: Defines the background of the plot area;

Check below a quick example on how the listed properties can be applied to a RadSignaturePad
instance:

XAML
<telerikInput:RadSignaturePad BorderThickness="1"
BorderColor="LightGray"
CornerRadius="25"
StrokeColor="Blue"
StrokeThickness="5"
BackgroundColor="BlanchedAlmond"/>
 

And here is the result:

See Also
 Events
 Commands
 Saving Options

1528
Telerik UI for Xamarin

Saving Options
SignaturePad provides SaveImageAsync method you can utilize to get the image drawn by the user
inside the plot area. The method has two overloads, so you can choose the exact settings for
retrieving the encoded image, such as format, quality, colors, etc. You will get the image as a
stream, so you can further use it according to the specific application requirements.

 SaveImageAsync(Stream outputStream)
 SaveImageAsync(Stream outputStream, SaveImageSettings settings)

SaveImageSettings class is used to set the exact settings when saving the image as a memory
stream. Here are the available options:

 ImageFormat (of type Telerik.XamarinForms.Input.ImageFormat): Defines the format of the


saved image, available options are ImageFormat.Jpeg and ImageFormat.Png;
 ImageQuality (double): Defines the quality of the encoded image, when using a lossy
compression format: the value of 1 specifies the maximum possible quality, resulting in
minimum compression; the value of 0 specifies the minimum possible quality, resulting in
maximum compression.
 ScaleFocus: Sets a scale factor, which can be used to reduce the size of the final image:
values below 1 downscale the image before saving, thus reducing the final image size;
values above 1 upscale the image before saving, thus increasing the final image size.
 BackgroundColor, StrokeColor, StrokeThickness: Apply styling options to the
signature inside the encoded image.

Check below a quick example on how you can get the image through SaveImageAsync method and
use it as a Source of a Xamarin.Forms.Image control.

Add a sample SignaturePad instance:

XAML
<telerikInput:RadSignaturePad x:Name="signaturePad"
BorderThickness="1"
BorderColor="LightGray"/>
 

Add a sample Image control to the page:

XAML
<Image x:Name="signatureImage" Grid.Row="2" />
 

Use the following snippet for saving the image as a Jpeg in a memory stream and use the stream as
a source of the defined Image control:

C#
var settings = new SaveImageSettings()

1529
Telerik UI for Xamarin

{
ImageFormat = ImageFormat.Jpeg,
ScaleFactor = 0.7,
ImageQuality = 1,
BackgroundColor = Color.LightGray,
StrokeColor = Color.DarkBlue,
StrokeThickness = 5
};

byte[] array;

using (var stream = new MemoryStream())


{
await this.signaturePad.SaveImageAsync(stream, settings);
array = stream.ToArray();

this.signatureImage.Source = ImageSource.FromStream(() => new


MemoryStream(array));
}
 

Here is how a sample signature looks with used saving settings as in the snippet above:

See Also
 Signature Configuration
 Events
 Commands

1530
Telerik UI for Xamarin

Events
The SignaturePad for Xamarin exposes the following events:

 StrokeStarted event is raised when a new stroke is started. The StrokeStarted event
handler receives two parameters:
 The Sender which is of type Telerik.XamarinForms.Input.SignatureView.
 and EventArgs
 StrokeCompleted event is raised when a new stroke is completed. The StrokeCompleted
event handler receives two parameters:
 The Sender which is of type Telerik.XamarinForms.Input.SignatureView.
 and EventArgs
 Cleared event is raised when the surface of Telerik.XamarinForms.Input.RadSignaturePad
is cleared

Example
1. The example contains a X Button, two Labels and a SignaturePad. The control's definition in
XAML:

XAML
<telerikInput:RadSignaturePad x:Name="signaturePad" BorderThickness="1"
BorderColor="LightGray"
StrokeStarted="RadSignaturePad_StrokeStarted"
StrokeCompleted="RadSignaturePad_StrokeCompleted"
Cleared="RadSignaturePad_Cleared"/>

<Button x:Name="clearButton"
Text="X"
BackgroundColor="Transparent"
Command="{Binding Source={x:Reference signaturePad}, Path=ClearCommand}"
HorizontalOptions="End"
VerticalOptions="Start"
Margin="0,10,10,0"/>

<Label x:Name="timeStampLabel"
HorizontalOptions="End"
VerticalOptions="End"
Margin="0,0,10,10"/>

1. Add the following namespace:

XAML

1531
Telerik UI for Xamarin

xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

Let's add the events:

The SignaturePad.StrokeStarted event. When stroke starts we will display a timestamp


using a Label:

C#
private void RadSignaturePad_StrokeStarted(object sender, EventArgs e)
{
this.timeStampLabel.Text = DateTime.Now.ToString();
this.logInfo.Text = "";

}
 

The SignaturePad.StrokeCompleted event. When stroke completes the timespamp


Label text is udated.

C#
private void RadSignaturePad_StrokeCompleted(object sender, EventArgs e)
{
this.timeStampLabel.Text = DateTime.Now.ToString();
}
 

The SignaturePad.Cleared event, When Cleared event is fired, Label with


Text="Cleared" is displayed.

C#
private void RadSignaturePad_Cleared(object sender, EventArgs e)
{
this.logInfo.Text = "Cleared";
this.timeStampLabel.Text = "";
}
 

1532
Telerik UI for Xamarin

See Also
 Configure the Signature
 Commands
 Save Signature

1533
Telerik UI for Xamarin

Commands
SignaturePad exposes a ClearCommand(ICommand) for clearing the signature.

XAML
<Grid RowDefinitions="Auto,*">
<Button Text="Clear the signature"
Command="{Binding ClearCommand, Source={x:Reference signaturePad}}"/>
<telerikInput:RadSignaturePad x:Name="signaturePad"
Grid.Row="1"
BorderThickness="1"
BorderColor="LightGray" />
</Grid>
 

Add the namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

See Also
 Signature Configuration
 Events
 Saving Options

1534
Telerik UI for Xamarin

Overview
RadSlideView is a flexible navigation control that allows you to slide between different views, thus
providing an interactive navigation. With it you can build a gallery display to show your images and
content efficiently.

Key features
 Customizable indicators and slide buttons: RadSlideView provides you with the ability to
customize the appearance of the indicators and the slide buttons. For more details check
Customize the Control topic.
 Item Template: You can define an ItemTemplate to present the data in the views in a way
that’s most suitable for your scenario. For more details read the Item Template topic.
 Infinity scrolling: The control allows you to start repeating the views when you reach the last
item in the collection. This is controlled through the IsInfiniteScrollingEnabled property.
 Built-in animation: RadSlideView has a built-in sliding animation which can be enabled or
disabled through the IsAnimated property.
 Commands: RadSlideView allows you to attach commands that will be executed when the
slide actions occur. For more details on this go to the Commands topic.
 UI Virtualization: RadSlideView supports UI Virtualization which processes only these visual
elements that are loaded in the selected view as well as the previous and the next one. This
speeds up the loading time, thus enhancing the UI performance.

1535
Telerik UI for Xamarin

Check out RadSlideView Getting Started help article that shows how to use it in a basic scenario.
 

See Also
 Customize the Control
 Item Template
 Commands

1536
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadSlideView control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadSlideView control
 Populating RadSlideView with data

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadSlideView control you have to install the
Telerik.UI.for.Xamarin.Primitives nuget package. This nuget will automatically refer the
Telerik.UI.for.Xamarin.Common and Telerik.UI.for.Xamarin.SkiaSharp nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadSlideView component:

Platform Assemblies
Portable Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Android Telerik.Xamarin.Android.Common.dll
Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
UWP Telerik.Core.dll
Telerik.UI.Xaml.Primitives.UWP.dll

1537
Telerik UI for Xamarin

Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll

3. Adding RadSlideView control


You could use one of the following approaches:

Drag the control from the Toolbox.

Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML or C#.

The snippet below shows a simple RadSlideView definition:

XAML
<telerikPrimitives:RadSlideView x:Name="slideView" />
 

C#
var listView = new SlideView();
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
 

C#
using Telerik.XamarinForms.Primitives;
 

4. Populating RadSlideView with data


RadSlideView is populated via its ItemsSource property. The control will display an indicator for each
item in the ItemsSource and display the view of the selected item.

The next snippet shows how you could set the control's ItemsSource property and populate it with
some data.

XAML
<telerikPrimitives:RadSlideView x:Name="slideView">

1538
Telerik UI for Xamarin

<telerikPrimitives:RadSlideView.ItemsSource>
<x:Array Type="{x:Type ContentView}">
<ContentView>
<telerikInput:RadCalendar Margin="50, 30"/>
</ContentView>
<ContentView>
<Label HorizontalOptions="Center" VerticalOptions="CenterAndExpand" Text="Other
View" TextColor="Blue" />
</ContentView>
<ContentView>
<Label HorizontalOptions="Center" VerticalOptions="CenterAndExpand"
Text="Another View" TextColor="Red" />
</ContentView>
</x:Array>
</telerikPrimitives:RadSlideView.ItemsSource>
</telerikPrimitives:RadSlideView>
 

Figure 1: RadSlideView example

Check the ItemTemplate article to see how to populate the control with business items and customize
their appearance.

SDK Browser and QSF applications contain different examples that show RadSlideViews's main
features. You can find the applications in the Examples and QSF folders of your local Telerik UI for
Xamarin installation.
 

See Also

1539
Telerik UI for Xamarin

 Customize the control


 ItemTemplate
 Commands

1540
Telerik UI for Xamarin

Control Template
RadSlideView's visual appearance is defined through a Control Template. In order to customize the
way the RadSlideView looks, you will need to take the default ControlTemplate and modify it.

This topic gives an overview of the ControlTemplate of the SlideView control, so you can copy it to
your app and make changes.

The original ControlTemplate


The SlideView contains three control templates:

 ControlTemplate: the look of the main


 IndicatorTemplate: appearance of the indicators
 SelectedIndicatorTemplate: the look of the selected indicator

Here is the definition of the

XAML
<ContentPage.Resources>
<ResourceDictionary>
<!-- IndicatorTemplate -->
<ControlTemplate x:Key="RadSlideView_IndicatorTemplate">
<Label Text="{TemplateBinding IndicatorText}"
FontSize="{TemplateBinding IndicatorFontSize}"
FontFamily="{TemplateBinding IndicatorFontFamily}"
VerticalOptions="Center"
TextColor="{TemplateBinding IndicatorColor}" />
</ControlTemplate>

<!-- SelectedIndicator ControlTemplate -->


<ControlTemplate x:Key="RadSlideView_SelectedIndicatorTemplate">
<Label Text="{TemplateBinding SelectedIndicatorText}"
FontSize="{TemplateBinding SelectedIndicatorFontSize}"
FontFamily="{TemplateBinding SelectedIndicatorFontFamily}"
VerticalOptions="Center"
TextColor="{TemplateBinding SelectedIndicatorColor}" />
</ControlTemplate>

<!-- SlideView ControlTemplate -->


<ControlTemplate x:Key="RadSlideView_ControlTemplate">
<Grid>
<ContentPresenter AutomationId="SlideViewContentPresenter" />

<telerikPrimitives:SlideViewLabel AutomationId="SlideViewLeftArrow"
VerticalOptions="Center"
IsVisible="{TemplateBinding ShowButtons}"
Text="&#x2039;"
FontSize="{TemplateBinding SlideButtonsSize}"

1541
Telerik UI for Xamarin

FontFamily="Arial"
HorizontalOptions="Start"
TextColor="{TemplateBinding SlideButtonsColor}">
<common:TelerikEffects.HelpText>
<OnPlatform x:TypeArguments="x:String">
<On Platform="Android" Value="RadSlideView Navigate Backward" />
</OnPlatform>
</common:TelerikEffects.HelpText>
<telerikPrimitives:SlideViewLabel.Effects>
<common:HelpTextEffect/>
</telerikPrimitives:SlideViewLabel.Effects>
<telerikPrimitives:SlideViewLabel.GestureRecognizers>
<TapGestureRecognizer Command="{TemplateBinding Path=PreviousItemCommand}" />
</telerikPrimitives:SlideViewLabel.GestureRecognizers>
<AutomationProperties.HelpText>
<OnPlatform x:TypeArguments="x:String">
<On Platform="iOS" Value="Navigate Backward" />
<On Platform="UWP" Value="Navigate Backward" />
</OnPlatform>
</AutomationProperties.HelpText>
<AutomationProperties.Name>
<OnPlatform x:TypeArguments="x:String">
<On Platform="iOS" Value="RadSlideView" />
<On Platform="UWP" Value="RadSlideView" />
</OnPlatform>
</AutomationProperties.Name>
</telerikPrimitives:SlideViewLabel>

<telerikPrimitives:SlideViewLabel AutomationId="SlideViewRightArrow"
VerticalOptions="Center"
Text="&#x203A;"
IsVisible="{TemplateBinding ShowButtons}"
FontSize="{TemplateBinding SlideButtonsSize}"
FontFamily="Arial"
HorizontalOptions="End"
TextColor="{TemplateBinding SlideButtonsColor}">
<common:TelerikEffects.HelpText>
<OnPlatform x:TypeArguments="x:String">
<On Platform="Android" Value="RadSlideView Navigate Forward" />
</OnPlatform>
</common:TelerikEffects.HelpText>
<telerikPrimitives:SlideViewLabel.Effects>
<common:HelpTextEffect />
</telerikPrimitives:SlideViewLabel.Effects>
<telerikPrimitives:SlideViewLabel.GestureRecognizers>
<TapGestureRecognizer Command="{TemplateBinding Path=NextItemCommand}" />
</telerikPrimitives:SlideViewLabel.GestureRecognizers>
<AutomationProperties.HelpText>
<OnPlatform x:TypeArguments="x:String">
<On Platform="iOS" Value="Navigate Forward" />
<On Platform="UWP" Value="Navigate Forward" />
</OnPlatform>
</AutomationProperties.HelpText>

1542
Telerik UI for Xamarin

<AutomationProperties.Name>
<OnPlatform x:TypeArguments="x:String">
<On Platform="iOS" Value="RadSlideView" />
<On Platform="UWP" Value="RadSlideView" />
</OnPlatform>
</AutomationProperties.Name>
</telerikPrimitives:SlideViewLabel>

<slideView:SlideViewIndicators Owner="{TemplateBinding}"
Spacing="{TemplateBinding Path=IndicatorsSpacing}"
SelectedIndicatorTemplate="{TemplateBinding SelectedIndicatorTemplate}"
IndicatorTemplate="{TemplateBinding IndicatorTemplate}"
IsVisible="{TemplateBinding ShowIndicators}"
VerticalOptions="End"
HorizontalOptions="Center"
InputTransparent="True" />
</Grid>
</ControlTemplate>
</ResourceDictionary>
</ContentPage.Resources>
 

where the Telerik namespace is as follow:

XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
xmlns:slideView="clr-namespace:Telerik.XamarinForms.Primitives.SlideView;assembly=Tele
rik.XamarinForms.Primitives"
xmlns:common="clr-namespace:Telerik.XamarinForms.Common;assembly=Telerik.XamarinForms.
Common"
 

Finally, use the custom ControlTemplate, IndicatorTemplate and SelectedIndicatorTemplate as a


StaticResource on any instance of RadSlideView:

XAML
<StackLayout>
<telerikPrimitives:RadSlideView x:Name="slideView"
ControlTemplate="{StaticResource RadSlideView_ControlTemplate}"
IndicatorTemplate="{StaticResource RadSlideView_IndicatorTemplate}"
SelectedIndicatorTemplate="{StaticResource
RadSlideView_SelectedIndicatorTemplate}">
<telerikPrimitives:RadSlideView.ItemsSource>
<x:Array Type="{x:Type ContentView}">
<ContentView>
<Grid HeightRequest="100">
<Label Text="View 1" />
</Grid>
</ContentView>
<ContentView>
<Label Text="View 2" />
</ContentView>

1543
Telerik UI for Xamarin

<ContentView >
<Label Text="View 3" />
</ContentView>
</x:Array>
</telerikPrimitives:RadSlideView.ItemsSource>
</telerikPrimitives:RadSlideView>
</StackLayout>
 

See Also
 Item Template
 Item Template Selector
 Customize the Control

1544
Telerik UI for Xamarin

Customize the Control


RadSlideView has several properties which you can use to customize its appearance and behavior.
This article lists them briefly.

Customizing the indicators


The indicators are the little ellipses displayed under the selected view used for switching between
the views. RadSlideView provides various options for customzing the look of the indicators via the
following properties:

 ShowIndicators: This property sets the visibility of the indicators. You can hide them by
setting it to False.
 IndicatorText: Indicators are represents by a string symbol that could be changed through
IndicatorText property;
 IndicatorFontSize: Defines the indicator text font size of all indicators except the selected
one;
 SelectedIndicatorFontSize: Sets the indicator text font size of the selected indicator;
 IndicatorFontFamily: Specified the indicator text FontFamily of the indicators except the
selected one;
 SelectedIndicatorFontFamily: Sets the indicator text FontFamily of the selected indicator;
 IndicatorColor: This property sets the color of the indicators except the selected one.
 SelectedIndicatorColor: This property sets the color of the selected indicator.
 IndicatorsSpacing: This property sets the spacing between the indicators.

Here is a quick example on how to customize the indicators:

XAML
<telerikPrimitives:RadSlideView x:Name="slideView"
IndicatorText="&#9830;"
SelectedIndicatorText="&#9830;"
SelectedIndicatorFontSize="32"
SelectedIndicatorColor="Red">
<telerikPrimitives:RadSlideView.ItemsSource>
<x:Array Type="{x:Type ContentView}">
<ContentView>
<Grid HeightRequest="100">
<Label Text="View 1" />
</Grid>
</ContentView>
<ContentView>
<Label Text="View 2" />
</ContentView>
<ContentView >
<Label Text="View 3" />
</ContentView>
</x:Array>
</telerikPrimitives:RadSlideView.ItemsSource>

1545
Telerik UI for Xamarin

</telerikPrimitives:RadSlideView>
 

And the result:

Customizing the slide buttons


The slide buttons can be customized via the following properties:

 ShowButtons: This property sets the buttons visibility. You can hide them by setting it to
False.
 SlideButtonsColor: This property sets the buttons color.
 SlideButtonsSize: This property sets the buttons size.

Customizing the content alignment


You can set the alignment of the content of the SlideView item via the following properties:

 HorizontalContentOptions: This property sets the horizonal alignment


 VerticalContentOptions: This property sets the vertical alignment.

HorizontalContentOptions and VerticalContentOptions are respected only when there isn't


ContentView or Template defined. In other cases, you would need to handle the content alignment
inside the View/Template respectively.
 

Add page spacing

1546
Telerik UI for Xamarin

The control allows you to define a spacing between each slide using the PageSpacingProperty(int).

Disabling the animation


The control supports a built-in sliding animation which is enabled by default. To disable it you can set
the control's IsAnimated property to False.

Disabling swiping
You can disable the swiping and allow the end user to change the view only with the slide buttons.
To do this set the IsSwipingEnabled property to False.

Enabling infinity scrolling


By default when you reach to the last view, the 'next' slide button won't do anything. You can alter
this and allow repeating of the views when you reach the last view, via the IsInfiniteScrollingEnabled
property.

Setting orientation
You change the orientation of the slide animation via the Orientation property of RadSlideView.

See Also

 Getting Started
 ItemTemplate

1547
Telerik UI for Xamarin

ItemTemplate
RadSlideView can be populated with various types of objects (string, int, any business objects, etc.).
You can customize the visualization of the views in the ItemsSource of the control using its
ItemTemplate property. The template could contain any view that you can use to display the data.

Additionally, you can select different visualization for each item via the ItemTemplateSelector
property.

Еxample
The following example shows how to populate the ItemsSource with business items and customize
their appearance.

First, create a sample MyItem class:

C#
public class MyItem
{
public string Content { get; set; }
}
 

Add a ViewModel containing a collection of MyItem objects:

C#
public class ViewModel
{
public ObservableCollection<MyItem> Views { get; set; }

public ViewModel()
{
this.Views = new ObservableCollection<MyItem>()
{
new MyItem() { Content = "View 1" },
new MyItem() { Content = "View 2" },
new MyItem() { Content = "View 3" },
};
}
}
 

Then, add the SlideView definition with a sample ItemTemplate applied:

XAML
<telerikPrimitives:RadSlideView x:Name="slideView" ItemsSource="{Binding Views}">
<telerikPrimitives:RadSlideView.ItemTemplate>
<DataTemplate>

1548
Telerik UI for Xamarin

<ContentView>
<Label Text="{Binding Content}" TextColor="#007ACC"
HorizontalTextAlignment="Center"
VerticalOptions="CenterAndExpand" />
</ContentView>
</DataTemplate>
</telerikPrimitives:RadSlideView.ItemTemplate>
</telerikPrimitives:RadSlideView>
 

All that is left is to set the BindingContext to the ViewModel:

C#
slideView.BindingContext = new ViewModel();
 

Here is the result:

Figure 1: RadSlideView with ItemTemplate applied

See Also

 Customize the Control


 ItemTemplateSelector

1549
Telerik UI for Xamarin

ItemTemplateSelector
RadSlideView control exposes an ItemTemplateSelector property which you can use to apply
different template to each item depending on a specific condition.

This article will show you how you can utilize this property to achieve divergent appearance for the
different items within your Telerik SlideView control.

TemplateSelector Implementation
Let's assume you have a RadSlideView bound to a collection of multiple Product objects and the
appearance of each item depends on a specific property of the business object.

C#
public class Product
{
public string Name { get; set; }
public double Price { get; set; }
public bool InStock { get; set; }
}
 

Add the following ViewModel class:

C#
public class ViewModel
{
public ObservableCollection<Product> Products { get; set; }
public ViewModel()
{
this.Products = new ObservableCollection<Product>()
{
new Product() {Name="Product 1", Price = 21.5, InStock = true},
new Product() {Name="Product 2", Price = 44.3, InStock = false},
new Product() {Name="Product 3", Price = 33, InStock = true}
};
}
}
 

Then, as you need to apply different template to the item based on the value of the InStock property,
you have to create a custom class that inherits from DataTemplateSelector. This class will return
different DataTemplate according to whether the value is true or false:

C#
public class SlideViewItemTemplateSelector : DataTemplateSelector
{
public DataTemplate InStockTemplate { get; set; }

1550
Telerik UI for Xamarin

public DataTemplate NotAvailableTemplate { get; set; }


protected override DataTemplate OnSelectTemplate(object item, BindableObject
container)
{
var product = item as Product;
if (product != null && product.InStock)
return InStockTemplate;
else return NotAvailableTemplate;
}
}
 

The next step is to define the needed templates inside the Resources of your page:

XAML
<ResourceDictionary>
<Style TargetType="Label">
<Setter Property="Label.TextColor" Value="#404040"/>
</Style>
<local:SlideViewItemTemplateSelector x:Key="SlideViewItemTemplateSelector">
<local:SlideViewItemTemplateSelector.InStockTemplate>
<DataTemplate>
<StackLayout Padding="50, 30">
<StackLayout Orientation="Horizontal">
<Label Text="Name: " />
<Label Text="{Binding Name}" />
</StackLayout>
<StackLayout Orientation="Horizontal">
<Label Text="Price: " />
<Label Text="{Binding Price}" />
</StackLayout>
<Label Text="In Stock" FontAttributes="Italic" TextColor="#007ACC" />
</StackLayout>
</DataTemplate>
</local:SlideViewItemTemplateSelector.InStockTemplate>
<local:SlideViewItemTemplateSelector.NotAvailableTemplate>
<DataTemplate>
<StackLayout Padding="50, 30">
<StackLayout Orientation="Horizontal">
<Label Text="Name: " />
<Label Text="{Binding Name}" />
</StackLayout>
<StackLayout Orientation="Horizontal">
<Label Text="Price: " />
<Label Text="{Binding Price}" />
</StackLayout>
<Label Text="This item is currently not available" FontAttributes="Italic"
TextColor="Red" />
</StackLayout>
</DataTemplate>
</local:SlideViewItemTemplateSelector.NotAvailableTemplate>
</local:SlideViewItemTemplateSelector>
</ResourceDictionary>

1551
Telerik UI for Xamarin

</ContentView.Resources>
 

Declare a simple SlideView and set its ItemsSource and ItemTemplateSelector properties:

XAML
<telerikPrimitives:RadSlideView x:Name="slideView"
ItemsSource="{Binding Products}"
ItemTemplateSelector="{StaticResource SlideViewItemTemplateSelector}">
</telerikPrimitives:RadSlideView>
 

All that is left is to set the BindingContext to the ViewModel:

C#
this.slideView.BindingContext = new ViewModel();
 

Here is how RadSlideView looks with both templates applied:

Figure 1: RadSlideView with InStockTemplate applied

Figure 2: RadSlideView with NotAvailableTemplate applied

1552
Telerik UI for Xamarin

See Also

 Customize the Control


 ItemTemplate

1553
Telerik UI for Xamarin

Events
RadSlideView provides the following events:

 SlidingToIndex: Occurs when the current selection is changing (executing a slide). The
SlidingToIndex event handler receives two parameters:
 The sender argument which is of type RadSlideViewPresenter (it contains all the
properties of the SlideView itself);
 А SlideViewSlidingToIndexEventArgs object which exposes the new index and a
cancellation option via the Index and Cancel properties. Setting the Cancel property of
the event arguments to True will stop the sliding action.
 SlidedToIndex: Occurs when the current selection is changed (a slide is executed). The
SlidingToIndex event handler receives two parameters:
 The sender argument which is of type RadSlideViewPresenter;
 А SlideViewSlidedToIndexEventArgs object which exposes the new index via the Index
property.

Example
Here is a quick example how to handle SlidingToIndex event of RadSlideView.

First, add the SlideView definition:

XAML
<telerikPrimitives:RadSlideView x:Name="slideView"
SlidingToIndex="GoingToNextSlide">
<telerikPrimitives:RadSlideView.ItemsSource>
<x:Array Type="{x:Type ContentView}">
<ContentView>
<telerikInput:RadCalendar Margin="50, 30" />
</ContentView>
<ContentView>
<Label HorizontalOptions="Center"
VerticalOptions="CenterAndExpand" Text="Other View" TextColor="Blue" />
</ContentView>
<ContentView>
<Label HorizontalOptions="Center" VerticalOptions="CenterAndExpand"
Text="Another View" TextColor="Red" />
</ContentView>
</x:Array>
</telerikPrimitives:RadSlideView.ItemsSource>
</telerikPrimitives:RadSlideView>
 

And then, the event handler (in the sample it just displays a message):

C#
private void GoingToNextSlide(object sender, SlideViewSlidingToIndexEventArgs e)

1554
Telerik UI for Xamarin

{
var slideView = sender as RadSlideViewPresenter;
if (slideView.SelectedIndex != -1)
Application.Current.MainPage.DisplayAlert("", "You're going from Slide " +
slideView.SelectedIndex + " to Slide " + e.Index, "OK");
}
 

See Also

 Getting Started

1555
Telerik UI for Xamarin

Commands
RadSlideView allows you to attach commands that will be executed when the slide actions occurs.
To do this you can use the Commands collection and add a custom SlideViewCommand for each
custom action you want to execute.

CommandId Enumeration
All the predefined commands within a RadSlideView instance are identified by a member of the
SlideViewCommandId enumeration. This is actually the key that relates a command instance to a
particular action/routine within the owning slideview. In order to register a custom command within a
RadSlideView instance you need to inherit from SlideViewCommand class and override its
CanExecute and Execute methods. Following are the members of the CommandId enumerations:

 SlidingToIndex
 SlidedToIndex

For each of the available commands there is a context object of type [CommandId]CommandContext
(namely SlideViewSlidingToIndexCommandContext and SlideViewSlidedToIndexCommandContext)
which is passed as a parameter in its Execute method. The context object provides information
identical to the corresponding event's args.

Example
This example shows how to add a custom command for the SlidingToIndex action.

First, create a class that inherits from SlideViewCommand and set its Id property accordingly. You
would also need to override CanExecute and Execute methods as demonstrated in the example
below:

C#
public class CustomSlideViewCommand : SlideViewCommand
{
public CustomSlideViewCommand()
{
this.Id = SlideViewCommandId.SlidingToIndex;
}

public override bool CanExecute(object parameter)


{
return true;
}

public override void Execute(object parameter)


{
var slidedToIndex = (parameter as SlideViewSlidingToIndexCommandContext).Index;
//add your logic here
Application.Current.MainPage.DisplayAlert("", "You're about to go to slide " +

1556
Telerik UI for Xamarin

slidedToIndex, "OK");
base.Execute(parameter);
}
}
 

Then add this Command to the Commands collection of the RadSlideView instance:

C#
this.slideView.Commands.Add(new CustomSlideViewCommand());
 

See Also

 Events

1557
Telerik UI for Xamarin

Overview
RadSpreadProcessing is part of the Telerik Document Processing libraries. The full documentation
for this component is available at
https://docs.telerik.com/devtools/document-processing/libraries/radspreadsprocessing.
 
This library enables you to work with spreadsheet documents – create ones from scratch, modify
existing documents or convert between the most common spreadsheet formats. You can save the
generated workbook to a local file, stream, or stream it to the client browser.

RadSpreadProcessing comes with support for:

 Shapes and Images: API for insertion, positioning and deletion of images in worksheets.
 Conditional Formatting: Make it easy to analyze data, find critical issues, patterns and trends
by representing the data inside in a user-friendly manner.
 Hyperlinks: The API enables you to add, remove, edit and search for hyperlinks in the
worksheets of the document.
 Workbook Protection: Prevents the users from modifying the workbook by adding, removing,
renaming or reordering sheets.
 Worksheet protection: Restricts the user from modifying the content and structure of the
worksheet. Additionally, the model offers protection options that let you choose a set of
commands that will be available to the user when protection is enabled.
 Grouping: Helps you organize data in sections, to be able to show and hide the currently
relevant chunks.
 Formulas: The library comes with more than 200 built-in functions. The API enables you to

1558
Telerik UI for Xamarin

easily plug custom ones as well.


 Named ranges: You can use the named ranges on workbook and worksheet levels.
 Styling: You can apply styles to the cells. The API allows you to duplicate one of the
predefined styles or create a new one according to your preferences.
 Theming: The document model comes with predefined themes called Document themes.
They enable you to specify colors, fonts and a variety of graphic effects in a document and
affect the look and feel of the whole workbook.
 Resizing: Auto fit or resize rows and columns.
 Number Formats: Enable you to format the data in the cells so it can be easily readable.
 Copy/Paste: Add or copy worksheets within or across workbooks. Of course, copying and
pasting of cells is supported as well.
 Data Validation: Enables you to control the type of data or the values that users enter into a
cell. Different data validation rules are available, including list, number, date, text length or
custom rules.
 Filtering worksheet data.
 Sorting the data in the worksheet.
 Find and replace data.
 Freeze Panes: Keep part of the worksheet visible at all times when scrolling.
 Hidden rows and columns: The API of the workbook model allows you to set the hidden state
of each row or column.
 Merge and unmerge cells: You have the ability to merge two or more adjacent cells into a
single cell that spans over multiple rows and columns.
 Auto fill and Series: Fill cells automatically with data following a specific pattern.
 Page Setup: Set and get header and footer settings and apply various page setup options
like paper size, orientation, scaling, margins, breaks, etc. Apply print settings.
 History: The document model provides the possibility to maintain a history stack that tracks
all changes to the content of the workbook. Each worksheet has its own history stack.

Supported formats
 XLSX
 XLS
 CSV
 Plain text
 PDF (export only)
 DataTable

See Also
 Getting Started
 What is a Workbook
 What is a Worksheet

Required references
You have two options to add the required Telerik references to your Xamarin.Forms app in order to
use RadSpreadProcessing:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet

1559
Telerik UI for Xamarin

package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadSpreadProcessing you have to install the Telerik.Documents.Core
and Telerik.Documents.Spreadsheet nuget packages. The following nugets are required in order to
be able to export to XLSX, XLS and PDF formats:
Telerik.Documents.Spreadsheet.FormatProviders.OpenXml,Telerik.Documents.Spreadsheet.Format
Providers.Xls, Telerik.Documents.Fixed, Telerik.Documents.Spreadsheet.FormatProviders.Pdf,
Telerik.Zip.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadSpreadProcessing:
 Telerik.Documents.Core.dll
 Telerik.Documents.Spreadsheet.dll

The following assemblies are required in order to be able to export to XLSX, XLS and PDF
formats:

 Telerik.Documents.Spreadsheet.FormatProviders.OpenXml.dll
 Telerik.Documents.Spreadsheet.FormatProviders.Xls.dll
 Telerik.Documents.Fixed.dll
 Telerik.Documents.Spreadsheet.FormatProviders.Pdf.dll
 Telerik.Zip.dll

Please keep in mind these assemblies are located in the Portable folder, still, you need to
add a reference to them in the Xamarin.Forms project as well as in each of the platform
projects (Android | iOS | UWP).
 

1560
Telerik UI for Xamarin

Overview
This article briefly explains the specifics of RadSpreadStreamProcessing - what is spread streaming,
how it works compared to the RadSpreadProcessing library and when to use it.

RadSpreadStreamProcessing is part of the Telerik Document Processing libraries. The full


documentation for this component is available at
https://docs.telerik.com/devtools/document-processing/libraries/radspreadstreamsprocessing.
 

What is Spread Streaming?


Spread streaming is a document processing paradigm that allows you to create big spreadsheet
documents with great performance and minimal memory footprint.

The key for the memory efficiency is that the spread streaming library writes the spreadsheet content
directly to a stream without creating and preserving the spreadsheet document model in memory.
Each time an exporter object is disposed, the set values are written into the stream. This allows you
to create large documents with an excellent performance.

Key Features
Some of the features you can take advantage of are:

 Export to XLSX or CSV files


 Writing directly into a stream
 Grouping: Helps you organize data in sections, to be able to show and hide the currently

1561
Telerik UI for Xamarin

relevant chunks.
 Hidden rows and columns: The API allows you to set the hidden state of each row or column.
 Cell formatting: A number of properties enabling you to apply the desired look to a cell.
 Cell styles: Using cell styles allows you to apply multiple format options in one step and also
offers an easy approach to achieve consistency in cell formatting.
 Merge cells: You have the ability to merge two or more adjacent cells into a single cell that
spans over multiple rows and columns.
 Controlling the view state of a sheet:
 Setting scale factor
 Control over the selection and the active cell
 Show/hide gridlines
 Show/hide row and column headers
 Freezing panes: Keep part of the worksheet always visible while scrolling.
 Changing the first visible cell: when you would like to show a particular part of the sheet to
the user on opening the document in a viewer.

RadSpreadStreamProcessing vs. RadSpreadProcessing


There are two main differences between the libraries.

 RadSpreadStreamProcessing can be used only to create documents and append data to


existing ones. On the other hand you can use the RadSpreadProcessing also for reading
and modifying the content of documents.
 RadSpreadStreamProcessing writes directly into a stream, unlike RadSpreadProcessing
which creates models for the elements in the document. This is why the memory used with
the spread streaming library is significantly lower than when using RadSpreadProcessing.

When to Use RadSpreadStreamProcessing


You can use RadSpreadStreamProcessing to create and export large amount of data with a low
memory footprint and great performance.

Required references
You have two options to add the required Telerik references to your Xamarin.Forms app in order to
use RadSpreadStreamProcessing:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadSpreadStreamProcessing you have to install the Telerik.Zip and
Telerik.Documents.SpreadsheetStreaming nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadSpreadStreamProcessing:
 Telerik.Zip.dll
 Telerik.Documents.SpreadsheetStreaming.dll

1562
Telerik UI for Xamarin

Please keep in mind these assemblies are located in the Portable folder, still, you need to
add a reference to them in the Xamarin.Forms project as well as in each of the platform
projects (Android | iOS | UWP).
 

1563
Telerik UI for Xamarin

Overview
Telerik TabView for Xamarin is a flexible navigation control that allows you to build tabbed interfaces.
Each tabview item has an associated content displayed on selection.

Key features
 Item Selection: RadTabView exposes selection API which allows you as a developer to
extend the navigation per application needs. For more details read the Selection topic.
 Flexible header and content of the items: You can easily customize the header and the
content of the tabview items. Go to the TabViewItem topic for more information on this.
 Customizable tab strip area position: The tab strip can be positioned top or bottom. Go to
TabViewHeaderItem article.
 Support for Scrolling Tabs: The tab strip area has configuration for scrolling the items inside.
For more information go to TabView Scrolling Tabs article.
 RadTabView gives you the ability to swipe inside the content in order to change the selected
item. This scenario can be achieved with and without using animation. For more details
review the Key Features article.
 Layout option for overflow tabs: If there are too many items in the TabView control and they
cannot fit into the tab strip area, a customizable overflow button will be displayed.

See Also
 Getting Started
 Key Features

1564
Telerik UI for Xamarin

 TabViewItem
 TabViewHeaderItem

1565
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadTabView control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadTabView control

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadTabView control you have to install the
Telerik.UI.for.Xamarin.Primitives nuget package. This nuget will automatically refer the
Telerik.UI.for.Xamarin.Common and Telerik.UI.for.Xamarin.SkiaSharp nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadTabView component:

Platform Assemblies
Portable Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Android Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Telerik.Xamarin.Android.Common.dll
Telerik.Xamarin.Android.Primitives.dll
iOS Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
UWP Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll

3. Adding RadTabView control


1566
Telerik UI for Xamarin

You could use one of the following approaches:

Drag the control from the Toolbox.

Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML or C#.

The snippet below shows a simple RadTabView definition:

XAML
<telerikPrimitives:RadTabView x:Name="tabView">
<telerikPrimitives:RadTabView.Items>
<telerikPrimitives:TabViewItem HeaderText="Home">
<telerikPrimitives:TabViewItem.Content>
<Label Margin="10" Text="This is the content of the Home tab" />
</telerikPrimitives:TabViewItem.Content>
</telerikPrimitives:TabViewItem>
<telerikPrimitives:TabViewItem HeaderText="Folder">
<telerikPrimitives:TabViewItem.Content>
<Label Margin="10" Text="This is the content of the Folder tab" />
</telerikPrimitives:TabViewItem.Content>
</telerikPrimitives:TabViewItem>
<telerikPrimitives:TabViewItem HeaderText="View">
<telerikPrimitives:TabViewItem.Content>
<Label Margin="10" Text="This is the content of the View tab" />
</telerikPrimitives:TabViewItem.Content>
</telerikPrimitives:TabViewItem>
</telerikPrimitives:RadTabView.Items>
</telerikPrimitives:RadTabView>
 

C#
RadTabView tabView = new RadTabView();
Telerik.XamarinForms.Primitives.TabViewItem homeTab = new
Telerik.XamarinForms.Primitives.TabViewItem()
{
HeaderText = "Home",
Content = new Label() { Text = "This is the content of the Home tab", Margin = new
Thickness(10) },
};
Telerik.XamarinForms.Primitives.TabViewItem folderTab = new
Telerik.XamarinForms.Primitives.TabViewItem()
{
HeaderText = "Folder",
Content = new Label() { Text = "This is the content of the Folder tab", Margin =
new Thickness(10) },
};
Telerik.XamarinForms.Primitives.TabViewItem viewTab = new

1567
Telerik UI for Xamarin

Telerik.XamarinForms.Primitives.TabViewItem()
{
HeaderText = "View",
Content = new Label() { Text = "This is the content of the View tab", Margin = new
Thickness(10) },
};
tabView.Items.Add(homeTab);
tabView.Items.Add(folderTab);
tabView.Items.Add(viewTab);
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
 

C#
using Telerik.XamarinForms.Primitives;
 

To display something in the tab you can define TabViewItem elements in its Items collection.

To define the header of a TabViewItem you can use its HeaderText property as in the example. If
you need to show a more complex layout you can use the Header property.

This is the result:

1568
Telerik UI for Xamarin

SDK Browser and QSF applications contain different examples that show RadTabView's main
features. You can find the applications in the Examples and QSF folders of your local Telerik UI for
Xamarin installation.
 

See Also
 Key Features
 TabViewItem
 TabViewHeaderItem

1569
Telerik UI for Xamarin

Key features
RadTabView control exposes the following properties:

 Items(ObservableItemCollection)
 Header (Telerik.XamarinForms.Primitives.TabViewHeader): Modify the header appearance.
 HeaderPosition(Telerik.XamarinForms.Primitives.TabViewHeaderPosition). Defnes the
tabview header position. You can choose between two options top and bottom. The default
header position is top.
 SelectedItem(object):
 IsContentPreserved: This property could be used to preserve the tabs content when
switching them. In this way the visual state of the components inside each tab wouldn't be
reset. When IsContentPreserved is set to True, the tabview does not unload/reload the tabs'
content. By default the property is False.

Swiping inside the TabView content


RadTabView allows you to swipe inside the content in order to change the selected item. This is the
default behavior of the control.

If you want to prevent this feature you will need to set the IsContentSwipingEnabled bool
property to False. The default value of the IsContentSwipingEnabled property is True.

IsContentSwipingAnimationEnabled(bool) property specifies whether a swipe inside the content


will change the selected item with animation. The default value is false.

Here is how the swiping inside the content looks:

1570
Telerik UI for Xamarin

IsContentSwipingEnabled and IsContentSwipeAnimationEnabled are part of the TabView features


set from R1 2021 Release. IsContentPreserved property is part of the TabView features set from R2
2019 Service Pack.
 

TabView Selection
Changing the selection will highlight the corresponding item and show its content under the tab strip
area.

The RadTabView control exposes a few useful properties which can help you work with the items
selection.

 SelectedItem property is used to set up the selection.

TabViewItem can be selected by setting its IsSelected property to true.


 
If the item assigned to the SelectedItem property is not added in the Items collection the control, the
selection will be lost.
 

Example

1571
Telerik UI for Xamarin

The snippet below shows how to set the selection manually.

C#
RadTabView tabView = new RadTabView();
tabView.Items.Add(new Telerik.XamarinForms.Primitives.TabViewItem() { HeaderText =
"Home" });
tabView.Items.Add(new Telerik.XamarinForms.Primitives.TabViewItem() { HeaderText =
"Folder" });
tabView.Items.Add(new Telerik.XamarinForms.Primitives.TabViewItem() { HeaderText =
"View" });

tabView.SelectedItem = tabView.Items[1];
 

This is the result:

A sample Selection example can be found in the TabView/Features folder of the SDK Samples
Browser application.
 

Customizing the Selected Item


In order to customize the appearance of the selected item, you can modify the control template of
the TabViewHeaderItem. More about this check the TabViewHeader Custom Template.

See Also
 TabViewItem
 TabView HeaderItem

1572
Telerik UI for Xamarin

 TabView Scrolling Tabs

1573
Telerik UI for Xamarin

Scrolling Tabs
With R1 2021 Official release the RadTabView control allows you to scroll through the tabs inside
the TabView Header.

To enable the scrolling you would need to use the RadTabView Header property of type
TabViewHeader - just set its IsScrollable property of type bool to True.

Example:
Here is the TabView definition with Header and IsScrollable set to True:

XAML
<telerikPrimitives:RadTabView x:Name="tabViewHeader" HeaderPosition="Top">
<telerikPrimitives:RadTabView.Header>
<telerikPrimitives:TabViewHeader BackgroundColor="#FFE5B6"
IsScrollable="True"
ItemSpacing="4">
</telerikPrimitives:TabViewHeader>
</telerikPrimitives:RadTabView.Header>
<telerikPrimitives:RadTabView.Items>
<telerikPrimitives:TabViewItem HeaderText="January "/>
<telerikPrimitives:TabViewItem HeaderText="February " />
<telerikPrimitives:TabViewItem HeaderText="March " />
<telerikPrimitives:TabViewItem HeaderText="April " />
<telerikPrimitives:TabViewItem HeaderText="May " />
<telerikPrimitives:TabViewItem HeaderText="June " />
<telerikPrimitives:TabViewItem HeaderText="July " />
<telerikPrimitives:TabViewItem HeaderText="August " />
<telerikPrimitives:TabViewItem HeaderText="September " />
<telerikPrimitives:TabViewItem HeaderText="October " />
<telerikPrimitives:TabViewItem HeaderText="November " />
<telerikPrimitives:TabViewItem HeaderText="December " />
</telerikPrimitives:RadTabView.Items>
</telerikPrimitives:RadTabView>
 

This is the result:

1574
Telerik UI for Xamarin

A sample TabView Header example can be found in the TabView/Features folder of the SDK
Samples Browser application.
 

See Also
 TabViewItem
 TabView HeaderItem

1575
Telerik UI for Xamarin

TabViewItem
TabViewItem is the control used to populate RadTabView. It displays the header of the tab item and
the corresponding content. TabView Item exposes the following properties:

 HeaderText(string): Defines a simple text for the TabView header.


 Header(Telerik.XamarinForms.Primitives.TabViewHeaderItem): Allows you to create a more
complex layout for the TabView Header using the TabViewHeaderItem control.
 Content(Xamarin.Forms.View): Defines the content of the TabView Item
 IsSelected(bool): Defines the selected TabView item.
 IsEnabled(bool): Defines whether the TabView Item is enabled/disabled. By default
IsEnabled is True.
 IsVisible(bool): Specifies whether the TabView Item is visible/hidden. IsVisible is supported
only with the TabView IsContentPreserved property set to False.

TabViewItem IsVisible is supported only in scenarios where "IsContentPreserved" property of the


TabView is False. If you try to hide an item (set "IsVisible" to False) when "IsContentPreserved" is
enabled, an InvalidOperationException will be raised.
 

Displaying TabViewItem
To display a TabViewItem you can add it in the Items collection of RadTabView.

Example
XAML
<telerikPrimitives:RadTabView x:Name="tabView" HeaderPosition="Bottom">
<telerikPrimitives:RadTabView.Items>
<telerikPrimitives:TabViewItem HeaderText="Tab1 " />
<telerikPrimitives:TabViewItem HeaderText="Tab2 " />
<telerikPrimitives:TabViewItem HeaderText="Tab3 " />
</telerikPrimitives:RadTabView.Items>
</telerikPrimitives:RadTabView>
 

Defining Header
You can define a header for TabViewItem using one of the following properties:

 HeaderText: Defines a simple text for the TabView header.


 Header: Allows you to create a more complex layout for the TabView using the
TabViewHeaderItem control.

Example with HeaderText and Header

1576
Telerik UI for Xamarin

XAML
<telerikPrimitives:RadTabView>
<telerikPrimitives:RadTabView.Items>
<telerikPrimitives:TabViewItem HeaderText="View">
<telerikPrimitives:TabViewItem.Content>
<Label Margin="10" Text="This is the content of the View tab" />
</telerikPrimitives:TabViewItem.Content>
</telerikPrimitives:TabViewItem>

<telerikPrimitives:TabViewItem>
<telerikPrimitives:TabViewItem.Header>
<telerikPrimitives:TabViewHeaderItem>
<telerikPrimitives:TabViewHeaderItem.Content>
<StackLayout Orientation="Horizontal" HorizontalOptions="Center">
<telerikPrimitives:RadBorder BackgroundColor="#CA5100"
HeightRequest="10"
VerticalOptions="Center"
WidthRequest="10" />
<Label Text="Folder" VerticalOptions="Center" />
</StackLayout>
</telerikPrimitives:TabViewHeaderItem.Content>
</telerikPrimitives:TabViewHeaderItem>
</telerikPrimitives:TabViewItem.Header>
<telerikPrimitives:TabViewItem.Content>
<Label Margin="10" Text="This is the content of the Folder tab" />
</telerikPrimitives:TabViewItem.Content>
</telerikPrimitives:TabViewItem>

</telerikPrimitives:RadTabView.Items>
</telerikPrimitives:RadTabView>
 

You can see both properties demonstrated in the Example section of this article.
 

Defining Content
You can define the content of a TabViewItem via its Content property. It is of type View, so you can
use any UI element that implements the View class.

Example
XAML
<telerikPrimitives:RadTabView x:Name="tabView">
<telerikPrimitives:RadTabView.Items>

<telerikPrimitives:TabViewItem HeaderText="Home">
<telerikPrimitives:TabViewItem.Content>
<Label Margin="10" Text="This is the content of the Home tab" />
</telerikPrimitives:TabViewItem.Content>
</telerikPrimitives:TabViewItem>

1577
Telerik UI for Xamarin

<telerikPrimitives:TabViewItem HeaderText="View">
<telerikPrimitives:TabViewItem.Content>
<Label Margin="10" Text="This is the content of the View tab" />
</telerikPrimitives:TabViewItem.Content>
</telerikPrimitives:TabViewItem>
</telerikPrimitives:RadTabView.Items>
</telerikPrimitives:RadTabView>
 

The RadTabView control displays only the content of the selected item.
 

Selecting an Item
You can manually select TabViewItem via its IsSelected bool property. Selecting an item will
deselect all the others from the Items collection. For more details on selection check the Key
Features article.

Disabled Tabs
With Telerik UI for Xamarin version 2020.3.1106.1 TabView Item has a support for Disabled tabs.
You can set the IsEnabled bool property of the TadViewItem to False if you want to prevent the
header to be clicked. The header text will look disabled and you can not click on it.

XAML
<telerikPrimitives:RadTabView x:Name="tabView">
<telerikPrimitives:RadTabView.Items>

<telerikPrimitives:TabViewItem HeaderText="Home" IsEnabled="False">


<telerikPrimitives:TabViewItem.Content>
<Label Margin="10" Text="This is the content of the Home tab" />
</telerikPrimitives:TabViewItem.Content>
</telerikPrimitives:TabViewItem>

<telerikPrimitives:TabViewItem HeaderText="View">
<telerikPrimitives:TabViewItem.Content>
<Label Margin="10" Text="This is the content of the View tab" />
</telerikPrimitives:TabViewItem.Content>
</telerikPrimitives:TabViewItem>
</telerikPrimitives:RadTabView.Items>
</telerikPrimitives:RadTabView>
 

Hidden Tabs
With Telerik UI for Xamarin R3 2021 TabView introduces IsVisible property for the TabViewItem -
with it you can easily show/hide certain TabItem without removing it from the TabView Items
collection.

1578
Telerik UI for Xamarin

XAML
<telerikPrimitives:RadTabView x:Name="tabView">
<telerikPrimitives:RadTabView.Items>

<telerikPrimitives:TabViewItem HeaderText="Home">
<telerikPrimitives:TabViewItem.Content>
<Label Margin="10" Text="This is the content of the Home tab" />
</telerikPrimitives:TabViewItem.Content>
</telerikPrimitives:TabViewItem>

<telerikPrimitives:TabViewItem HeaderText="View"
IsVisible="False">
<telerikPrimitives:TabViewItem.Content>
<Label Margin="10" Text="This is the content of the View tab" />
</telerikPrimitives:TabViewItem.Content>
</telerikPrimitives:TabViewItem>

<telerikPrimitives:TabViewItem HeaderText="Folder">
<telerikPrimitives:TabViewItem.Content>
<Label Margin="10" Text="This is the content of the Folder tab" />
</telerikPrimitives:TabViewItem.Content>
</telerikPrimitives:TabViewItem>

</telerikPrimitives:RadTabView.Items>
</telerikPrimitives:RadTabView>
 

Check the result below on different platforms:

1579
Telerik UI for Xamarin

Example
This example demonstrates how to define RadTabView with TabViewItems and set their header,
content and also how to select an item via its IsSelected property.

XAML
<telerikPrimitives:RadTabView x:Name="tabView">
<telerikPrimitives:RadTabView.Items>

<telerikPrimitives:TabViewItem HeaderText="Home">
<telerikPrimitives:TabViewItem.Content>
<Label Margin="10" Text="This is the content of the Home tab" />
</telerikPrimitives:TabViewItem.Content>
</telerikPrimitives:TabViewItem>

<telerikPrimitives:TabViewItem HeaderText="View">
<telerikPrimitives:TabViewItem.Content>
<Label Margin="10" Text="This is the content of the View tab" />
</telerikPrimitives:TabViewItem.Content>
</telerikPrimitives:TabViewItem>

<telerikPrimitives:TabViewItem>
<telerikPrimitives:TabViewItem.Header>
<telerikPrimitives:TabViewHeaderItem>
<telerikPrimitives:TabViewHeaderItem.Content>
<StackLayout Orientation="Horizontal" HorizontalOptions="Center">
<telerikPrimitives:RadBorder BackgroundColor="#CA5100"
HeightRequest="10"
VerticalOptions="Center"
WidthRequest="10" />
<Label Text="Folder" VerticalOptions="Center" />
</StackLayout>
</telerikPrimitives:TabViewHeaderItem.Content>
</telerikPrimitives:TabViewHeaderItem>
</telerikPrimitives:TabViewItem.Header>
<telerikPrimitives:TabViewItem.Content>
<Label Margin="10" Text="This is the content of the Folder tab" />
</telerikPrimitives:TabViewItem.Content>
</telerikPrimitives:TabViewItem>

</telerikPrimitives:RadTabView.Items>
</telerikPrimitives:RadTabView>
 

C#
RadTabView tabView = new RadTabView();
Telerik.XamarinForms.Primitives.TabViewItem homeTab = new
Telerik.XamarinForms.Primitives.TabViewItem()
{
HeaderText = "Home",
Content = new Label()
{

1580
Telerik UI for Xamarin

Text = "This is the content of the Home tab",


Margin = new Thickness(10)
},
};
Telerik.XamarinForms.Primitives.TabViewItem viewTab = new
Telerik.XamarinForms.Primitives.TabViewItem()
{
HeaderText = "View",
Content = new Label()
{
Text = "This is the content of the View tab",
Margin = new Thickness(10)
},
};
StackLayout folderTabHeaderPanel = new StackLayout()
{
Orientation = StackOrientation.Horizontal,
Margin = new Thickness(5, 0, 0, 0),
};
folderTabHeaderPanel.Children.Add(new ContentView()
{
BackgroundColor = (Color)(new
ColorTypeConverter()).ConvertFromInvariantString("#CA5100"),
WidthRequest = 10,
HeightRequest = 10,
VerticalOptions = LayoutOptions.Center,
});
folderTabHeaderPanel.Children.Add(new Label() { Text = "Folder" });
Telerik.XamarinForms.Primitives.TabViewItem folderTab = new
Telerik.XamarinForms.Primitives.TabViewItem()
{
Header = new TabViewHeaderItem() { Content = folderTabHeaderPanel },
Content = new Label()
{
Text = "This is the content of the Folder tab",
Margin = new Thickness(10)
},
};

tabView.Items.Add(homeTab);
tabView.Items.Add(viewTab);
tabView.Items.Add(folderTab);
 

Here is the result:

1581
Telerik UI for Xamarin

See Also
 TabViewHeaderItem

1582
Telerik UI for Xamarin

TabViewHeaderItem
The tab strip area of RadTabView contains a special toolbar panel that hosts all TabViewHeaderItem
elements. Each individual TabViewItem has a Header property as well so you can set a specific
TabViewHeaderItem for each tab.

Setting the Header's Position


You can use the HeaderPosition property of RadTabView to control the position of the header. The
property allows you to place the header at the Top of the control where is by default or at the
Bottom, under the content of the selected tab.

Default TabViewHeaderItem ControlTemplate


Here is the default Header ControlTemplate definition:

XAML
<ControlTemplate x:Key="HeaderControlTemplate" >
<Grid BackgroundColor="Transparent">
<BoxView IsVisible="{TemplateBinding IsSelected}"
BackgroundColor="{TemplateBinding SelectedColor}"
VerticalOptions="End"
HeightRequest="2" />
<Label Text="{TemplateBinding Text}"
Margin="0, 0, 0, 2"
VerticalOptions="Center"
HorizontalOptions="Center" />
</Grid>
</ControlTemplate>
 

The TabView definition and how to control template is set to the TabView Header

XAML
<telerikPrimitives:RadTabView x:Name="tabView"
HeaderPosition="Top">
<telerikPrimitives:RadTabView.Items>
<telerikPrimitives:TabViewItem>
<telerikPrimitives:TabViewItem.Header>
<telerikPrimitives:TabViewHeaderItem Text="Tab 1"
ControlTemplate="{StaticResource HeaderControlTemplate}" />
</telerikPrimitives:TabViewItem.Header>
</telerikPrimitives:TabViewItem>
<telerikPrimitives:TabViewItem HeaderText="Tab 2"/>
<telerikPrimitives:TabViewItem HeaderText="Tab 3"/>
</telerikPrimitives:RadTabView.Items>
</telerikPrimitives:RadTabView>

1583
Telerik UI for Xamarin

Customize the TabViewHeaderItem Control Template:


You can customize the appearance of each TabViewHeaderItem by replacing its default template
with one of your choice. Below you can find a sample scenario where a custom control template is
declared and set to the ControlTemplate property of the TabViewHeaderItem.

You can alter the control template of the TabViewHeaderItem in order to control the color of the
selected item.
 

Example
XAML
<ContentView.Resources>
<ResourceDictionary>
<ControlTemplate x:Key="HeaderControlTemplate">
<Grid BackgroundColor="Transparent">
<BoxView IsVisible="{TemplateBinding IsSelected}"
BackgroundColor="Orange"
VerticalOptions="End"
HeightRequest="5"/>
<StackLayout Orientation="Horizontal"
Margin="0, 0, 0, 8">
<Label Text="{TemplateBinding Text}"
FontSize="15"
TextColor="#9E4F2C"
VerticalOptions="Center"
HorizontalTextAlignment="Start"/>
<Label Text="Description"
TextColor="Blue"
IsVisible="{TemplateBinding IsSelected}"
VerticalTextAlignment="Center"
FontSize="12"/>
</StackLayout>
</Grid>
</ControlTemplate>
</ResourceDictionary>
</ContentView.Resources>
<telerikPrimitives:RadTabView x:Name="tabView"
HeaderPosition="Top">
<telerikPrimitives:RadTabView.Items>
<telerikPrimitives:TabViewItem>
<telerikPrimitives:TabViewItem.Header>
<telerikPrimitives:TabViewHeaderItem Text="Tab 1"
ControlTemplate="{StaticResource HeaderControlTemplate}" />
</telerikPrimitives:TabViewItem.Header>
</telerikPrimitives:TabViewItem>
<telerikPrimitives:TabViewItem HeaderText="Tab 2"/>
<telerikPrimitives:TabViewItem HeaderText="Tab 3"/>

1584
Telerik UI for Xamarin

</telerikPrimitives:RadTabView.Items>
</telerikPrimitives:RadTabView>
 

Here is the result how the TabViewHeaderItem with custom Control Template looks:

A sample HeaderItem Custom Template example can be found in the TabView/Features folder of
the SDK Samples Browser application.
 

TabView Header
The RadTabView control exposes a Header(TelerikXamarinForms.Primitives.TabViewHeader)
property which you can use to modify the header's appearance.

The TabViewHeader allows you to style and customize the OverflowButton. In addition you can
decide whetehr scrolling inside the tabs will be allowed using the IsScrollanle bool property.
When IsScrollable is True, OverflowButton won't be visualized, instead you can scroll through
the tabs.

OverflowButton styling
Example how to set styling to OverflowButton

XAML
<telerikPrimitives:RadTabView x:Name="tabViewHeaderOverfowButton"
HeaderPosition="Bottom">
<telerikPrimitives:RadTabView.Header>

1585
Telerik UI for Xamarin

<telerikPrimitives:TabViewHeader BackgroundColor="LightBlue"
OverflowButtonContentPadding="3"
OverflowButtonFontSize="20"
OverflowButtonText="More items"
OverflowButtonTextColor="Black"
OverflowPopupBackgroundColor="LightBlue"/>
</telerikPrimitives:RadTabView.Header>
</telerikPrimitives:RadTabView>
 

Scrolling Tabs
Here is how to set IsScrollable

XAML
<telerikPrimitives:RadTabView x:Name="tabViewHeader" HeaderPosition="Top">
<telerikPrimitives:RadTabView.Header>
<telerikPrimitives:TabViewHeader IsScrollable="True"/>
</telerikPrimitives:RadTabView.Header>
</telerikPrimitives:RadTabView>
 

Here is how the scrolling is performed:

Adjust the width between the tab view headers


By default there is a spacing between the tab view headers. The behavior comes from the
RadToolbar control which is used for the TabView headers.In order to adjust the width between the
tabview headers you will need to set the ItemSpacing property (of type double) to the
RadTabView.Header

XAML
<telerikPrimitives:RadTabView x:Name="tabView"
HeaderPosition="Top">
<telerikPrimitives:RadTabView.Header>
<telerikPrimitives:TabViewHeader ItemSpacing="0"/>
</telerikPrimitives:RadTabView.Header>
</telerikPrimitives:RadTabView>
 

Customizing the Overflow Button

1586
Telerik UI for Xamarin

If there are too many items in the tabview control and they cannot fit into the tab strip area, an
overflow button will be displayed. You can customize the button through the following properties.

 OverflowButtonText: You can use this property to set the text of the button. The default one
is "More".
 OverflowButtonTemplate: If you need more complex layout for the button you can use this
property.

Example
This example demonstrates how to replace the default header of the RadTabView control and
change its background.

XAML
<telerikPrimitives:RadTabView x:Name="tabViewHeaderOverfowButton"
HeaderPosition="Bottom">
<telerikPrimitives:RadTabView.Header>
<telerikPrimitives:TabViewHeader BackgroundColor="#FFE5B6"
ItemSpacing="4"
OverflowPopupBackgroundColor="#FFE5B6">
<telerikPrimitives:TabViewHeader.OverflowButtonTemplate>
<DataTemplate>
<Label Margin="3,0,3,0"
BackgroundColor="#FFE5B6"
Text=" + "
TextColor="#9E4F2C"
VerticalOptions="Center"/>
</DataTemplate>
</telerikPrimitives:TabViewHeader.OverflowButtonTemplate>
</telerikPrimitives:TabViewHeader>
</telerikPrimitives:RadTabView.Header>
<telerikPrimitives:RadTabView.Items>
<telerikPrimitives:TabViewItem HeaderText="January " />
<telerikPrimitives:TabViewItem HeaderText="February " />
<telerikPrimitives:TabViewItem HeaderText="March " />
<telerikPrimitives:TabViewItem HeaderText="April " />
<telerikPrimitives:TabViewItem HeaderText="May " />
<telerikPrimitives:TabViewItem HeaderText="June " />
<telerikPrimitives:TabViewItem HeaderText="July " />
<telerikPrimitives:TabViewItem HeaderText="August " />
<telerikPrimitives:TabViewItem HeaderText="September " />
<telerikPrimitives:TabViewItem HeaderText="October " />
<telerikPrimitives:TabViewItem HeaderText="November " />
<telerikPrimitives:TabViewItem HeaderText="December " />
</telerikPrimitives:RadTabView.Items>
</telerikPrimitives:RadTabView>
 

and the style used for TabViewHeaderItem

XAML
<Style TargetType="telerikPrimitives:TabViewHeaderItem">

1587
Telerik UI for Xamarin

<Setter Property="TextColor" Value="#9E4F2C"/>


<Setter Property="SelectedColor" Value="Blue"/>
</Style>
 

In addition here is how to define the TadView Header using C#:

C#
RadTabView tabView = new RadTabView()
{
HeaderPosition = TabViewHeaderPosition.Bottom,
Header = new Telerik.XamarinForms.Primitives.TabViewHeader()
{
BackgroundColor = (Color)(new
ColorTypeConverter()).ConvertFromInvariantString("#293955"),
OverflowButtonTemplate = new DataTemplate(() =>
{
return new Label()
{
Text = " + ",
BackgroundColor = (Color)(new
ColorTypeConverter()).ConvertFromInvariantString("#CA5100"),
Margin = new Thickness(3, 0, 3, 0)
};
}),
}
};

for (int i = 1; i <= 13; i++)


{
tabView.Items.Add(new Telerik.XamarinForms.Primitives.TabViewItem() { HeaderText =
string.Format("Tab{0} ", i) });
}
 

Additionally, you can work with the already assigned header instead of replacing it with a new one.
For example - tabView.Header.BackgroundColor = Color.Green.

Here is how the overflow button looks after customization:

1588
Telerik UI for Xamarin

A sample Overflow Button Customization example can be found in the TabView/Features folder -
Tab View Header of the SDK Samples Browser application.
 

See Also

 TabViewItem

1589
Telerik UI for Xamarin

Overview
Telerik Templated Picker for Xamarin is a fully customizable picker control which allows you create a
custom picker based on the scenario you want to achieve. You can pick an item from a selector with
a custom template.

Key features
 Selector Template: Custom Picker control allows you to define a template for the items. To
learn more about this, visit Templates article.
 DisplayString Format: You can choose what text to display when an item from the selector
template was picked through the Picker DisplayStringFormat property. For more info on this
check the Key Features - Display String section.
 Flexible Styling API: Take advantage of the styling capabilities of RadTemplated Picker. You
can easily style its Spinners, the Popup and its header and footer. For more details check
Styling article.
 Commands Support: Templated Picker exposes commands that allows you to clear the
selected item - Clear Command and Toggle Command which allows you to open and close
the dialog. More information about Commands support check our Commands article.

Check out RadTemplated Picker Getting Started help article that shows how to use it in a basic
scenario.
 

1590
Telerik UI for Xamarin

See Also
 Visual Structure
 Getting Started
 Templates
 Styling

1591
Telerik UI for Xamarin

Visual Structure
Here are described all visual elements used in the Templated Picker for Xamarin.

Templated Picker Structure before and after selection

Templated Picker Popup Visual Structure

Legend
 Placeholder - the text visualized before picking a value from the popup. Placeholder could be
customized through the PlaceholderTemplate property. For more information review

1592
Telerik UI for Xamarin

Templates article.
 DisplayStringFormat - the text vislualized after an item from the selector is picked.
 SelectedItem - the item which is highlighted when the picker's popup is open.
 Header - the header of the popup For more information review Templates article.
 SelectorTemplate - Defines the template used for displaying the selector of the picker. For
more information review Templates article.
 Footer - the footer of the popup. For more information review Templates article.

See Also
 Getting Started
 Templates
 Styling

1593
Telerik UI for Xamarin

Getting Started with Custom Picker for


Xamarin
This article will guide you through the steps needed to add a basic RadTemplatedPicker control in
your application.

 Setting up the app


 Adding the required Telerik references
 Adding RadTemplatedPicker control

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadTemplatedPicker control you have to install the
Telerik.UI.for.Xamarin.Input nuget package. This nuget will automatically refer the
Telerik.UI.for.Xamarin.Primitives, Telerik.UI.for.Xamarin.Common, and
Telerik.UI.for.Xamarin.DataControls nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadTemplatedPicker component:

Platform Assemblies
Portable Telerik.XamarinForms.Input
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.SkiaSharp.dll
Android Telerik.XamarinForms.Input
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.SkiaSharp.dll
iOS Telerik.XamarinForms.Input

1594
Telerik UI for Xamarin

Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.SkiaSharp.dll
UWP Telerik.XamarinForms.Input
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.SkiaSharp.dll

3. Adding RadTemplatedPicker control


You could use one of the following approaches:

Drag the control from the Toolbox.

Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML or C#.

The snippet below shows a simple RadTemplatedPicker definition:

XAML
<telerikInput:RadTemplatedPicker>
<telerikInput:RadTemplatedPicker.SelectorTemplate>
<ControlTemplate>
<telerikInput:RadCalendar SelectedDate="{TemplateBinding SelectedValue,
Mode=TwoWay}"/>
</ControlTemplate>
</telerikInput:RadTemplatedPicker.SelectorTemplate>
</telerikInput:RadTemplatedPicker>
 

C#
RadTemplatedPicker templatedPicker = new RadTemplatedPicker();
ControlTemplate controlTemplate = new
ControlTemplate(typeof(TemplatedPickerCalendar));
templatedPicker.SelectorTemplate = controlTemplate;
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

C#

1595
Telerik UI for Xamarin

using Telerik.XamarinForms.Input;
 

This is the result:

SDK Browser and QSF applications contain different examples that show RadTemplatedPicker's
main features. You can find the applications in the Examples and QSF folders of your local Telerik UI
for Xamarin installation.
 

See Also
 Visual Structure
 Key Features
 Templates
 Styling

1596
Telerik UI for Xamarin

Templated Picker from Beta to Official


With R2 2020 Official Release of Telerik UI for Xamarin, the RadTemplatedPicker control is now
official. The following article describes the changes made in the Templated Picker in its official
version.

API changes
Placeholder Label Text

Beta Official
Pick a value Select Value

Localization keys
The following table contains the names of the localzation keys which were changed in the official
version of the control:

Beta Official
Pickers_Placeholder TemplatedPicker_PlaceholderLabelText
Pickers_Popup_AcceptButtonText Picker_Popup_AcceptButtonText
Pickers_Popup_RejectButtonText Picker_Popup_CancelButtonText

Visual changes
Border below the Templated Picker text

 BorderThickness(Xamarin.Forms.Thickness): Specifies the border thickness of the picker.


Default value is new Thickness(0,0,0,1).

Header and Footer visibility


With the official version of the control IsHeaderVisible and IsFooterVisible porperties have a public
setter.

By default the header of the TemplatedPicker Popup is visible. In order to hide the header you need
to set IsHeaderVisible property to False. The default value of HeaderLabelText is Select
Value.By default the footer of the TemplatedPicker Popup is visible. In order to hide the footer you
need to set IsFooterVisible to False.

See Also

1597
Telerik UI for Xamarin

 Templates
 Styling

1598
Telerik UI for Xamarin

Key Features
The purpose of this help article is to show you the key features of the Templated(Custom) Picker
control for Xamarin.

DisplayMemberPath
Its purpose is to specify a property of the source object to serve as the visual representation of the
spinner item.

DisplayStringFormat
You can choose what text to display when an item from the spinner was picked through the Picker
DisplayStringFormat property.

SelectedValue
The SelectedValue property is used when you have linked your RadTemplatedPicker to a data
source, and you want to return a value of type object other than the one which is displayed.

Example
Here is a sample example which shows how the SelectedValue and DisplayMemberPath can be
used:

XAML
<telerikInput:RadTemplatedPicker SelectedValue="{Binding FromCity, Mode=TwoWay}"
DisplayMemberPath="Name"
SelectorTemplate="{StaticResource SelectorTemplate}">
<telerikInput:RadTemplatedPicker.SelectorSettings>
<telerikInput:PickerPopupSelectorSettings HeaderTemplate="{StaticResource
HeaderTemplate}"/>
</telerikInput:RadTemplatedPicker.SelectorSettings>
</telerikInput:RadTemplatedPicker>
 

Here is a sample definition of the SelectorTemplate:

XAML
<ControlTemplate x:Key="SelectorTemplate">
<Grid HeightRequest="250">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<dataControls:RadSpinner Grid.Column="0"

1599
Telerik UI for Xamarin

ItemsSource="{Binding Countries}"
SelectedItem="{Binding FromCountry, Mode=TwoWay}"
DisplayMemberPath="Name" />
<dataControls:RadSpinner Grid.Column="1"
ItemsSource="{Binding FromCountry.Cities}"
SelectedItem="{TemplateBinding SelectedValue}"
DisplayMemberPath="Name" />
</Grid>
</ControlTemplate>
 

and for the HeaderTemplate:

XAML
<ControlTemplate x:Key="HeaderTemplate">
<Grid BackgroundColor="DarkGray">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Label Text="Origin Country"
HorizontalOptions="Center"
VerticalOptions="Center"
TextColor="White" />
<Label Grid.Column="1"
Text="Origin City"
HorizontalOptions="Center"
VerticalOptions="Center"
TextColor="White" />
</Grid>
</ControlTemplate>
 

add the following data item for the first spinner:

C#
public class Country : NotifyPropertyChangedBase
{
private string name;

public Country()
{
this.Cities = new ObservableCollection<City>();
}

public string Name


{
get
{
return this.name;
}
set

1600
Telerik UI for Xamarin

{
if (value != this.name)
{
this.UpdateValue(ref this.name, value);
}
}
}

public ObservableCollection<City> Cities { get; }


}
 

add the following data item for the second spinner:

C#
public class City : NotifyPropertyChangedBase
{
private string name;

public string Name


{
get
{
return this.name;
}
set
{
if (value != this.name)
{
this.UpdateValue(ref this.name, value);
}
}
}
}
 

here is a sample definition of the ViewModel:

C#
public class ViewModel : NotifyPropertyChangedBase
{
private Country fromCountry;
private City fromCity;

public ViewModel()
{
this.Countries = new ObservableCollection<Country>
{
new Country
{
Name = "Austria",
Cities =

1601
Telerik UI for Xamarin

{
new City { Name = "Graz" },
new City { Name = "Innsbruck" },
new City { Name = "Linz" },
new City { Name = "Ratz" },
new City { Name = "Salzburg" },
new City { Name = "Vienna" },
new City { Name = "Wolfsberg" },
new City { Name = "Zeltweg" }
}
},
new Country
{
Name = "Belgium",
Cities =
{
new City { Name = "Antwerp" },
new City { Name = "Assesse" },
new City { Name = "Bruges" },
new City { Name = "Charleroi" },
new City { Name = "Lint" },
new City { Name = "Ranst" },
new City { Name = "Schaffen" },
new City { Name = "Veurne" },
new City { Name = "Zingem" },
}
},
new Country
{
Name = "Denmark",
Cities =
{
new City { Name = "Aalborg" },
new City { Name = "Aarhus" },
new City { Name = "Billund" },
new City { Name = "Copenhagen" },
new City { Name = "Karup" },
new City { Name = "Odense" },
new City { Name = "Viborg" },
new City { Name = "Vojens" }
}
},
new Country
{
Name = "France",
Cities =
{
new City { Name = "Aurillac" },
new City { Name = "Belley" },
new City { Name = "Bourg-en-Bresse" },
new City { Name = "Carcassonne" },
new City { Name = "Caen" },
new City { Name = "Deauville" },

1602
Telerik UI for Xamarin

new City { Name = "La Rochelle" },


new City { Name = "Nice" },
new City { Name = "Marseille" },
new City { Name = "Paris - Val-De-Marne" },
new City { Name = "Paris - Val d'Oise" },
new City { Name = "Rodez" }
}
},
new Country
{
Name = "Germany",
Cities =
{
new City { Name = "Baden-Baden" },
new City { Name = "Berlin" },
new City { Name = "Borkum" },
new City{ Name = "Bremen" },
new City{ Name = "Dortmund" },
new City{ Name = "Dresden" },
new City{ Name = "Hamburg" },
new City{ Name = "Hannover" },
new City{ Name = "Leipzig" },
new City{ Name = "Mannheim" },
new City{ Name = "Munich" },
new City{ Name = "Nuremberg" }
}
},
new Country
{
Name = "Italy",
Cities =
{
new City { Name = "Aosta" },
new City { Name = "Bari" },
new City { Name = "Bologna" },
new City { Name = "Parma" },
new City { Name = "Rimini" },
new City { Name = "Rome - Fiumicino" },
new City { Name = "Rome - Ciampino" }
}
},
new Country
{
Name = "Netherlands",
Cities =
{
new City { Name = "Amsterdam" },
new City { Name = "Bonaire" },
new City { Name = "Eindhoven" },
new City { Name = "Maastricht" },
new City { Name = "Rotterdam" }
}
},

1603
Telerik UI for Xamarin

new Country
{
Name = "Portugal",
Cities =
{
new City { Name = "Braga" },
new City { Name = "Cascais" },
new City { Name = "Lisbon" },
new City { Name = "Porto" }
}
},
new Country
{
Name = "Spain",
Cities =
{
new City { Name = "Alicante" },
new City { Name = "Barcelona" },
new City { Name = "Madrid" },
new City { Name = "Seville" },
new City { Name = "Valencia" },
new City { Name = "Zaragoza" }
}
},
new Country
{
Name = "United Kingdom",
Cities =
{
new City { Name = "Bristol Airport" },
new City { Name = "Castle Donington" },
new City { Name = "Liverpool" },
new City { Name = "London City Airport" },
new City { Name = "London Luton" },
new City { Name = "Manchester Airport" },
new City { Name = "Norwich" },
new City { Name = "Southampton" }
}
},
};
}

public Country FromCountry


{
get
{
return this.fromCountry;
}
set
{
if (value != this.fromCountry)
{
this.UpdateValue(ref this.fromCountry, value);

1604
Telerik UI for Xamarin

}
}
}

public City FromCity


{
get
{
return this.fromCity;
}
set
{
if (value != this.fromCity)
{
this.UpdateValue(ref this.fromCity, value);
}
}
}

public ObservableCollection<Country> Countries { get; }


}
 

Set thus defined ViewModel as a BindingContext of the page:

C#
this.BindingContext = new ViewModel();
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

This is the result:

1605
Telerik UI for Xamarin

See Also
 Templates
 Styling

1606
Telerik UI for Xamarin

Templates
Templated Picker for Xamarin provides the following template:

 SelectorTemplate(ControlTemplate): Defines the template used for displaying the selector of


the picker.

In addition to this you can define the following templates provided from the RadPickerBase class:

 PlaceholderTemplate(ControlTemplate): Defines the template visualized for the placeholder.


 DisplayTemplate(ControlTemplate): Defines the template visualized when an item from the
selector was picked.

And using RadPickerBase.SelectorSettings property(of type


Telerik.XamarinForms.Input.PickerPopupSelectorSettings) you can define the following templates:

 HeaderTemplate(ControlTemplate): Defines what will be displayed inside the dialog(popup)


header.
 FooterTemplate(ControlTemplate): Defines what will be displayed inside the dialog(popup)
footer.

Example
Here is a sample Templated Picker definition:

XAML
<telerikInput:RadTemplatedPicker SelectedValue="{Binding FromCity, Mode=TwoWay}"
DisplayMemberPath="Name"
SelectorTemplate="{StaticResource SelectorTemplate}">
<telerikInput:RadTemplatedPicker.SelectorSettings>
<telerikInput:PickerPopupSelectorSettings HeaderTemplate="{StaticResource
HeaderTemplate}"/>
</telerikInput:RadTemplatedPicker.SelectorSettings>
</telerikInput:RadTemplatedPicker>
 

Selector Template
Here is a sample definition of the SelectorTemplate:

XAML
<ControlTemplate x:Key="SelectorTemplate">
<Grid HeightRequest="250">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>

1607
Telerik UI for Xamarin

<dataControls:RadSpinner Grid.Column="0"
ItemsSource="{Binding Countries}"
SelectedItem="{Binding FromCountry, Mode=TwoWay}"
DisplayMemberPath="Name" />
<dataControls:RadSpinner Grid.Column="1"
ItemsSource="{Binding FromCountry.Cities}"
SelectedItem="{TemplateBinding SelectedValue}"
DisplayMemberPath="Name" />
</Grid>
</ControlTemplate>
 

Header Template:
XAML
<ControlTemplate x:Key="HeaderTemplate">
<Grid BackgroundColor="DarkGray">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Label Text="Origin Country"
HorizontalOptions="Center"
VerticalOptions="Center"
TextColor="White" />
<Label Grid.Column="1"
Text="Origin City"
HorizontalOptions="Center"
VerticalOptions="Center"
TextColor="White" />
</Grid>
</ControlTemplate>
 

add the following Business model for the first spinner:

C#
public class Country : NotifyPropertyChangedBase
{
private string name;

public Country()
{
this.Cities = new ObservableCollection<City>();
}

public string Name


{
get
{
return this.name;

1608
Telerik UI for Xamarin

}
set
{
if (value != this.name)
{
this.UpdateValue(ref this.name, value);
}
}
}

public ObservableCollection<City> Cities { get; }


}
 

add the following Business model for the second spinner:

C#
public class City : NotifyPropertyChangedBase
{
private string name;

public string Name


{
get
{
return this.name;
}
set
{
if (value != this.name)
{
this.UpdateValue(ref this.name, value);
}
}
}
}
 

here is a sample definition of the ViewModel:

C#
public class ViewModel : NotifyPropertyChangedBase
{
private Country fromCountry;
private City fromCity;

public ViewModel()
{
this.Countries = new ObservableCollection<Country>
{
new Country
{

1609
Telerik UI for Xamarin

Name = "Austria",
Cities =
{
new City { Name = "Graz" },
new City { Name = "Innsbruck" },
new City { Name = "Linz" },
new City { Name = "Ratz" },
new City { Name = "Salzburg" },
new City { Name = "Vienna" },
new City { Name = "Wolfsberg" },
new City { Name = "Zeltweg" }
}
},
new Country
{
Name = "Belgium",
Cities =
{
new City { Name = "Antwerp" },
new City { Name = "Assesse" },
new City { Name = "Bruges" },
new City { Name = "Charleroi" },
new City { Name = "Lint" },
new City { Name = "Ranst" },
new City { Name = "Schaffen" },
new City { Name = "Veurne" },
new City { Name = "Zingem" },
}
},
new Country
{
Name = "Denmark",
Cities =
{
new City { Name = "Aalborg" },
new City { Name = "Aarhus" },
new City { Name = "Billund" },
new City { Name = "Copenhagen" },
new City { Name = "Karup" },
new City { Name = "Odense" },
new City { Name = "Viborg" },
new City { Name = "Vojens" }
}
},
new Country
{
Name = "France",
Cities =
{
new City { Name = "Aurillac" },
new City { Name = "Belley" },
new City { Name = "Bourg-en-Bresse" },
new City { Name = "Carcassonne" },

1610
Telerik UI for Xamarin

new City { Name = "Caen" },


new City { Name = "Deauville" },
new City { Name = "La Rochelle" },
new City { Name = "Nice" },
new City { Name = "Marseille" },
new City { Name = "Paris - Val-De-Marne" },
new City { Name = "Paris - Val d'Oise" },
new City { Name = "Rodez" }
}
},
new Country
{
Name = "Germany",
Cities =
{
new City { Name = "Baden-Baden" },
new City { Name = "Berlin" },
new City { Name = "Borkum" },
new City{ Name = "Bremen" },
new City{ Name = "Dortmund" },
new City{ Name = "Dresden" },
new City{ Name = "Hamburg" },
new City{ Name = "Hannover" },
new City{ Name = "Leipzig" },
new City{ Name = "Mannheim" },
new City{ Name = "Munich" },
new City{ Name = "Nuremberg" }
}
},
new Country
{
Name = "Italy",
Cities =
{
new City { Name = "Aosta" },
new City { Name = "Bari" },
new City { Name = "Bologna" },
new City { Name = "Parma" },
new City { Name = "Rimini" },
new City { Name = "Rome - Fiumicino" },
new City { Name = "Rome - Ciampino" }
}
},
new Country
{
Name = "Netherlands",
Cities =
{
new City { Name = "Amsterdam" },
new City { Name = "Bonaire" },
new City { Name = "Eindhoven" },
new City { Name = "Maastricht" },
new City { Name = "Rotterdam" }

1611
Telerik UI for Xamarin

}
},
new Country
{
Name = "Portugal",
Cities =
{
new City { Name = "Braga" },
new City { Name = "Cascais" },
new City { Name = "Lisbon" },
new City { Name = "Porto" }
}
},
new Country
{
Name = "Spain",
Cities =
{
new City { Name = "Alicante" },
new City { Name = "Barcelona" },
new City { Name = "Madrid" },
new City { Name = "Seville" },
new City { Name = "Valencia" },
new City { Name = "Zaragoza" }
}
},
new Country
{
Name = "United Kingdom",
Cities =
{
new City { Name = "Bristol Airport" },
new City { Name = "Castle Donington" },
new City { Name = "Liverpool" },
new City { Name = "London City Airport" },
new City { Name = "London Luton" },
new City { Name = "Manchester Airport" },
new City { Name = "Norwich" },
new City { Name = "Southampton" }
}
},
};
}

public Country FromCountry


{
get
{
return this.fromCountry;
}
set
{
if (value != this.fromCountry)

1612
Telerik UI for Xamarin

{
this.UpdateValue(ref this.fromCountry, value);
}
}
}

public City FromCity


{
get
{
return this.fromCity;
}
set
{
if (value != this.fromCity)
{
this.UpdateValue(ref this.fromCity, value);
}
}
}

public ObservableCollection<Country> Countries { get; }


}
 

Set thus defined ViewModel as a BindingContext of the page:

C#
this.BindingContext = new ViewModel();
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

This is the templated picker visual structure:

1613
Telerik UI for Xamarin

A sample Key Features example can be found in the TemplatedPicker/Features folder of the SDK
Samples Browser application.
 

See Also
 Styling

1614
Telerik UI for Xamarin

Custom (Templated) Picker Localization


RadDateTime Picker for Xamarin provides language localization. In short, you can translate the used
across the Templated Picker texts to other languages, so that your app can be adapted to different
regions.

To learn in details about the localization process of Telerik UI for Xamarin components, please go
through the common Localization and Globalization topic.
 

Templated Picker Localization strings


Localization Key Default Value
TemplatedPicker_PlaceholderLabelText Select value
TemplatedPicker_Popup_HeaderLabelText Select value

Common Picker Localizations strings


Localization Key Default Value
Picker_Popup_AcceptButtonText OK
Picker_Popup_CancelButtonText Cancel
Check in the image below how the common localization strings are presented in Templated Picker:

See Also

1615
Telerik UI for Xamarin

 Localization and Globalization

1616
Telerik UI for Xamarin

Events
Templated Picker for Xamarin exposes a SelectionChanged event which is raised when the user
confirms the selected item.

Example
XAML
<telerikInput:RadTemplatedPicker
SelectionChanged="RadTemplatedPicker_SelectionChanged" x:Name="picker">
<telerikInput:RadTemplatedPicker.SelectorTemplate>
<ControlTemplate>
<telerikInput:RadCalendar SelectedDate="{TemplateBinding SelectedValue,
Mode=TwoWay}"/>
</ControlTemplate>
</telerikInput:RadTemplatedPicker.SelectorTemplate>
</telerikInput:RadTemplatedPicker>
 

and the SelectionChanged event, where the sender is the RadTemplatedPicker control

C#
private void RadTemplatedPicker_SelectionChanged(object sender, System.EventArgs e)
{
// implement your logic here
}
 

See Also
 Commands
 Methods
 Templates

1617
Telerik UI for Xamarin

Methods
Templated Picker for Xamarin allows you to clear the selected date/time through its ClearSelection
method

Example
XAML
<StackLayout>
<Button Clicked="OnClearSelectionClicked" Text="clear selection"/>
<telerikInput:RadTemplatedPicker x:Name="picker">
<telerikInput:RadTemplatedPicker.SelectorTemplate>
<ControlTemplate>
<telerikInput:RadCalendar SelectedDate="{TemplateBinding SelectedValue,
Mode=TwoWay}"/>
</ControlTemplate>
</telerikInput:RadTemplatedPicker.SelectorTemplate>
</telerikInput:RadTemplatedPicker>
</StackLayout>
 

and we can clear the selection inside the button click event:

C#
private void OnClearSelectionClicked(object sender, EventArgs e)
{
this.picker.ClearSelection();
}
 

also you will need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

See Also
 Events
 Commands

1618
Telerik UI for Xamarin

Commands
TemplatedPicker Commands
TemplatedPicker for Xamarin exposes the following commands you can use to programmatically
manipulate displaying the popup as well as clearing the selected item:

 ToggleCommand(ICommand): Allows you to show/hide the popup used for selecting an item
from the custom picker.
 ClearCommand(ICommand): Allows you to clear the displayed item.

PopupSelector Commands
Through the popup users can pick an item. The value should be confirmed or rejected through the
OK and Cancel buttons placed on the popup.

TemplatedPicker allows you to add a custom logic for the Accept and Cancel commands which are
executed when OK and Cancel buttons, respectively, are pressed.

 AcceptCommand(ICommand): Defines the command which confirms the current selection of


the picker and closes the popup. AcceptCommandParameter can be used to pass a
parameter to the command execute method.
 CancelCommand(ICommand): Defines the command which rejects the current selection of
the picker and closes the popup. CancelCommandParameter can be used to pass a
parameter to the command execute method.

The Accept and Cancel commands can be applied using the SelectorSettings property of
RadTemplatedPicker. In addition, you can pass command parameters through the
AcceptCommandParameter and CancelCommandParameter properties of the TemplatedPicker
SelectorSettings.

Example
Here is the Templated Picker definition:

XAML
<StackLayout>
<Button Text="Toggle Command" Command="{Binding Source={x:Reference picker},
Path=ToggleCommand}"/>
<Button Text="Clear Command" Command="{Binding Source={x:Reference picker},
Path=ClearCommand}"/>
<telerikInput:RadTemplatedPicker x:Name="picker">
<telerikInput:RadTemplatedPicker.SelectorTemplate>
<ControlTemplate>
<telerikInput:RadCalendar SelectedDate="{TemplateBinding SelectedValue,
Mode=TwoWay}"/>
</ControlTemplate>

1619
Telerik UI for Xamarin

</telerikInput:RadTemplatedPicker.SelectorTemplate>
<telerikInput:RadTemplatedPicker.SelectorSettings>
<telerikInput:PickerPopupSelectorSettings AcceptCommand="{Binding Accept}"
AcceptCommandParameter="{Binding SelectedValue, Source={x:Reference picker}}"
CancelCommand="{Binding Cancel}"
CancelCommandParameter="{Binding SelectedValue, Source={x:Reference picker}}"/>
</telerikInput:RadTemplatedPicker.SelectorSettings>
<telerikInput:RadTemplatedPicker.BindingContext>
<local:ViewModel/>
</telerikInput:RadTemplatedPicker.BindingContext>
</telerikInput:RadTemplatedPicker>
</StackLayout>
 

a sample ViewModel:

C#
public class ViewModel
{
public ICommand Accept { get; set; }
public ICommand Cancel { get; set; }

public ViewModel()
{
this.Accept = new Command(this.OnAccept);
this.Cancel = new Command(this.OnCancel);
}

private void OnAccept(object param)


{
Application.Current.MainPage.DisplayAlert("Value selected", String.Format("New
Value: {0:d}", (DateTime)param), "OK");
// implement your custom logic here
}

private void OnCancel(object param)


{
var message = param != null ? String.Format("Current value: {0:d}",
(DateTime)param) : "Currently no value is selected";
Application.Current.MainPage.DisplayAlert("Value Selection Canceled", message,
"OK");
// implement your custom logic here
}
}
 

also you will need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

1620
Telerik UI for Xamarin

See Also
 Events
 Templates

1621
Telerik UI for Xamarin

Styling
TemplatedPicker Styling
 PlaceholderLabelStyle(of type Style with target type Label): Defines the style applied to the
placeholder label.
 DisplayLabelStyle(of type Style with target type Label): Defines the style applied to the label
which is visualized when item from the selector is picked.

PickerContentView class exposes the following properties for styling the TemplatedPicker Border
and Background Color:

 BackgroundColor(Xamarin.Forms.Color): Defines the background color of the picker.


 BorderColor(Xamarin.Forms.Color): Defines the border color of the picker.
 BorderThickness(Xamarin.Forms.Thickness): Specifies the border thickness of the picker.
Default value is new Thickness(0,0,0,1).
 CornerRadius(Xamarin.Forms.Thinckness): Specifies the corner radius of the picker.

PlaceholderLabel Style

DisplayLabel Style

1622
Telerik UI for Xamarin

Popup Styling
Using the SelectorSettings property (of type
Telerik.XamarinForms.Input.PickerPopupSelectorSettings) of the DatePicker you can modify the
appearance of the dialog (popup). PickerPopupSelectorSettings class exposes the following Style
properties:

 PopupViewStyle(of type Style with target type telerikInput:PickerPopupContentView):


Defines the popup view style.
 HeaderStyle(of type Style with target type telerikInput:PickerPopupHeaderView): Defines the
popup header style.
 HeaderLabelStyle(of type Style with target type Label): Defines the popup header label style.
 FooterStyle(of type Style with target type telerikInput:PickerPopupFooterView): Defines the
popup footer style.
 AcceptButtonStyle(of type Style with target type Button): Defines the Accept button style.
 CancelButtonStyle(of type Style with target type Button): Defines the Cancel button style.

The SelectorSetting also provides the following properties for popup customization:

 PopupOutsideBackgroundColor(Xamarin.Forms.Color): Defines the color outside of the


popup.
 IsPopupModal(bool): Defines a boolean value indicating if the popup should be closed when
tapped outside of the popup. By default the value of the IsPopupModal is false.
 When IsPopupModal="True" the UI behind the popup gets inactive and cannot be used
until the popup is closed.
 When IsPopupModal="False" the popup could be closed when clicking outside the
popup.
 HeaderLabelText(string): Specifies the text visualized in the popup header.

1623
Telerik UI for Xamarin

 IsHeaderVisible(bool): Specifies whether the Popup header is currently visible. By default the
valuse is True.
 IsFooterVisible(bool): Specifies whether the Popup footer is currently visible. By default the
valuse is True.
 AcceptButtonText(string): Defines the text visualized for the accept button. By default the text
is OK.
 CancelButtonText(string): Defines the text visualized for the cancel button. By default the text
is Cancel.

Namespaces
Using one of the following styles PopupViewStyle, HeaderStyle, FooterStyle you need to add the
following namespace

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

Example
Here is a sample example which shows how the styling properties are applied.

A sample Templated Picker definition:

XAML
<telerikInput:RadTemplatedPicker Placeholder="Pick a destination!"
DisplayStringFormat="Destination choosen: {0}"
DisplayLabelStyle="{StaticResource DisplayLabelStyle}"
PlaceholderLabelStyle="{StaticResource DefaultPlaceholderLabelStyle}"
Style="{StaticResource DefaultTemplatedPickerStyle}"
SelectedValue="{Binding FromCity, Mode=TwoWay}"
DisplayMemberPath="Name">
<telerikInput:RadTemplatedPicker.SelectorSettings>
<telerikInput:PickerPopupSelectorSettings>
<telerikInput:PickerPopupSelectorSettings.HeaderTemplate>
<ControlTemplate>
<Grid BackgroundColor="{StaticResource AccentColor}">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Label Text="Origin Country"
Style="{StaticResource PickerHeaderLabelStyle}" />
<Label Grid.Column="1"
Text="Origin City"
Style="{StaticResource PickerHeaderLabelStyle}" />
</Grid>
</ControlTemplate>
</telerikInput:PickerPopupSelectorSettings.HeaderTemplate>

1624
Telerik UI for Xamarin

<telerikInput:PickerPopupSelectorSettings.HeaderStyle>
<Style TargetType="telerikInput:PickerPopupHeaderView">
<Setter Property="HeightRequest" Value="56" />
</Style>
</telerikInput:PickerPopupSelectorSettings.HeaderStyle>
<telerikInput:PickerPopupSelectorSettings.AcceptButtonStyle>
<Style TargetType="Button"
BasedOn="{StaticResource PickerPopupFooterAcceptButton_Style}">
<Setter Property="TextColor" Value="{StaticResource AccentColor}" />
</Style>
</telerikInput:PickerPopupSelectorSettings.AcceptButtonStyle>
<telerikInput:PickerPopupSelectorSettings.CancelButtonStyle>
<Style TargetType="Button"
BasedOn="{StaticResource PickerPopupFooterCancelButton_Style}">
<Setter Property="TextColor" Value="{StaticResource AccentColor}" />
</Style>
</telerikInput:PickerPopupSelectorSettings.CancelButtonStyle>
</telerikInput:PickerPopupSelectorSettings>
</telerikInput:RadTemplatedPicker.SelectorSettings>
<telerikInput:RadTemplatedPicker.SelectorTemplate>
<ControlTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="250" />
</Grid.RowDefinitions>
<telerikPrimitives:RadBorder Grid.ColumnSpan="2"
Style="{StaticResource DefaultRadBorderStyle}" />
<dataControls:RadSpinner Grid.Column="0"
ItemsSource="{Binding Countries}"
SelectedItem="{Binding FromCountry, Mode=TwoWay}"
ItemStyle="{StaticResource ItemStyle}"
SelectedItemStyle="{StaticResource SelectedItemStyle}"
DisplayMemberPath="Name" />
<dataControls:RadSpinner Grid.Column="1"
ItemsSource="{Binding FromCountry.Cities}"
SelectedItem="{TemplateBinding SelectedValue}"
ItemStyle="{StaticResource ItemStyle}"
SelectedItemStyle="{StaticResource SelectedItemStyle}"
DisplayMemberPath="Name" />
</Grid>
</ControlTemplate>
</telerikInput:RadTemplatedPicker.SelectorTemplate>
</telerikInput:RadTemplatedPicker>
 

and here are how the styles are defined in the page resources

PlaceholderLabel Style

1625
Telerik UI for Xamarin

XAML
<Style x:Key="DefaultPlaceholderLabelStyle" TargetType="Label">
<Setter Property="TextColor" Value="#4A4949"/>
<Setter Property="HorizontalTextAlignment" Value="Center"/>
<Setter Property="VerticalTextAlignment" Value="Center"/>
</Style>
 

DisplayLabel Style
XAML
<Style x:Key="DisplayLabelStyle" TargetType="Label">
<Setter Property="TextColor" Value="#4A4949"/>
<Setter Property="HorizontalTextAlignment" Value="Center"/>
<Setter Property="VerticalTextAlignment" Value="Center"/>
</Style>
 

HeaderLabel Style
XAML
<Style x:Key="PickerHeaderLabelStyle"
TargetType="Label">
<Setter Property="TextColor" Value="White" />
<Setter Property="FontAttributes" Value="Bold" />
<Setter Property="HorizontalOptions" Value="Center" />
<Setter Property="VerticalOptions" Value="Center" />
</Style>
 

Footer Style
XAML
<Style x:Key="PickerPopupFooterButtons_BaseStyle"
TargetType="Button">
<Setter Property="BackgroundColor" Value="Transparent"/>
<Setter Property="TextColor" Value="#007AFF"/>
<Setter Property="VerticalOptions" Value="Center"/>
<Setter Property="Margin">
<OnPlatform x:TypeArguments="Thickness">
<On Platform="iOS">0, 0, 20, 0</On>
</OnPlatform>
</Setter>
</Style>
 

AcceptButton Style

1626
Telerik UI for Xamarin

XAML
<Style x:Key="PickerPopupFooterAcceptButton_Style" BasedOn="{StaticResource
PickerPopupFooterButtons_BaseStyle}"
TargetType="Button">
<Setter Property="HorizontalOptions" Value="End"/>
</Style>
 

CancelButton Style
XAML
<Style x:Key="PickerPopupFooterCancelButton_Style" BasedOn="{StaticResource
PickerPopupFooterButtons_BaseStyle}"
TargetType="Button">
<Setter Property="HorizontalOptions" Value="EndAndExpand"/>
</Style>
 

add the following Business model for the first spinner:

C#
public class Country : NotifyPropertyChangedBase
{
private string name;

public Country()
{
this.Cities = new ObservableCollection<City>();
}

public string Name


{
get
{
return this.name;
}
set
{
if (value != this.name)
{
this.UpdateValue(ref this.name, value);
}
}
}

public ObservableCollection<City> Cities { get; }


}
 

add the following Business model for the second spinner:

1627
Telerik UI for Xamarin

C#
public class City : NotifyPropertyChangedBase
{
private string name;

public string Name


{
get
{
return this.name;
}
set
{
if (value != this.name)
{
this.UpdateValue(ref this.name, value);
}
}
}
}
 

here is a sample definition of the ViewModel:

C#
public class ViewModel : NotifyPropertyChangedBase
{
private Country fromCountry;
private City fromCity;

public ViewModel()
{
this.Countries = new ObservableCollection<Country>
{
new Country
{
Name = "Austria",
Cities =
{
new City { Name = "Graz" },
new City { Name = "Innsbruck" },
new City { Name = "Linz" },
new City { Name = "Ratz" },
new City { Name = "Salzburg" },
new City { Name = "Vienna" },
new City { Name = "Wolfsberg" },
new City { Name = "Zeltweg" }
}
},
new Country
{
Name = "Belgium",

1628
Telerik UI for Xamarin

Cities =
{
new City { Name = "Antwerp" },
new City { Name = "Assesse" },
new City { Name = "Bruges" },
new City { Name = "Charleroi" },
new City { Name = "Lint" },
new City { Name = "Ranst" },
new City { Name = "Schaffen" },
new City { Name = "Veurne" },
new City { Name = "Zingem" },
}
},
new Country
{
Name = "Denmark",
Cities =
{
new City { Name = "Aalborg" },
new City { Name = "Aarhus" },
new City { Name = "Billund" },
new City { Name = "Copenhagen" },
new City { Name = "Karup" },
new City { Name = "Odense" },
new City { Name = "Viborg" },
new City { Name = "Vojens" }
}
},
new Country
{
Name = "France",
Cities =
{
new City { Name = "Aurillac" },
new City { Name = "Belley" },
new City { Name = "Bourg-en-Bresse" },
new City { Name = "Carcassonne" },
new City { Name = "Caen" },
new City { Name = "Deauville" },
new City { Name = "La Rochelle" },
new City { Name = "Nice" },
new City { Name = "Marseille" },
new City { Name = "Paris - Val-De-Marne" },
new City { Name = "Paris - Val d'Oise" },
new City { Name = "Rodez" }
}
},
new Country
{
Name = "Germany",
Cities =
{
new City { Name = "Baden-Baden" },

1629
Telerik UI for Xamarin

new City { Name = "Berlin" },


new City { Name = "Borkum" },
new City{ Name = "Bremen" },
new City{ Name = "Dortmund" },
new City{ Name = "Dresden" },
new City{ Name = "Hamburg" },
new City{ Name = "Hannover" },
new City{ Name = "Leipzig" },
new City{ Name = "Mannheim" },
new City{ Name = "Munich" },
new City{ Name = "Nuremberg" }
}
},
new Country
{
Name = "Italy",
Cities =
{
new City { Name = "Aosta" },
new City { Name = "Bari" },
new City { Name = "Bologna" },
new City { Name = "Parma" },
new City { Name = "Rimini" },
new City { Name = "Rome - Fiumicino" },
new City { Name = "Rome - Ciampino" }
}
},
new Country
{
Name = "Netherlands",
Cities =
{
new City { Name = "Amsterdam" },
new City { Name = "Bonaire" },
new City { Name = "Eindhoven" },
new City { Name = "Maastricht" },
new City { Name = "Rotterdam" }
}
},
new Country
{
Name = "Portugal",
Cities =
{
new City { Name = "Braga" },
new City { Name = "Cascais" },
new City { Name = "Lisbon" },
new City { Name = "Porto" }
}
},
new Country
{
Name = "Spain",

1630
Telerik UI for Xamarin

Cities =
{
new City { Name = "Alicante" },
new City { Name = "Barcelona" },
new City { Name = "Madrid" },
new City { Name = "Seville" },
new City { Name = "Valencia" },
new City { Name = "Zaragoza" }
}
},
new Country
{
Name = "United Kingdom",
Cities =
{
new City { Name = "Bristol Airport" },
new City { Name = "Castle Donington" },
new City { Name = "Liverpool" },
new City { Name = "London City Airport" },
new City { Name = "London Luton" },
new City { Name = "Manchester Airport" },
new City { Name = "Norwich" },
new City { Name = "Southampton" }
}
},
};
}

public Country FromCountry


{
get
{
return this.fromCountry;
}
set
{
if (value != this.fromCountry)
{
this.UpdateValue(ref this.fromCountry, value);
}
}
}

public City FromCity


{
get
{
return this.fromCity;
}
set
{
if (value != this.fromCity)
{

1631
Telerik UI for Xamarin

this.UpdateValue(ref this.fromCity, value);


}
}
}

public ObservableCollection<Country> Countries { get; }


}
 

Set thus defined ViewModel as a BindingContext of the page:

C#
this.BindingContext = new ViewModel();
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

This is how the Templated Picker looks when the SelectorSetting properties are applied:

A sample Styling example can be found in the TemplatedPicker/Features folder of the SDK Samples
Browser application.
 

1632
Telerik UI for Xamarin

See Also
 Getting Started
 Templates

1633
Telerik UI for Xamarin

Spinner
RadSpinner for Xamarin is a control which allows you to display items in a list. It also provides an
option to loop through its items. RadSpinner control is used for the DateTime Picker, ListPicker. Also
is could be used inside the Templated Picker SelectorTemplate.

Spinner control inherits from the RadBorder control.


 

Key Features
 ItemsSource(IList): Defines a collection used to generate the content of the spinner.
 IsLooping(bool): Defines a value indicating whether the items should loop infinitely while
scrolling. By default the looping is disabled. In order to enable it set IsLooping="True".
 ItemLength(double): Defines the length of the items in the spinner.
 ItemSpacing(double): Defines the spacing between the items.
 SelectedItem(object): Defines the selected item.
 SelectedIndex(int): Specifies the selected index of the Spinner control.
 DisplayStringFormat(string): Defines the string format used to display the items of the
spinner.
 DisplayMemberPath(string): Specifies a path to the property used to display the items of the
spinner

Templates
 ItemTemplate(DataTemplate): Defines the template for the spinner items
 SelectedItemTemplate(DataTemplate): Defines the template for spinner selected item

Styling
 ItemStyle(Style): Defines the style for the spinner items.
 SelectedItemStyle(Style): Defines the style for the spinner selected item.

Events
 SelectionChanged

Example
Sample examples where RadSpinner control is used can be found in our SDK Browser Application
TemplatedPicker/Features - Styling and KeyFeatures examples.

See Also

1634
Telerik UI for Xamarin

 Templates

1635
Telerik UI for Xamarin

Overview
Telerik Time Picker for Xamarin provides a convenient way for the app users to select a time. Its
items are visualized inside a popup. Time Picker control has a number of features which allows you
to set a time range, time format and fully customize the dialog appearance such as its header and
footer.

Key features
 Spinner Format: Time Picker for Xamarin allows you to use standard or custom time format
string through the TimePicker.SpinnerFormat property. Depending on what format is set, the
picker visualizes spinner controls with prepopulated values to be picked. For more
information check the Time Format String article in our documentation.
 Templates: Time Picker provides templates for its header and footer. Also we have exposed
templates for the picker placeholder and display text. For additional info go to Templates
article.
 DisplayString Format: You can choose what text to be displayed when a time value is
selected using the TimePicker DisplayStringFormat property. For more info on this check the
Key Features - DisplayString Format section.
 Time Range: RadTime Picker allows you to define a time range when setting minimum and
maximum time values and choose a time in between. To learn more about this, visit Key
Features Time Range section.
 Flexible Styling API: Take advantage of the styling capabilities of the RadTimePicker control.

1636
Telerik UI for Xamarin

You can easily style its Spinners, the Popup and its header and footer, the text displayed after
time is selected and many more.
 Commands Support: Time Picker exposes command that allows you to clear the selected
time - Clear Command and Toggle Command that allows you to open and close the dialog.
For more information on this check TimePicker's Commands topic.

Check out Time Picker for Xamarin Getting Started help article that shows how to use it in a basic
scenario.
 

See Also
 Visual Structure
 Getting Started
 Key Features
 Templates
 Styling

1637
Telerik UI for Xamarin

Visual Structure
Here are described all visual elements used in the Time Picker for Xamarin.

Time Picker Structure before and after a time value is


selected

Picker Popup Visual Structure


More information about Spinners refer to the RadSpinner help article.
 

Legend

1638
Telerik UI for Xamarin

 Placeholder - the text visualized before picking a time value. Placeholder can be customized
through the PlaceholderTemplate property.
 DisplayStringFormat - the text visualized after a time value is picked.
 Header - the text displayed in the popup header. It can be set to a direct text through the
HeaderLabelText property or fully customize the popup header using the HeaderTemplate
property
 SpinnerHeader - the text visualized for spinner header depending on the values to be picked.
For example if the SpinnerFormatString is g and AreSpinnerHeadersVisible="True" The text
visualized for spinner header will be Hours Minutes AM/PM.
 Spinner - displays items in a list.
 SelectionHighlight - highlight the currently selected time when the popup is open.
 Footer - the footer of the popup. By default is contains OK and Cancel Buttons. It can be
customized through the FooterTemplate property.

See Also
 Getting Started
 Key Features
 Time Format Strings

1639
Telerik UI for Xamarin

Getting Started with Time Picker for


Xamarin
This article will guide you through the steps needed to add a basic RadTimePicker control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadTimePicker control

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadTimePicker control you have to install the
Telerik.UI.for.Xamarin.Input nuget package. This nuget will automatically refer the
Telerik.UI.for.Xamarin.Primitives, Telerik.UI.for.Xamarin.Common, and
Telerik.UI.for.Xamarin.DataControls nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadTimePicker component:

Platform Assemblies
Portable Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.SkiaSharp.dll
Android Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.SkiaSharp.dll

1640
Telerik UI for Xamarin

iOS Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.SkiaSharp.dll
UWP Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.SkiaSharp.dll

3. Adding RadTimePicker control


You could use one of the following approaches:

Drag the control from the Toolbox.

Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML or C#.

The snippet below shows a simple RadTimePicker definition:

XAML
<telerikInput:RadTimePicker />
 

In addition to this, you need to add the following namespace:


XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

C#
using Telerik.XamarinForms.Input;
 

This is the result:

1641
Telerik UI for Xamarin

SDK Browser and Telerik Xamarin Samples applications contain different examples that show
RadTimePicker's main features. For detailed information on this go to Xamarin Demos Applications
topic.
 

See Also
 Supported Standard Time Format Strings
 Key Features
 Templates
 Styling

1642
Telerik UI for Xamarin

Key Features
The purpose of this help article is to show you the key features of the Time Picker control for
Xamarin.

Time Range
Time Picker allows you to define a time range and choose a time in between through the following
properties:

 MinimumTime(TimeSpan): Defines a time which marks the beginning of the range of the
available time values. The default value is TimeSpan.Zero.
 MaximumTime(TimeSpan): Defines a time which marks the end of the range of the available
time values to choose from. The default value is TimeSpan(23, 59, 59).

Example
XAML
<telerikInput:RadTimePicker MinimumTime="8:00:00"
MaximumTime="19:00:00"/>
 

Current Selected Time


 Time(TimeSpan?): Defines the current time selection. The default value is null.

Example
XAML
<telerikInput:RadTimePicker Time="10:30:00"/>
 

Incremental Time Steps


By default the TimePicker increments each part of its time values by one step. You can change the
default setup using the following properties:

 HourStep(int): Controls the incremental step of the hour value. Default value is 1.
 MinuteStep(int): Controls the incremental step of the minute value. Default value is 1.
 SecondStep(int): Controls the incremental step of the second value. Default value is 1.

XAML
<telerikInput:RadTimePicker HourStep="2"
MinuteStep="10"

1643
Telerik UI for Xamarin

SecondStep="30"/>
 

DefaultHighlightedTime
RadTime Picker DefaultHighlightedTime(TimeSpan) defines the System.TimeSpan which will be
used to pre-scroll each spinner when RadTimePicker.Time property is set to null.

Example
XAML
<telerikInput:RadTimePicker DefaultHighlightedTime="11:30:00"
SpinnerFormat="t"
AreSpinnerHeadersVisible="False"/>
 

DisplayString Format
 DisplayStringFormat(string): Defines the format of the string that will be visualized when the
picker dialog is closed.

The format set for DisplayStringFormat should be a valid time format.


 

Example
Here is a sample Time Picker definition:

XAML
<telerikInput:RadTimePicker DefaultHighlightedTime="11:30:00"
SpinnerFormat="t"
AreSpinnerHeadersVisible="False"/>
 

A sample Key Features example can be found in the TimePicker/Features folder of the SDK Samples
Browser application.
 

See Also
 Templates
 Time Format Strings
 Styling
 Selection
 Commands

1644
Telerik UI for Xamarin

Spinner Format
Time Picker for Xamarin allows you to use standard or custom time format strings through the
SpinnerFormat property. Depending on what format is set, the picker visualizes spinner controls with
prepopulated values to be picked.

 SpinnerFormat(string): Defines the string format for the spinners. The default format is "g".

Standard Тime Format Strings


The available standard date and time format strings that can be set to the SpinnerFormat property
are described in the table below:

Supported Standard Time Format String Description


"G" Short Date and Long Time Format Specifier
"g" Short Date and Short Time Format Specifier
"T" Long Time Format Specifier
"t" Short Time Format Specifier
For more information on different format go to Standard Date and Time Format Strings topic on
Microsoft Docs.
 

Custom Time Format String


The available custom time format strings that can be set to the SpinnerFormat property are
described in the table below:

Supported Custom Time Format Strings


"H"
"HH"
"h"
"hh"
"m"
"mm"
"s"
"ss"
"t"

1645
Telerik UI for Xamarin

"tt"
For more details on different formats go to Custom Date and Time Format Strings topic on Microsoft
Docs.
 

Supported Separators
When SpinnerFormat is set and device culture is changed, the separators used for the format string
won't be changed. Check below a list of the available separators:

Supported Time Separators Formats


"-"
"."
"'"
""
":"
"/"

Example
SpinnerFormat="H:mm"
XAML
<telerikInput:RadTimePicker SpinnerFormat="H:mm" />
 

And the result:

1646
Telerik UI for Xamarin

See Also
 Templates
 Styling
 Commands

1647
Telerik UI for Xamarin

Templates
In case the default templates of the TimePicker control do not suit your needs, you can easily define
a custom template. The available templates for customizing are:

 PlaceholderTemplate(ControlTemplate): Defines the template visualized for the placeholder.


 DisplayTemplate(ControlTemplate): Defines the template visualized when the picked time is
displayed.
 HeaderTemplate(ControlTemplate): Defines what will be displayed inside the dialog(popup)
header.
 FooterTemplate(ControlTemplate): Defines what will be displayed inside the dialog(popup)
footer.

The snippet below shows a sample RadTimePicker definition with the listed above template
properties applied:

Let's add the templates definition to the page resources:

PlaceholderTemplate
XAML
<ControlTemplate x:Key="placeholderTemplate">
<Button Text="Pick a time"
FontAttributes="Bold"
TextColor="White"
BackgroundColor="#B73562"
HeightRequest="50" Command="{TemplateBinding ToggleCommand}" />
</ControlTemplate>
 

DisplayTemplate
XAML
<ControlTemplate x:Key="displayTemplate">
<Button Text="{TemplateBinding DisplayString}"
TextColor="White"
BackgroundColor="#7BAEFF"
HeightRequest="50"
Command="{TemplateBinding ToggleCommand}" />
</ControlTemplate>
 

1648
Telerik UI for Xamarin

HeaderTemplate
XAML
<ControlTemplate x:Key="headerTemplate">
<Label Text="Time Picker"
TextColor="White"
VerticalTextAlignment="Center"
HorizontalTextAlignment="Center"
BackgroundColor="#B73562"/>
</ControlTemplate>
 

FooterTemplate
XAML
<ControlTemplate x:Key="footerTemplate">
<StackLayout Orientation="Horizontal" Spacing="0"
HorizontalOptions="FillAndExpand" BackgroundColor="#B73562">
<Button Text="No"
TextColor="White"
BackgroundColor="Transparent"
Command="{TemplateBinding CancelCommand}" />
<Button Text="Yes"
TextColor="White"
BackgroundColor="Transparent"
Command="{TemplateBinding AcceptCommand}" />
</StackLayout>
</ControlTemplate>
 

1649
Telerik UI for Xamarin

In addition, you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

A sample Custom Templates example can be found in the TimePicker/Features folder of the SDK
Samples Browser application.
 

See Also
 Suppoted Standard Time Format Strings
 Key Features
 Styling

1650
Telerik UI for Xamarin

Тime Picker Localization


RadTime Picker for Xamarin provides language localization. In short, you can translate the used
across the Time Picker texts to other languages, so that your app can be adapted to different
regions.

To learn in details about the localization process of Telerik UI for Xamarin components, please go
through the common Localization and Globalization topic.
 
The sections below list all the localization keys used in Time Picker Spinners.

Time Spinners Localization Keys


Localization Key Default Value
TimePicker_Popup_HeaderLabelText Select Time
TimePicker_PlaceholderLabelText Select Time

Common Picker Localizations strings


Localization Key Default Value
Picker_AmPmSpinnerHeaderLabelText AM/PM
Picker_HourSpinnerHeaderLabelText Hours
Picker_MinuteSpinnerHeaderLabelText Minutes
Picker_SecondSpinnerHeaderLabelText Seconds
Picker_Popup_AcceptButtonText OK
Picker_Popup_CancelButtonText Cancel
Check in the image below how the localization strings are presented in Time Picker:

1651
Telerik UI for Xamarin

See Also
 Localization and Globalization

1652
Telerik UI for Xamarin

Selection
RadTimePicker control enables the app users to quickly and easily select a time value. This topic will
go through the provided by the TimePicker API related to time selection.

Important Properties
 Time(TimeSpan?): Defines the current time selection. The default value is null.

Check below a quick example of Time property usage:

XAML
<telerikInput:RadTimePicker Time="10:30:00"/>
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

Methods
RadTimePicker allows you to cancel the selected time through its ClearSelection method.

XAML
<StackLayout>
<Button Text="Clear Selection" Clicked="OnClearSelectionClicked"/>
<telerikInput:RadTimePicker x:Name="timePicker"/>
</StackLayout>
 

Call ClearSelection inside the button click event - as a result Time property will be updated to null.

C#
private void OnClearSelectionClicked(object sender, EventArgs e)
{
this.dateTimePicker.ClearSelection();
}
 

Events
RadTime Picker exposes a SelectionChanged event which is raised when the user picks a time

1653
Telerik UI for Xamarin

value.

XAML
<telerikInput:RadTimePicker x:Name="timePicker"
SelectionChanged="TimePicker_SelectionChanged"/>
 

Add the SelectionChanged event, where the sender is of type object, but can be cast to
RadTimePicker type:

C#
private void TimePicker_SelectionChanged(object sender, EventArgs e)
{
// implement your logic here
}
 

See Also
 Key Features
 Templates
 Commands

1654
Telerik UI for Xamarin

Commands
TimePicker Commands
RadTime Picker exposes the following commands you can use to programmatically manipulate
displaying the popup as well as clearing the selected time:

 ToggleCommand(ICommand): Allows you to show/hide the popup used for selecting a time
value.
 ClearCommand(ICommand): Allows you to clear the selected time.

Example for ToggleCommand and ClearCommand

XAML
<StackLayout>
<Button Text="Toggle Popup" Command="{Binding Source={x:Reference timePicker},
Path=ToggleCommand}"/>
<Button Text="Clear Selected Time" Command="{Binding Source={x:Reference
timePicker}, Path=ClearCommand}"/>
<telerikInput:RadTimePicker x:Name="timePicker" />
</StackLayout>
 

also you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

PopupSelector Commands
Through the popup users can pick a time. The time value should be confirmed or rejected through
the OK and Cancel buttons placed on the popup.

RadTimePicker allows you to add a custom logic for the Accept and Cancel commands which are
executed when OK and Cancel buttons, respectively, are pressed.

 AcceptCommand(ICommand): Defines the command which confirms the current selection of


the picker and closes the popup. AcceptCommandParameter can be used to pass a
parameter to the command execute method.
 CancelCommand(ICommand): Defines the command which rejects the current selection of
the picker and closes the popup. CancelCommandParameter can be used to pass a
parameter to the command execute method.

The Accept and Cancel commands can be applied using the SelectorSettings property of
RadTimePicker. In addition, you can pass command parameters through the

1655
Telerik UI for Xamarin

AcceptCommandParameter and CancelCommandParameter properties of the TimePicker


SelectorSettings.

Here is a quick example on how they could be set:

Example for AcceptCommand and CancelCommand

XAML
<telerikInput:RadTimePicker x:Name="timePicker">
<telerikInput:RadTimePicker.SelectorSettings>
<telerikInput:PickerPopupSelectorSettings AcceptCommand="{Binding Accept}"
AcceptCommandParameter="{Binding Time, Source={x:Reference timePicker}}"
CancelCommand="{Binding Cancel}"
CancelCommandParameter="{Binding Time, Source={x:Reference timePicker}}"/>
</telerikInput:RadTimePicker.SelectorSettings>
</telerikInput:RadTimePicker>
 

Let's add a sample ViewModel class:

C#
public class ViewModel
{
public ICommand Accept { get; set; }
public ICommand Cancel { get; set; }

public ViewModel()
{
this.Accept = new Command(this.OnAccept);
this.Cancel = new Command(this.OnCancel);
}

private void OnAccept(object param)


{
Application.Current.MainPage.DisplayAlert("Time selected", "New time: " +
(TimeSpan)param, "OK");
// implement your custom logic here
}

private void OnCancel(object param)


{
var message = param != null ? "Current time: " + (TimeSpan)param : "Currently
no time is selected";
Application.Current.MainPage.DisplayAlert("Time Selection Canceled", message,
"OK");
// implement your custom logic here
}
}
 

See Also

1656
Telerik UI for Xamarin

 Key Features
 Templates
 Selection

1657
Telerik UI for Xamarin

Styling
TimePicker Styling
Time Picker control for Xamаrin provides the following Style properties for customizing its look:

 SpinnerStyle(of type Style with target type telerikDataControls:RadSpinner): Defines the


style applied to the spinner item and selected item.
 SpinnerHeaderStyle(of type Style with target type Xamarin.Forms.Label): Specifies the style
applied to the spinner header labels.
 SelectionHighlightStyle(of type Style with target type telerikPrimitives:RadBorder): Specifies
the style applied to the selection inside the popup.
 PlaceholderLabelStyle(of type Style with target type Xamarin.Forms.Label): Defines the style
applied to the placeholder label.
 DisplayLabelStyle(of type Style with target type Xamarin.Forms.Label): Defines the style
applied to the label which is visualized when time is selected.

In addition, RadTimePicker exposes properties for specifying its border style and background color,
namely:

 BackgroundColor(Xamarin.Forms.Color): Defines the background color of the picker.


 BorderColor(Xamarin.Forms.Color): Defines the border color of the picker.
 BorderThickness(Xamarin.Forms.Thickness): Specifies the border thickness of the picker.
Default value is new Thickness(0,0,0,1).
 CornerRadius(Xamarin.Forms.Thinckness): Specifies the corner radius of the picker.

Popup Styling
Using the SelectorSettings property (of type
Telerik.XamarinForms.Input.PickerPopupSelectorSettings) of the TimePicker you can modify the
appearance of the dialog (popup). PickerPopupSelectorSettings class exposes the following Style
properties:

 PopupViewStyle(of type Style with target type telerikInput:PickerPopupContentView):


Defines the popup view style.
 HeaderStyle(of type Style with target type telerikInput:PickerPopupHeaderView): Defines the
popup header style.
 HeaderLabelStyle(of type Style with target type Xamarin.Forms.Label): Defines the popup
header label style.
 FooterStyle(of type Style with target type telerikInput:PickerPopupFooterView): Defines the
popup footer style.
 AcceptButtonStyle(of type Style with target type Xamarin.Forms.Button): Defines the Accept
button style.
 CancelButtonStyle(of type Style with target type Xamarin.Forms.Button): Defines the Cancel
button style.

The SelectorSettings also provides the following properties for popup customization:

1658
Telerik UI for Xamarin

 PopupOutsideBackgroundColor(Xamarin.Forms.Color): Defines the color outside of the


popup.
 IsPopupModal(bool): Defines a boolean value indicating if the popup should be closed when
tapped outside of the popup.
 When IsPopupModal="True" the UI behind the popup gets inactive and cannot be used
until the popup is closed.
 When IsPopupModal="False" the popup could be closed when clicking outside the
popup. By default the value of the IsPopupModal is false.
 HeaderLabelText(string): Specifies the text visualized in the popup header.
 IsHeaderVisible(bool): Specifies whether the Popup header is currently visible. By default the
valuse is True.
 IsFooterVisible(bool): Specifies whether the Popup footer is currently visible. By default the
valuse is True.
 AcceptButtonText(string): Defines the text visualized for the accept button. By default the text
is OK.
 CancelButtonText(string): Defines the text visualized for the cancel button. By default the text
is Cancel.

Namespaces
When defining some of these Styles you would need to include additional namespaces, so that the
target types are properly resolved.

Using PopupViewStyle, HeaderStyle or FooterStyle you will need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

Using SelectionHighlightStyle, TabStripStyle you need to add the following namespace:

XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
 

Using SpinnerStyle you need to add the following namespace:

XAML
xmlns:telerikDatacontrols="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te
lerik.XamarinForms.DataControls"
 

Example
Here is a sample example that shows how the styling properties are applied.

Let's have the following Time Picker definition:

1659
Telerik UI for Xamarin

XAML
<telerikInput:RadTimePicker SpinnerHeaderStyle="{StaticResource spinnerHeaderStyle}"
SpinnerStyle="{StaticResource spinnerStyle}"
SelectionHighlightStyle="{StaticResource selectionHighlightStyle}"
DisplayLabelStyle="{StaticResource displayLabelStyle}"
PlaceholderLabelStyle="{StaticResource placeholderLabelStyle}"
DisplayStringFormat="HH:mm">
<telerikInput:RadTimePicker.SelectorSettings>
<telerikInput:PickerPopupSelectorSettings
PopupOutsideBackgroundColor="#D9D9D9CC"
PopupViewStyle="{StaticResource popupViewStyle}"
HeaderStyle="{StaticResource headerStyle}"
HeaderLabelText="Time Picker"
HeaderLabelStyle="{StaticResource headerLabelStyle}"
FooterStyle="{StaticResource footerStyle}"
AcceptButtonStyle="{StaticResource acceptButtonStyle}"
CancelButtonStyle="{StaticResource cancelButtonStyle}"/>
</telerikInput:RadTimePicker.SelectorSettings>
</telerikInput:RadTimePicker>
 

And here are how the styles are defined in the page resources.

Spinner Style

XAML
<Style TargetType="telerikDataControls:RadSpinner" x:Key="spinnerStyle">
<Setter Property="ItemStyle">
<Setter.Value>
<Style TargetType="telerikDataControls:SpinnerItemView">
<Setter Property="TextColor" Value="#797979" />
<Setter Property="BackgroundColor" Value="#F2F2F2" />
<Setter Property="CornerRadius" Value="10" />
<Setter Property="Margin" Value="6, 4" />
</Style>
</Setter.Value>
</Setter>
<Setter Property="SelectedItemStyle">
<Setter.Value>
<Style TargetType="telerikDataControls:SpinnerItemView">
<Setter Property="TextColor" Value="#00B5DC" />
<Setter Property="BackgroundColor" Value="#E4F3F9" />
<Setter Property="CornerRadius" Value="10" />
<Setter Property="Margin" Value="6, 4" />
</Style>
</Setter.Value>
</Setter>
</Style>
 

SpinnerHeader Style

1660
Telerik UI for Xamarin

XAML
<Style TargetType="Label" x:Key="spinnerHeaderStyle">
<Setter Property="TextColor" Value="Black"/>
<Setter Property="FontAttributes" Value="Bold"/>
<Setter Property="HorizontalOptions" Value="FillAndExpand"/>
<Setter Property="VerticalOptions" Value="FillAndExpand"/>
<Setter Property="HorizontalTextAlignment" Value="Center"/>
<Setter Property="VerticalTextAlignment" Value="Center"/>
</Style>
 

SelectionHighlight Style

XAML
<Style TargetType="telerikPrimitives:RadBorder" x:Key="selectionHighlightStyle">
<Setter Property="BorderColor" Value="#00B5DC"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Padding" Value="0,6,0,6"/>
<Setter Property="HeightRequest" Value="40"/>
<Setter Property="VerticalOptions" Value="Center"/>
</Style>
 

PlaceholderLabel Style

XAML
<Style TargetType="Label" x:Key="placeholderLabelStyle">
<Setter Property="TextColor" Value="#4A4949"/>
<Setter Property="VerticalTextAlignment" Value="Center"/>
<Setter Property="HorizontalTextAlignment" Value="Center"/>
<Setter Property="HeightRequest" Value="50"/>
</Style>
 

DisplayLabel Style

XAML
<Style TargetType="Label" x:Key="displayLabelStyle">
<Setter Property="TextColor" Value="Black"/>
<Setter Property="VerticalTextAlignment" Value="Center"/>
<Setter Property="HorizontalTextAlignment" Value="Center"/>
<Setter Property="HeightRequest" Value="50"/>
</Style>
 

PopupView Style

XAML
<Style TargetType="telerikInput:PickerPopupContentView" x:Key="popupViewStyle">
<Setter Property="BackgroundColor" Value="White"/>

1661
Telerik UI for Xamarin

<Setter Property="WidthRequest" Value="270"/>


</Style>
 

Header Style

XAML
<Style TargetType="telerikInput:PickerPopupHeaderView" x:Key="headerStyle">
<Setter Property="BackgroundColor" Value="#00B5DC"/>
<Setter Property="HeightRequest" Value="60"/>
<Setter Property="Margin" Value="0"/>
<Setter Property="Padding" Value="0"/>
<Setter Property="HorizontalOptions" Value="FillAndExpand"/>
<Setter Property="VerticalOptions" Value="FillAndExpand"/>
</Style>
 

HeaderLabel Style

XAML
<Style TargetType="Label" x:Key="headerLabelStyle">
<Setter Property="TextColor" Value="White"/>
<Setter Property="HorizontalOptions" Value="Center"/>
<Setter Property="VerticalOptions" Value="Center"/>
<Setter Property="FontSize" Value="Title"/>
</Style>
 

Footer Style

XAML
<Style TargetType="telerikInput:PickerPopupFooterView" x:Key="footerStyle">
<Setter Property="BackgroundColor" Value="Transparent"/>
</Style>
 

AcceptButton Style

XAML
<Style TargetType="Button" x:Key="acceptButtonStyle">
<Setter Property="BackgroundColor" Value="Transparent"/>
<Setter Property="Text" Value="OK"/>
<Setter Property="TextColor" Value="#00B5DC"/>
</Style>
 

CancelButton Style

XAML
<Style TargetType="Button" x:Key="cancelButtonStyle">

1662
Telerik UI for Xamarin

<Setter Property="BackgroundColor" Value="Transparent"/>


<Setter Property="Text" Value="X"/>
<Setter Property="TextColor" Value="#00B5DC"/>
</Style>
 

Namespaces

In addition, add the following namespaces:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te
lerik.XamarinForms.DataControls"
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
 

This is how the Time Picker control looks when the styles described above are applied:

A sample Styling example can be found in the TimePicker/Features folder of the SDK Samples
Browser application.
 

See Also
 Key Features
 Custom Templates

1663
Telerik UI for Xamarin

 Commands
 Visual Structure

1664
Telerik UI for Xamarin

Overview
Telerik TimeSpan Picker for Xamarin provides an easy way to select a time duration. TimeSpan
control represents a time interval and allows you to set a time range between two times measured in
numbers of days, hours, minutes and seconds. The Flexible Styling API gives you the opportunity to
fully customize the dialog appearance such as its header and footer.

Key features
 Spinner Format: TimeSpan Picker for Xamarin allows you to use standard or custom
timespan format string through the TimeSpanPicker.SpinnerFormat property. Depending on
what format is set, the picker visualizes spinner controls with prepopulated values to be
picked. For more information check the TimeSpan Format String article in our documentation.
 Templates: TimeSpan Picker provides templates for its header and footer. Also we have
exposed templates for the picker placeholder and display text. For additional info go to
Templates article.
 DisplayString Format: You can choose what text to be displayed when a time interval is
selected using the TimeSpanPicker DisplayStringFormat property. For more info on this
check the Key Features - DisplayString Format section.
 Time Range: RadTimeSpan Picker allows you to define a time range when setting minimum
and maximum time values and choose a time in between. To learn more about this, visit Key
Features Time Range section.
 Flexible Styling API: Take advantage of the styling capabilities of the RadTimeSpanPicker

1665
Telerik UI for Xamarin

control. You can easily style its Spinners, the Popup and its header and footer, the text displayed
after time is selected and many more.
 Commands Support: TimeSpan Picker exposes command that allows you to clear the
selected time interval - Clear Command and Toggle Command that allows you to open and
close the dialog. More information about Commands support check our help article here.

Check out TimeSpan Picker for Xamarin Getting Started help article that shows how to use it in a
basic scenario.
 

See Also
 Key Features
 Templates
 Commands

1666
Telerik UI for Xamarin

Visual Structure
Here are described all visual elements used in the TimeSpan Picker for Xamarin.

TimeSpan Picker Structure before and after time interval


selection.

Picker Popup Visual Structure


Currently, the RadTimeSpan Picker does not provide spinners for Milliseconds.
 
More information about Spinners refer to the RadSpinner help article.
 

1667
Telerik UI for Xamarin

Legend
 Placeholder - the text visualized before picking a date/time. Placeholder could be customized
through the PlaceholderTemplate property.
 DisplayStringFormat - the text vislualized after a date/time is picked.
 Header and HeaderLabelText- the text displayed in the popup header. It could se set a direct
text through the HeaderLabelText property or fully customize the popup header using the
HeaderTemplate property.
 SpinnersHeader - the text visualized for spinner header depending on the values to be
picked. For example if the SpinnerFormat is g the text visualized for spinner header will be
Days Hours Minutes Seconds.
 Spinner - displays time interval values in a list.
 SelectionHighlight - highlisht the current selected time interval when the popup is open.
 Footer - the footer of the popup. By default is contains OK and Cancel Buttons. It could be
customized through the FooterTemplate property.

See Also
 Key Features
 Templates
 Commands

1668
Telerik UI for Xamarin

Getting Started with TimeSpan Picker for


Xamarin
This article will guide you through the steps needed to add a basic RadTimeSpanPicker control in
your application.

 Setting up the app


 Adding the required Telerik references
 Adding RadDatePicker control

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadTimeSpanPicker control you have to install the
Telerik.UI.for.Xamarin.Input nuget package. This nuget will automatically refer the
Telerik.UI.for.Xamarin.Primitives, Telerik.UI.for.Xamarin.Common, and
Telerik.UI.for.Xamarin.DataControls nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadTimeSpanPicker component:

Platform Assemblies
Portable Telerik.XamarinForms.Input
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.SkiaSharp.dll
Android Telerik.XamarinForms.Input
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.SkiaSharp.dll

1669
Telerik UI for Xamarin

iOS Telerik.XamarinForms.Input
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.SkiaSharp.dll
UWP Telerik.XamarinForms.Input
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.SkiaSharp.dll

3. Adding RadTimeSpanPicker control


You could use one of the following approaches:

Drag the control from the Toolbox.

Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML or C#.

The snippet below shows a simple RadTimeSpanPicker definition:

XAML
<telerikInput:RadTimeSpanPicker />
 

In addition to this, you need to add the following namespace:


XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

C#
using Telerik.XamarinForms.Input;
 

This is the result:

1670
Telerik UI for Xamarin

SDK Browser and Telerik Xamarin Samples applications contain different examples that show
RadTimePicker's main features. For detailed information on this go to Xamarin Demos Applications
topic.
 

See Also
 Suppoted Standard TimeSpan Format Strings
 Key Features
 Templates
 Styling

1671
Telerik UI for Xamarin

Spinner Format
TimeSpan Picker for Xamarin allows you to use standard or custom timespan format strings through
the SpinnerFormat property. Depending on what format is set, the picker visualizes spinner controls
with prepopulated values to be picked.

 SpinnerFormat(string): Defines the string format for the spinners. The default format is "g".

Standard TimeSpan Format Strings


The available Standard TimeSpan Format Strings which can be set to the SpinnerFormat property
are described in the table below:

Supported Standard TimeSpan Format String Description


"G" General Long "G" format specifier
"g" General Short "g" format specifier
"c" Constant "c" format specifier
You can set only short Standard TimeSpan Format Strings to the TimeSpan Picker control.
 

Custom TimeSpan Format Strings


The available Custom TimeSpan Format Strings which can be set to the SpiinerFormat property are
described in the table below:

Supported Custom TimeSpan Format Strings


"d"
"dd"
"ddd"
"dddd"
"h"
"hh"
"m"
"mm"
"s"
"ss"
You can set only short Custom TimeSpan Format Strings to the TimeSpan Picker control.
 

1672
Telerik UI for Xamarin

Supported Separators
When SpinnerFormat is set and device culture is changed, the separators used for the format string
won't be changed:

Supported Separator Formats


"-"
"."
","
""
":"
"/"

See Also
 Templates
 Styling
 Selection
 Commands

1673
Telerik UI for Xamarin

Key Features
The purpose of this help article is to show you the key features of the TimeSpan Picker control for
Xamarin.

TimeSpan Range
Date Picker allows you to define a date range and choose a date in between through the following
properties:

 MinimumTime(TimeSpan): Defines the lowest limit of the available selection range. The
default value is TimeSpan(0, 0, 0, 0, 0).
 MaximumTime(TimeSpan): Defines the upper limit of the available selection range. The
default value is TimeSpan(30, 23, 59, 59).

If negaive value is set for MinimumTime, the TimeSpan Picker will coerce this value to minimum
value - TimeSpan(0, 0, 0, 0, 0).
 

Example
XAML
<telerikInput:RadTimeSpanPicker MinimumTime="0:0:00:00"
MaximumTime="8:00:00:0"/>
 

Current Selected Time Interval


 Time(TimeSpan?): Defines the current selection of time interval. The default value is null.

Example
XAML
<telerikInput:RadTimeSpanPicker Time="5:10:30:00"/>
 

Incremental Time Steps


By defaul the TimeSpan Picker increments each part of its time values by one step. You can change
the default setup using the following properties:

 DayStep(int): Controls the incremental step of the day value. Default value is 1.
 HourStep(int): Controls the incremental step of the hour value. Default value is 1.
 MinuteStep(int): Controls the incremental step of the minute value. Default value is 1.
 SecondStep(int): Controls the incremental step of the second value. Default value is 1.

1674
Telerik UI for Xamarin

Example
XAML
<telerikInput:RadTimeSpanPicker DayStep="2"
HourStep="4"
MinuteStep="10"
SecondStep="30"/>
 

DefaultHighlightedTime Interval
RadTimeSpan Picker DefaultHighlightedTime(TimeSpan) defines the System.TimeSpan which will
be visualized when there is no selection.

Example
XAML
<telerikInput:RadTimeSpanPicker DefaultHighlightedTime="5:10:30:00"
SpinnerFormat="G"
AreSpinnerHeadersVisible="False"/>
 

DisplayString Format
 DisplayStringFormat(string): Defines the format of the string that will be visualized when the
picker dialog is closed.

The format set for DisplayStringFormat should be a valid timespan format.


 
A sample Key Features example can be found in the TimeSpanPicker/Features folder of the SDK
Samples Browser application.
 

See Also
 Templates
 Styling
 Commands
 Selection

1675
Telerik UI for Xamarin

Templates
If the default templates of the control do not suit your needs, you can easily define custom ones. The
available templates for customizing are:

 PlaceholderTemplate(ControlTemplate): Defines the template visualized for the placeholder.


 DisplayTemplate(ControlTemplate): Defines the template visualized when the picked
date/time is displayed.
 HeaderTemplate(ControlTemplate): Defines what will be displayed inside the dialog(popup)
header.
 FooterTemplate(ControlTemplate): Defines what will be displayed inside the dialog(popup)
footer.

PlaceholderTemplate
XAML
<ControlTemplate x:Key="Picker_PlaceholderView_ControlTemplate">
<Grid>
<Grid.GestureRecognizers>
<TapGestureRecognizer Command="{TemplateBinding ToggleCommand}" />
</Grid.GestureRecognizers>
<Label Text="{TemplateBinding Placeholder}"
Style="{TemplateBinding PlaceholderLabelStyle}"
AutomationId="PickerPlaceholderLabel"/>
</Grid>
</ControlTemplate>
 

DisplayTemplate
XAML
<ControlTemplate x:Key="Picker_DisplayView_ControlTemplate">
<Grid>
<Grid.GestureRecognizers>
<TapGestureRecognizer Command="{TemplateBinding ToggleCommand}" />
</Grid.GestureRecognizers>
<Label Text="{TemplateBinding DisplayString}"
Style="{TemplateBinding DisplayLabelStyle}"
AutomationId="PickerDisplayLabel"/>
</Grid>
</ControlTemplate>
 

HeaderTemplate
XAML

1676
Telerik UI for Xamarin

<ControlTemplate x:Key="PopupView_Header_ControlTemplate">
<telerikPrimitives:RadBorder BackgroundColor="{TemplateBinding BackgroundColor}"
BorderColor="{TemplateBinding BorderColor}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="{TemplateBinding CornerRadius}">
<Label Text="{TemplateBinding HeaderLabelText}"
Style="{TemplateBinding HeaderLabelStyle}"
AutomationId="PickerPopupHeaderLabel"/>
</telerikPrimitives:RadBorder>
</ControlTemplate>
 

FooterTemplate
XAML
<ControlTemplate x:Key="PopupView_Footer_ControlTemplate">
<telerikPrimitives:RadBorder BackgroundColor="{TemplateBinding BackgroundColor}"
BorderColor="{TemplateBinding BorderColor}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="{TemplateBinding CornerRadius}">
<OnPlatform x:TypeArguments="View">
<On Platform="Android, iOS">
<StackLayout Orientation="Horizontal" Spacing="0" HorizontalOptions="End">
<Button Text="{TemplateBinding CancelButtonText}"
Style="{TemplateBinding CancelButtonStyle}"
Command="{TemplateBinding CancelCommand}"
AutomationId="PickerPopupCancelButton"/>
<Button Text="{TemplateBinding AcceptButtonText}"
Style="{TemplateBinding AcceptButtonStyle}"
Command="{TemplateBinding AcceptCommand}"
AutomationId="PickerPopupOkButton"/>
</StackLayout>
</On>
<On Platform="UWP">
<StackLayout Orientation="Horizontal" Spacing="0" HorizontalOptions="End">
<Button Text="{TemplateBinding AcceptButtonText}"
Style="{TemplateBinding AcceptButtonStyle}"
Command="{TemplateBinding AcceptCommand}"
AutomationId="PickerPopupOkButton"/>
<Button Text="{TemplateBinding CancelButtonText}"
Style="{TemplateBinding CancelButtonStyle}"
Command="{TemplateBinding CancelCommand}"
AutomationId="PickerPopupCancelButton"/>
</StackLayout>
</On>
</OnPlatform>
</telerikPrimitives:RadBorder>
</ControlTemplate>
 

and the TimeSpan Picker definition:

1677
Telerik UI for Xamarin

XAML
<telerikInput:RadTimeSpanPicker MinimumDate="2020,01,1"
MaximumDate="2025,12,31"
SpinnerFormat="MMM/dd/yyyy"
PlaceholderTemplate="{StaticResource Picker_PlaceholderView_ControlTemplate}"
DisplayTemplate="{StaticResource Picker_DisplayView_ControlTemplate}">
<telerikInput:RadDTimeSpanPicker.SelectorSettings>
<telerikInput:PickerPopupSelectorSettings HeaderTemplate="{StaticResource
PopupView_Header_ControlTemplate}"
HeaderLabelText="Date Picker"
FooterTemplate="{StaticResource PopupView_Footer_ControlTemplate}"/>
</telerikInput:RadTimeSpanPicker.SelectorSettings>
</telerikInput:RadDatePicker>
 

Example How to Customize the Default Look


The snippet below shows a simple TimeSpan Picker definition:

Now lets add the templates definition to the page resources:

Custom PlaceholderTemplate
XAML
<ControlTemplate x:Key="placeholderTemplate">
<Button Text="Pick a time interval"
FontAttributes="Bold"
TextColor="White"
BackgroundColor="#70B8FF"
HeightRequest="50"
Command="{TemplateBinding ToggleCommand}" />
</ControlTemplate>
 

Custom DisplayTemplate
XAML
<ControlTemplate x:Key="displayTemplate">
<Button Text="{TemplateBinding DisplayString}"
TextColor="White"
BackgroundColor="#70B8FF"
HeightRequest="50"
Command="{TemplateBinding ToggleCommand}" />

1678
Telerik UI for Xamarin

</ControlTemplate>
 

Custom HeaderTemplate
XAML
<ControlTemplate x:Key="headerTemplate">
<Label Text="Select Duration"
TextColor="White"
VerticalTextAlignment="Center"
HorizontalTextAlignment="Center"
BackgroundColor="#70B8FF"/>
</ControlTemplate>
 

Custom FooterTemplate
XAML
<ControlTemplate x:Key="footerTemplate">
<StackLayout Orientation="Horizontal" Spacing="0"
HorizontalOptions="FillAndExpand" BackgroundColor="#70B8FF">
<Button Text="&#xE80A;"
FontFamily="{StaticResource IconsFontFamily}"
TextColor="White"
BackgroundColor="Transparent"
Command="{TemplateBinding CancelCommand}" />
<Button Text="&#xE809;"
FontFamily="{StaticResource IconsFontFamily}"
TextColor="White"
BackgroundColor="Transparent"
Command="{TemplateBinding AcceptCommand}" />
</StackLayout>
</ControlTemplate>
 

Here is how the header and footer looks after customization:

1679
Telerik UI for Xamarin

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

A sample Custom Templates example can be found in the TimeSpan/Features folder of the SDK
Samples Browser application.
 

See Also
 Key Features
 Templates
 Commands

1680
Telerik UI for Xamarin

TimeSpan Picker Localization


RadTimeSpan Picker for Xamarin provides language localization. In short, you can translate the
used across the TimeSpan Picker texts to other languages, so that your app can be adapted to
different regions.

To learn in details about the localization process of Telerik UI for Xamarin components, please go
through the common Localization and Globalization topic.
 
The sections below list all the localization keys used in TimeSpan Picker for Xamarin control.

TimeSpan Picker Localization string


Localization Key Default Value
TimeSpanPicker_PlaceholderLabelText Select Duration
TimeSpanPicker_Popup_HeaderLabelText Select Duration

Common Picker Localizations strings


Localization Key Default Value
Picker_DaysSpinnerHeaderLabelText Days
Picker_HourSpinnerHeaderLabelText Hours
Picker_MinuteSpinnerHeaderLabelText Minutes
Picker_SecondSpinnerHeaderLabelText Seconds
Picker_Popup_AcceptButtonText OK
Picker_Popup_CancelButtonText Cancel
Check in the image below how the localization strings are presented in TimeSpan Picker:

1681
Telerik UI for Xamarin

See Also
 Localization and Globalization

1682
Telerik UI for Xamarin

Selection
RadTimeSpanPicker control enables the app users to quickly and easily select a time interval. This
topic will go through the provided by the DatePicker API related to time interval selection.

Important Properties
 Time(TimeSpan?): Defines the current selection of time interval. The default value is null.

Example
XAML
<telerikInput:RadTimeSpanPicker Time="5:10:30:00"/>
 

and add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

Methods
TimeSpan Picker for Xamarin allows you to clear the selected date through its ClearSelection
method

Example
XAML
<StackLayout>
<Button Text="Clear Selection" Clicked="OnClearSelectionClicked"/>
<telerikInput:RadTimeSpanPicker x:Name="timeSpanPicker"/>
</StackLayout>
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

Call ClearSelection inside the button click event - as a result Time property will be updated to null.

1683
Telerik UI for Xamarin

C#
private void OnClearSelectionClicked(object sender, EventArgs e)
{
this.timeSpanPicker.ClearSelection();
}
 

Events
TimeSpan Picker exposes a SelectionChanged event which is raised when the user pick the
selected date.

Example
XAML
<telerikInput:RadTimeSpanPicker
SelectionChanged="RadTimeSpanPicker_SelectionChanged"/>
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

and the SelectionChanged event, where the sender is the RadTimeSpanPicker control

C#
private void RadTimeSpanPicker_SelectionChanged(object sender, EventArgs e)
{
// implement your logic here
}
 

See Also
 Key Features
 Templates
 Commands

1684
Telerik UI for Xamarin

Commands
TimeSpanPicker Commands
TimeSpan Picker for Xamarin exposes the following commands you can use to programmatically
manipulate displaying the popup as well as clearing the selected time interval:

 ToggleCommand(ICommand): Allows you to show/hide the popup used for selecting a time
interval.
 ClearCommand(ICommand): Allows you to clear the displayed time interval.

Example for ToggleCommand and ClearCommand


XAML
<StackLayout>
<Button Text="Toggle Command" Command="{Binding Source={x:Reference
timeSpanPicker}, Path=ToggleCommand}"/>
<Button Text="Clear Command" Command="{Binding Source={x:Reference
timeSpanPicker}, Path=ClearCommand}"/>
<telerikInput:RadTimePicker x:Name="timeSpanPicker" />
</StackLayout>
 

also you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

PopupSelector Commands
Through the popup users can pick a time interval. The time interval value should be confirmed or
rejected through the OK and Cancel buttons placed on the popup.

TimeSpan Picker allows you to add a custom logic for the Accept and Cancel commands which are
executed when OK and Cancel buttons, respectively, are pressed.

 AcceptCommand(ICommand): Defines the command which confirms the current selection of


the picker and closes the popup. AcceptCommandParameter can be used to pass a
parameter to the command execute method.
 CancelCommand(ICommand): Defines the command which rejects the current selection of
the picker and closes the popup. CancelCommandParameter can be used to pass a
parameter to the command execute method.

The Accept and Cancel commands can be applied using the SelectorSettings property of

1685
Telerik UI for Xamarin

RadTimeSpanPicker. In addition, you can pass command parameters through the


AcceptCommandParameter and CancelCommandParameter properties of the TimeSpanPicker
SelectorSettings.

Here is a quick example on how they could be set:

Example for AcceptCommand and CancelCommand


XAML
<telerikInput:RadTimeSpanPicker x:Name="timeSpanPicker">
<telerikInput:RadTimeSpanPicker.SelectorSettings>
<telerikInput:PickerPopupSelectorSettings AcceptCommand="{Binding Accept}"
AcceptCommandParameter="{Binding Time, Source={x:Reference timeSpanPicker}}"
CancelCommand="{Binding Cancel}"
CancelCommandParameter="{Binding Time, Source={x:Reference timeSpanPicker}}"/>
</telerikInput:RadTimeSpanPicker.SelectorSettings>
<telerikInput:RadTimeSpanPicker.BindingContext>
<local:ViewModel/>
</telerikInput:RadTimeSpanPicker.BindingContext>
</telerikInput:RadTimeSpanPicker>
 

and the ViewModel

C#
public class ViewModel
{
public ICommand Accept { get; set; }
public ICommand Cancel { get; set; }

public ViewModel()
{
this.Accept = new Command(this.OnAccept);
this.Cancel = new Command(this.OnCancel);
}

private void OnAccept(object param)


{
Application.Current.MainPage.DisplayAlert("Time Interval selected", "New time
interval: " + (TimeSpan)param, "OK");
// implement your custom logic here
}

private void OnCancel(object param)


{
var message = param != null ? "Current time interval: " + (TimeSpan)param :
"Currently no time interval is selected";
Application.Current.MainPage.DisplayAlert("Time Interval Selection Canceled",
message, "OK");
// implement your custom logic here
}
}

1686
Telerik UI for Xamarin

also you need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

See Also
 Key Features
 Templates
 Selection

1687
Telerik UI for Xamarin

Styling
TimeSpanPicker Styling
TimeSpan Picker control for Xamаrin provides the following Style properties for customizing its look:

 SpinnerStyle(of type Style with target type telerikDataControls:RadSpinner): Defines the


style applied to the spinner item and selected item interval.
 SpinnerHeaderStyle(of type Style with target type Xamarin.Forms.Label): Specifies the style
applied to the spinner header labels.
 SelectionHighlightStyle(of type Style with target type telerikPrimitives:RadBorder): Specifies
the style applied to the selection inside the popup.
 PlaceholderLabelStyle(of type Style with target type Xamarin.Forms.Label): Defines the style
applied to the placeholder label.
 DisplayLabelStyle(of type Style with target type Xamarin.Forms.Label): Defines the style
applied to the label which is visualized when time duration is selected.

In addition, RadTimeSpanPicker exposes properties for specifying its border style and background
color, namely:

 BackgroundColor(Xamarin.Forms.Color): Defines the background color of the picker.


 BorderColor(Xamarin.Forms.Color): Defines the border color of the picker.
 BorderThickness(Xamarin.Forms.Thickness): Specifies the border thickness of the picker.
Default value is new Thickness(0,0,0,1).
 CornerRadius(Xamarin.Forms.Thinckness): Specifies the corner radius of the picker.

Popup Styling
Using the SelectorSettings property (of type
Telerik.XamarinForms.Input.PickerPopupSelectorSettings) of the TimeSpanPicker you can modify
the appearance of the dialog (popup). PickerPopupSelectorSettings class exposes the following
Style properties:

 PopupViewStyle(of type Style with target type telerikInput:PickerPopupContentView):


Defines the popup view style.
 HeaderStyle(of type Style with target type telerikInput:PickerPopupHeaderView): Defines the
popup header style.
 HeaderLabelStyle(of type Style with target type Xamarin.Forms.Label): Defines the popup
header label style.
 FooterStyle(of type Style with target type telerikInput:PickerPopupFooterView): Defines the
popup footer style.
 AcceptButtonStyle(of type Style with target type Xamarin.Forms.Button): Defines the Accept
button style.
 CancelButtonStyle(of type Style with target type Xamarin.Forms.Button): Defines the Cancel
button style.

The SelectorSettings also provides the following properties for popup customization:

1688
Telerik UI for Xamarin

 PopupOutsideBackgroundColor(Xamarin.Forms.Color): Defines the color outside of the


popup.
 IsPopupModal(bool): Defines a boolean value indicating if the popup should be closed when
tapped outside of the popup.
 When IsPopupModal="True" the UI behind the popup gets inactive and cannot be used
until the popup is closed.
 When IsPopupModal="False" the popup could be closed when clicking outside the
popup. By default the value of the IsPopupModal is false.
 HeaderLabelText(string): Specifies the text visualized in the popup header.
 IsHeaderVisible(bool): Specifies whether the Popup header is currently visible. By default the
valuse is True.
 IsFooterVisible(bool): Specifies whether the Popup footer is currently visible. By default the
valuse is True.
 AcceptButtonText(string): Defines the text visualized for the accept button. By default the text
is OK.
 CancelButtonText(string): Defines the text visualized for the cancel button. By default the text
is Cancel.

Namespaces
When defining some of these Styles you would need to include additional namespaces, so that the
target types are properly resolved.

Using PopupViewStyle, HeaderStyle or FooterStyle you will need to add the following namespace:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
 

Using SelectionHighlightStyle, TabStripStyle you need to add the following namespace:

XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
 

Using SpinnerStyle you need to add the following namespace:

XAML
xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te
lerik.XamarinForms.DataControls"
 

Example
Here is a sample example that shows how the styling properties are applied.

Let's have the following TimeSpan Picker definition:

1689
Telerik UI for Xamarin

XAML
<telerikInput:RadTimeSpanPicker SpinnerHeaderStyle="{StaticResource
spinnerHeaderStyle}"
SpinnerStyle="{StaticResource spinnerStyle}"
SelectionHighlightStyle="{StaticResource selectionHighlightStyle}"
DisplayLabelStyle="{StaticResource displayLabelStyle}"
PlaceholderLabelStyle="{StaticResource placeholderLabelStyle}">
<telerikInput:RadTimeSpanPicker.SelectorSettings>
<telerikInput:PickerPopupSelectorSettings
PopupOutsideBackgroundColor="#D9D9D9CC"
PopupViewStyle="{StaticResource popupViewStyle}"
HeaderStyle="{StaticResource headerStyle}"
HeaderLabelText="Select Duration"
HeaderLabelStyle="{StaticResource headerLabelStyle}"
FooterStyle="{StaticResource footerStyle}"
AcceptButtonStyle="{StaticResource acceptButtonStyle}"
CancelButtonStyle="{StaticResource cancelButtonStyle}"/>
</telerikInput:RadTimeSpanPicker.SelectorSettings>
</telerikInput:RadTimeSpanPicker>
 

And here are how the styles are defined in the page resources.

Spinner Style

XAML
<Style TargetType="telerikDataControls:RadSpinner" x:Key="spinnerStyle">
<Setter Property="ItemStyle">
<Setter.Value>
<Style TargetType="telerikDataControls:SpinnerItemView">
<Setter Property="TextColor" Value="#797979" />
<Setter Property="BackgroundColor" Value="#F2F2F2" />
<Setter Property="CornerRadius" Value="10" />
<Setter Property="Margin" Value="6, 4" />
</Style>
</Setter.Value>
</Setter>
<Setter Property="SelectedItemStyle">
<Setter.Value>
<Style TargetType="telerikDataControls:SpinnerItemView">
<Setter Property="TextColor" Value="#00B5DC" />
<Setter Property="BackgroundColor" Value="#E4F3F9" />
<Setter Property="CornerRadius" Value="10" />
<Setter Property="Margin" Value="6, 4" />
</Style>
</Setter.Value>
</Setter>
</Style>
 

SpinnerHeader Style

1690
Telerik UI for Xamarin

XAML
<Style TargetType="Label" x:Key="spinnerHeaderStyle">
<Setter Property="TextColor" Value="Black"/>
<Setter Property="FontAttributes" Value="Bold"/>
<Setter Property="HorizontalOptions" Value="FillAndExpand"/>
<Setter Property="VerticalOptions" Value="FillAndExpand"/>
<Setter Property="HorizontalTextAlignment" Value="Center"/>
<Setter Property="VerticalTextAlignment" Value="Center"/>
</Style>
 

SelectionHighlight Style

XAML
<Style TargetType="telerikPrimitives:RadBorder" x:Key="selectionHighlightStyle">
<Setter Property="BorderColor" Value="#00B5DC"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Padding" Value="0,6,0,6"/>
<Setter Property="HeightRequest" Value="40"/>
<Setter Property="VerticalOptions" Value="Center"/>
<Setter Property="BackgroundColor" Value="#F9F9F9"/>
</Style>
 

PlaceholderLabel Style

XAML
<Style TargetType="Label" x:Key="placeholderLabelStyle">
<Setter Property="TextColor" Value="#1188FF"/>
<Setter Property="VerticalTextAlignment" Value="Center"/>
<Setter Property="HorizontalTextAlignment" Value="Center"/>
<Setter Property="HeightRequest" Value="50"/>
</Style>
 

DisplayLabel Style

XAML
<Style TargetType="Label" x:Key="displayLabelStyle">
<Setter Property="TextColor" Value="#1188FF"/>
<Setter Property="VerticalTextAlignment" Value="Center"/>
<Setter Property="HorizontalTextAlignment" Value="Center"/>
<Setter Property="HeightRequest" Value="50"/>
</Style>
 

PopupView Style

XAML
<Style TargetType="telerikInput:PickerPopupContentView" x:Key="popupViewStyle">

1691
Telerik UI for Xamarin

<Setter Property="BackgroundColor" Value="White"/>


<Setter Property="WidthRequest" Value="270"/>
</Style>
 

Header Style

XAML
<Style TargetType="telerikInput:PickerPopupHeaderView" x:Key="headerStyle">
<Setter Property="BackgroundColor" Value="#00B5DC"/>
<Setter Property="HeightRequest" Value="60"/>
<Setter Property="Margin" Value="0"/>
<Setter Property="Padding" Value="0"/>
<Setter Property="HorizontalOptions" Value="FillAndExpand"/>
<Setter Property="VerticalOptions" Value="FillAndExpand"/>
</Style>
 

HeaderLabel Style

XAML
<Style TargetType="Label" x:Key="headerLabelStyle">
<Setter Property="TextColor" Value="White"/>
<Setter Property="HorizontalOptions" Value="Center"/>
<Setter Property="VerticalOptions" Value="Center"/>
<Setter Property="FontSize" Value="Title"/>
</Style>
 

Footer Style

XAML
<Style TargetType="telerikInput:PickerPopupFooterView" x:Key="footerStyle">
<Setter Property="BackgroundColor" Value="#00B5DC"/>
</Style>
 

AcceptButton Style

XAML
<Style TargetType="Button" x:Key="acceptButtonStyle">
<Setter Property="BackgroundColor" Value="Transparent"/>
<Setter Property="Text" Value="Accept"/>
<Setter Property="TextColor" Value="White"/>
</Style>
 

CancelButton Style

XAML

1692
Telerik UI for Xamarin

<Style TargetType="Button" x:Key="cancelButtonStyle">


<Setter Property="BackgroundColor" Value="Transparent"/>
<Setter Property="Text" Value="Reject"/>
<Setter Property="TextColor" Value="White"/>
</Style>
 

Namespaces

In addition, add the following namespaces:

XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te
lerik.XamarinForms.DataControls"
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
 

This is how the TimeSpan Picker control looks when the styles described above are applied:

A sample Styling example can be found in the TimeSpanPicker/Features folder of the SDK Samples
Browser application.
 

See Also
 Key Features

1693
Telerik UI for Xamarin

 Custom Templates
 Commands
 Visual Structure

1694
Telerik UI for Xamarin

Overview
RadTreeView facilitates display, management, and navigation of hierarchical data structures. The
product offers many advanced features like commands mechanism, data binding, checkbox support.
RadTreeView allows you to achieve complex behavior and nicely blends into the interface of your
application.

Figure 1: Overview

Key features
 Hierarchical Navigation: RadTreeView significantly improves the navigation and performance
of your application where navigation over hierarchical structure is required.
 Expand/Collapse API: RadTreeView introduces several methods which can be used to
programmatically control the state of its items.
 Commands Support: RadTreeView strictly follows the MVVM best practices and provides an
intuitive and easy-to-use set of APIs that allow different aspects of the RadTreeView

1695
Telerik UI for Xamarin

control’s behavior to be handled and/or completely overridden. RadTreeView exposes a


Commands collection that allows you to register custom commands with each control’s instance.
 CheckBox Support: Telerik RadTreeView provides check boxes buttons displayed next to
each item. The RadTreeView allows the user to check/uncheck the nodes and to perform
various tasks with the collection of checked nodes. The Tri-State CheckBox mode of
RadTreeView allows for RadTreeViewItems' CheckBoxes to have an additional, third state -
Indeterminate.
 Data Binding: Simply setting the collection of custom business objects as an ItemsSource in
combination with a "HierarchyAdapter" class is enough to visualize the
hierarchically-structured source.
 Load on Demand: Load On Demand feature allows you to delay the population of
RadTreeView and load subitems only when they’re requested, thus improving the overall
performance of your app.
 UI Virtualization: The user interface uses virtualization for displaying the required elements,
meaning that they are created only when needed and only for the currently visible cells.
 Theming Support: RadTreeView comes with built-in theming support that allows you to easily
build slick interfaces with the look-and-feel of a predefined theme

See Also
 Getting Started

1696
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadTreeView control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadDataGrid control

1. Setting up the app


Take a look at these articles and follow the instructions to setup your app:

 Setup app with Telerik UI for Xamarin on Windows


 Setup app with Telerik UI for Xamarin on Mac

2. Adding the required Telerik references


You have two options:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadTreeView control you have to install the
Telerik.UI.for.Xamarin.DataControls nuget package. This nuget will automatically refer the
Telerik.UI.for.Xamarin.Primitives and Telerik.UI.for.Xamarin.Common nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadTreeView component:

Platform Assemblies
Portable/Standard Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.Primitives.dll
Android Telerik.Xamarin.Android.Common.dll
Telerik.Xamarin.Android.Data.dll
Telerik.Xamarin.Android.Input.dll
Telerik.Xamarin.Android.List.dll
Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataControls.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Primitives.dll

1697
Telerik UI for Xamarin

Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataControls.dll
UWP Telerik.Core.dll
Telerik.Data.dll
Telerik.UI.Xaml.Controls.Data.UWP.dll
Telerik.UI.Xaml.Input.UWP.dll
Telerik.UI.Xaml.Primitives.UWP.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.Primitives.dll

3. Adding RadTreeView control


You could use one of the following approaches:

Drag the control from the Toolbox.


Take a look at the following topics on how to use the toolbox:

 Telerik UI for Xamarin Toolbox on Windows


 Telerik UI for Xamarin Toolbox on Mac

Create the control definition in XAML:


XAML
<telerikDataControls:RadTreeView x:Name="treeView" ItemsSource="{Binding Source}" />
 

In addition to this, you need to add the following namespace:

XAML
xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te
lerik.XamarinForms.DataControls"
 

RadTreeView control provides UI virtualization, so it requires its visual parent to provide vertical or
horizontal space for the control to fill into. The following scenarios will measure the control with
infinity and the virtualization will not work:

 positioning the TreeView control inside StackLayout which is wrapped in ScrollView.


 positioning the TreeView inside ScrollView.

For additional information, please check the Controls are not Apppearing article.

 
As you can notice, the ItemsSource property of the control needs to be set. The collection we have is
representing a hierarchical view and this is the reason for using the RadTreeView control for this
setup.

1698
Telerik UI for Xamarin

First, let's use a simple Item business object which holds its sub items inside Children collection:

C#
public class Item
{
public Item(string name)
{
this.Name = name;
this.Children = new ObservableCollection<Item>();
}

public string Name { get; set; }


public IList<Item> Children { get; set; }
}
 

Then, create a ViewModel containing a collection of Items objects that will be used as ItemsSource
of the TreeView:

C#
public class ViewModel
{
public ViewModel()
{
Source = new ObservableCollection<Item>();
Source.Add(new Item("My Documents")
{
Children = new List<Item>()
{
new Item("Xamarin Projects")
{
Children = new ObservableCollection<Item>()
{
new Item("TreeView Examples"),
new Item("Calendar & Scheduling QSF")
}
},
new Item("Documentation Drafts")
}
});
Source.Add(new Item("Shared Documents")
{
Children = new List<Item>()
{
new Item("Reports")
{
Children = new List<Item>()
{
new Item("October"),
new Item("November"),
new Item("December")
}

1699
Telerik UI for Xamarin

}
}
});
}
public ObservableCollection<Item> Source { get; set; }
}
 

An important step for the control to load its items correctly is to apply TreeViewDescriptor(s). The
TreeViewDescriptor basically defines the data items' hierarchy as well as how each item is
visualized through the properties listed below:

 TargetType - the type of the data item the descriptor refers to;
 DisplayMemberPath - the name of the property that is displayed for this data item;
 ItemsSourcePath - the path to the list containing the sub items;
 ItemTemplate - you could customize the visual appearance of each item type through the
ItemTemplate property of the descriptor;

Here is an example how the TreeViewDescriptor is applied:

XAML
<telerikDataControls:RadTreeView x:Name="treeView" ItemsSource="{Binding Source}">
<telerikDataControls:TreeViewDescriptor DisplayMemberPath="Name"
ItemsSourcePath="Children"
TargetType="{x:Type local:Item}" />
</telerikDataControls:RadTreeView>
 

Lastly, set the ViewModel class as BindingContext:

C#
this.BindingContext = new ViewModel();
 

Here is the appearance of the RadTreeView control once the upper steps have been accomplished:

1700
Telerik UI for Xamarin

You can check a runnable demo in the Getting Started section of the RadTreeView component in
the SDK Samples Browser application(can be found in the Examples folder of your local Telerik UI
for Xamarin installation)
 

See Also
 Commands
 Expand/Collapse
 CheckBoxes
 Theming

1701
Telerik UI for Xamarin

Expand/Collapse Items
RadTreeView exposes several useful methods which can be utilized in order to control the states of
its items. You can use the following methods when trying to change the state of an individual item:

 void Expand(object item): Expands a specific item from the source collection
 void Collapse(object item): Collapses a specific item from the source collection

The following code snippets show how to expand/collapse a specific item from the code-behind of
the page where the control is defined:

C#
private void ExpandItem2(object sender, EventArgs e)
{
var item2 = (treeView.ItemsSource as IList<Item>)[1];
treeView.Expand(item2);
}
private void CollapseItem2(object sender, EventArgs e)
{
var item2 = (treeView.ItemsSource as IList<Item>)[1];
treeView.Collapse(item2);
}
 

Where Item is the business object used in the TreeView ItemsSource collection.

If you would like to collapse/expand all items within the source collection, you can utilize the
following methods:

 void ExpandAll(): Expands all items from the source collection


 void CollapseAll(): Collapses all items from the source collection

C#
private void ExpandAll(object sender, EventArgs e)
{
treeView.ExpandAll();
}
private void CollapseAll(object sender, EventArgs e)
{
treeView.CollapseAll();
}
 

You can check a runnable demo in the Features section of the RadTreeView component in the SDK
Samples Browser application(can be found in the Examples folder of your local Telerik UI for
Xamarin installation)
 

See Also
1702
Telerik UI for Xamarin

 Commands
 CheckBoxes
 Theming

1703
Telerik UI for Xamarin

CheckBox elements
RadTreeView supports showing CheckBox elements and checking specific items from its
ItemsSource. The checked items are added to the CheckedItems property of the control. You can
also control the Visibility of the CheckBox elements as well as their state propagation.

CheckBox State Propagation


You can control the state propagation by setting the CheckBoxMode property of the RadTreeView.
The CheckBoxModes enum consists of the following values:

 None: The CheckBox would not be present.


 Individual: The CheckBox state will affect only the individual item.
 Propagate: The CheckBox state of the children items will affect the parent item. In case all
items within a parent nodes are checked - it will be with checked state as well. If all items are
not checked, the parent item will not be checked. If only some of the children items are
checked, the parent item will be shown with an indeterminate state.

When adding items to the items source of the TreeView, the checked state will propagate according
to the parent item.
 
Here is an example of how you can set the property:

XAML
<telerikDataControls:RadTreeView x:Name="treeView"
ItemsSource="{Binding Source}"
CheckBoxMode="Propagate">
<telerikDataControls:TreeViewDescriptor DisplayMemberPath="Name"
ItemsSourcePath="Children"
TargetType="{x:Type local:Item}" />
</telerikDataControls:RadTreeView>
 

Here is a picture that show the different states of the CheckBox:

1704
Telerik UI for Xamarin

Programmatic Check and Uncheck


The RadTreeView exposes two methods to programmatically check or uncheck an item.

 CheckItem(object item): Adds an item to CheckedItems collection


 UncheckItem(object item): Removes an item from the CheckedItems collection

C#
private void CheckFirstItem()
{
var firstItem = (treeView.ItemsSource as IList<Item>)[0];
treeView.CheckItem(firstItem);
}

private void UncheckFirstItem()


{
var firstItem = (treeView.ItemsSource as IList<Item>)[0];
treeView.UncheckItem(firstItem);
}
 

CheckedItems collection
The control exposes a collection of all the checked items. CheckedItems is a read-only collection of
type Telerik.XamarinForms.DataControls.TreeView.CheckedItemsCollection, so you can
add/remove items to it only through the TreeView CheckItem and UncheckItem methods. To keep
track of the checked items subscribe to its CollectionChanged event:

1705
Telerik UI for Xamarin

C#
treeView.CheckedItems.CollectionChanged += CheckedItems_CollectionChanged;
 

And here is the CollectionChanged event handler:

C#
private void CheckedItems_CollectionChanged(object sender,
System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
var ci = this.treeView.CheckedItems as CheckedItemsCollection;
this.CheckedItemsCount.Text = ci.Count.ToString();
}
 

CheckBoxes Visibility
The CheckBox visibility can be controlled through the CheckBoxMode property. Setting it to "None"
would remove the appearance of these elements. Here is the appearance of the control when the
CheckBoxMode is set to None:

You can check a runnable demo in the Features section of the RadTreeView component in the SDK
Samples Browser application(can be found in the Examples folder of your local Telerik UI for
Xamarin installation)
 

See Also

1706
Telerik UI for Xamarin

 Commands
 Expand/Collapse
 Theming

1707
Telerik UI for Xamarin

Custom Item Template


RadTreeView can be populated with various types of objects (string, any business objects, etc.). You
can customize the visualization of the views in the ItemsSource of the control using the
ItemTemplate property of the TreeViewDescriptors. The template could contain any view that you
can use to display the data.

You can take the default TreeView ItemTemplate and use it as base for further customizations.
 
The following example shows how to populate the ItemsSource with business items and customize
their appearance.

First, create the needed business objects that will be the items of the TreeView. For the example
there will be Country type with subitems of City type:

 Country definition:

C#
public class Country
{
public string Name { get; set; }
public string Icon { get; set; }
public ObservableCollection<City> Cities { get; set; }
}
 

 City definition:

C#
public class City
{
public string Name { get; set; }
}
 

Then, create a ViewModel where the items are defined:

C#
public class ViewModel
{
public ObservableCollection<Country> Source { get; set; }

public ViewModel()
{
this.Source = new ObservableCollection<Country>();
this.Source.Add(new Country()
{
Name = "Italy",

1708
Telerik UI for Xamarin

Icon = "TreeView_Flag_Italy.png",
Cities = new ObservableCollection<City>()
{
new City() { Name = "Rome"},
new City() { Name = "Milano"}
}
});
this.Source.Add(new Country()
{
Name = "Germany",
Icon = "TreeView_Flag_Germany.png",
Cities = new ObservableCollection<City>()
{
new City() { Name = "Berlin"},
new City() { Name = "Frankfurt"}
}
});
this.Source.Add(new Country()
{
Name = "India",
Icon = "TreeView_Flag_India.png",
Cities = new ObservableCollection<City>()
{
new City() { Name = "Mumbai"}
}
});
this.Source.Add(new Country()
{
Name = "Argentina",
Icon = "TreeView_Flag_Argentina.png",
Cities = new ObservableCollection<City>()
{
new City() { Name = "Buenos Aires"}
}
});
this.Source.Add(new Country()
{
Name = "USA",
Icon = "TreeView_Flag_USA.png",
Cities = new ObservableCollection<City>()
{
new City() { Name = "Miami"},
new City() { Name = "New York"},
new City() { Name = "Los Angeles"}
}
});
}
}
 

Add the TreeView definition to your page. Since there are two types of items (Country and City), two
TreeViewDescriptors should be added. For the Country item there is a separate ItemTemplate
defined, so that the Country.Icon is visualized as well:

1709
Telerik UI for Xamarin

XAML
<telerikDataControls:RadTreeView x:Name="treeView"
ItemsSource="{Binding Source}">
<telerikDataControls:TreeViewDescriptor DisplayMemberPath="Name"
ItemsSourcePath="Cities"
TargetType="{x:Type local:Country}">
<telerikDataControls:TreeViewDescriptor.ItemTemplate>
<DataTemplate>
<Grid Margin="{Binding Path=Level, Converter={StaticResource
levelToMarginConverter}}"
HeightRequest="40">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<telerikTreeView:ExpandCollapseIndicator FontSize="Medium"
WidthRequest="10"
Margin="15,0"
VerticalTextAlignment="Center"
IsLoading="{Binding Path=IsLoading}"
IsLoadOnDemandEnabled="{Binding Path=IsLoadOnDemandEnabled}"
IsExpanded="{Binding Path=IsExpanded}"
IsLeaf="{Binding Path=IsLeaf}" />
<Image Grid.Column="1"
VerticalOptions="Center"
Source="{Binding Item.Icon, Converter={StaticResource ImageSourceConverter}}"
/>
<telerikTreeView:ItemText Grid.Column="2"
Margin="8,0,0,0"
VerticalOptions="Center"
Text="{Binding Item.Name}" />
</Grid>
</DataTemplate>
</telerikDataControls:TreeViewDescriptor.ItemTemplate>
</telerikDataControls:TreeViewDescriptor>
<telerikDataControls:TreeViewDescriptor DisplayMemberPath="Name"
TargetType="{x:Type local:City}" />
</telerikDataControls:RadTreeView>
 

Here is the ImageSourceConverter class which basically maps the icon's path according to the
target platform:

C#
public class ImageSourceConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo
culture)
{
if (value == null)
{
return string.Empty;

1710
Telerik UI for Xamarin

if (Device.RuntimePlatform == Device.UWP)
{
return "Assets/" + value;
}

if (Device.RuntimePlatform == Device.iOS)
{
return ((string)value).Replace(".png", string.Empty);
}

return value;
}
public object ConvertBack(object value, Type targetType, object parameter,
CultureInfo culture)
{
throw new NotImplementedException();
}
}
 

In the ItemTemplate there is a reference to the levelToMarginConverter StaticResource - this is an


inner TreeView converter used to calculate the item's offset according to its Level.

Both converters should be defined as Resources like this:

XAML
<ResourceDictionary>
<local:ImageSourceConverter x:Key="ImageSourceConverter" />
<telerikTreeView:LevelToMarginConverter x:Key="levelToMarginConverter" />
</ResourceDictionary>
 

Where the telerikTreeView namespace is the following:

XAML
xmlns:telerikTreeView="clr-namespace:Telerik.XamarinForms.DataControls.TreeView;assemb
ly=Telerik.XamarinForms.DataControls"
 

All that is left, is to set the BindingContext to the ViewModel:

C#
this.BindingContext = new ViewModel();
 

Here is how the TreeView looks with custom ItemTemplate:

1711
Telerik UI for Xamarin

You can check a runnable demo in the Features section of the RadTreeView component in the SDK
Samples Browser application(can be found in the Examples folder of your local Telerik UI for
Xamarin installation)
 

See Also
 Default ItemTemplate
 Expand/Collapse
 Commands

1712
Telerik UI for Xamarin

Default ItemTemplate
When using the ItemTemplate property of the TreeViewDescriptor it overrides the default template.
For example, if you are using the default template with CheckBoxes, when overriding it, the
CheckBoxes will be no longer shown. In order to properly visualize them you will need the original
ItemTemplate.

This topic gives an overview of the default ItemTemplate of the TreeViewDescriptor, so you can copy
it to your app and make changes.

The original ItemTemplate

The XAML defined below relies on the following namespace to be set:

XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te
lerik.XamarinForms.DataControls"
xmlns:telerikTreeView="clr-namespace:Telerik.XamarinForms.DataControls.TreeView;assemb
ly=Telerik.XamarinForms.DataControls"
 

XAML
<ResourceDictionary>
<telerikTreeView:LevelToMarginConverter x:Key="levelToMarginConverter" />

<DataTemplate x:Key="CustomControlTemplate">
<StackLayout Orientation="Horizontal"
Margin="{Binding Path=Level, Converter={StaticResource
levelToMarginConverter}}">
<StackLayout.HeightRequest>
<OnPlatform x:TypeArguments="x:Double">
<On Platform="iOS" Value="44"></On>
<On Platform="Android" Value="40"></On>
<On Platform="UWP" Value="40"></On>
</OnPlatform>
</StackLayout.HeightRequest>
<telerikTreeView:ExpandCollapseIndicator FontSize="Medium"
WidthRequest="10"
Margin="15,0"
VerticalTextAlignment="Center"
IsLoading="{Binding Path=IsLoading}"
IsLoadOnDemandEnabled="{Binding Path=IsLoadOnDemandEnabled}"
IsExpanded="{Binding Path=IsExpanded}"
IsLeaf="{Binding Path=IsLeaf}">
<AutomationProperties.HelpText>
<OnPlatform x:TypeArguments="x:String">
<On Platform="iOS" Value="RadTreeView"></On>
</OnPlatform>

1713
Telerik UI for Xamarin

</AutomationProperties.HelpText>
</telerikTreeView:ExpandCollapseIndicator>
<telerikPrimitives:RadCheckBox IsChecked="{Binding Path=IsChecked,
Mode=TwoWay}"
IsVisible="{Binding Path=IsCheckBoxVisible}"
VerticalOptions="Center">
<AutomationProperties.HelpText>
<OnPlatform x:TypeArguments="x:String">
<On Platform="iOS" Value="RadTreeView"></On>
</OnPlatform>
</AutomationProperties.HelpText>
</telerikPrimitives:RadCheckBox>
<telerikTreeView:ItemText Text="{Binding Path=Header}"
VerticalTextAlignment="Center">
<AutomationProperties.HelpText>
<OnPlatform x:TypeArguments="x:String">
<On Platform="iOS" Value="RadTreeView"></On>
</OnPlatform>
</AutomationProperties.HelpText>
</telerikTreeView:ItemText>
</StackLayout>
</DataTemplate>
</ResourceDictionary>
 

Finally, use the custom Item ControlTemplate as a StaticResource on any instance of


TreeViewDescriptor ItemTemplate:

XAML
<telerikDataControls:RadTreeView x:Name="treeView">
<telerikDataControls:TreeViewDescriptor ItemTemplate="{StaticResource
CustomControlTemplate}"/>
</telerikDataControls:RadTreeView>
 

See Also
 Commands
 CheckBoxes
 Theming

1714
Telerik UI for Xamarin

Load on Demand
Load On Demand feature allows you to delay the population of RadTreeView and load subitems only
when they’re requested, thus saving computing resources and improving the initial performance of
your app.

The Load on Demand mechanism is implemented in such a way that as soon as the end-user tries
to expand an item, the treeview receives a notification that a load on demand operation is requested
and a busy indicator is displayed for the respective item. When the requested items are loaded, and
the operation is marked as finished, the busy indicator is hidden and the items are visualized in the
TreeView.

In order to enable the load on demand feature, you would need to utilize the LoadOnDemand
command of RadTreeView as demonstrated in the example below:

First, let's create a sample Category class which represents the root items of the TreeView and
holds its subitems inside its Children property:

C#
public class Category : NotifyPropertyChangedBase
{
public string Name { get; set; }

ObservableCollection<string> children;
public ObservableCollection<string> Children
{
get
{
return this.children;
}
set
{
if (this.children != value)
{
this.children = value;
this.OnPropertyChanged();
}
}
}
}
 

Then, create a ViewModel with a sample Source property which contains the root items of the
TreeView. You would also need to create a Command for handling the load on demand scenario.

C#
public class ViewModel : NotifyPropertyChangedBase
{
public ObservableCollection<Category> Source { get; set; }

1715
Telerik UI for Xamarin

public ICommand LoadOnDemandCommand


{
get; set;
}
public ViewModel()
{
this.Source = new ObservableCollection<Category>()
{
new Category { Name = "Products"},
new Category { Name = "Purchase"},
new Category { Name = "Support"},
new Category { Name = "Community"}
};

this.LoadOnDemandCommand = new Command(async (p) => await


this.LoadOnDemandExecute(p), (p) => this.IsLoadOnDemandEnabled(p));
}
private bool IsLoadOnDemandEnabled(object p)
{
var context = (TreeViewLoadOnDemandCommandContext)p;
return context.Item is Category;
}
async private Task LoadOnDemandExecute(object p)
{
var context = (TreeViewLoadOnDemandCommandContext)p;
var category = context.Item as Category;
if (category != null)
{
ObservableCollection<string> children = await Task.Run(() =>
this.LoadChildren(category));
category.Children = children;
context.Finish();
}
}
private ObservableCollection<string> LoadChildren(Category category)
{
Task.Delay(1000).Wait();

Dictionary<string, ObservableCollection<string>> allItems = new


Dictionary<string, ObservableCollection<string>>();
allItems.Add("Products", new ObservableCollection<string>() { "Telerik UI for
Xamarin", "Telerik UI for WPF", "Telerik Reporting" });
allItems.Add("Purchase", new ObservableCollection<string>() { "Buy now",
"License Agreement", "Policies" });
allItems.Add("Support", new ObservableCollection<string>() { "Support Center",
"Knowledge Base", "Demos", "Tutorials" });
allItems.Add("Community", new ObservableCollection<string>() { "Learning
Resources", "Blogs", "Forums" });

var result = new ObservableCollection<string>();


bool hasChildren = allItems.TryGetValue(category.Name, out result);

return result;
}

1716
Telerik UI for Xamarin

IsLoadOnDemandEnabled method is called when each item is initialized and defines whether a
load-on-demand feature is enabled for this item.
 
Finally, define RadTreeView with the needed TreeViewDescriptors as well as the
LoadOnDemandCommand applied:

XAML
<telerikDataControls:RadTreeView x:Name="treeView" ItemsSource="{Binding Source}" >
<telerikDataControls:RadTreeView.Commands>
<telerikTreeView:TreeViewUserCommand Id="LoadOnDemand" Command="{Binding
LoadOnDemandCommand}" />
</telerikDataControls:RadTreeView.Commands>
<telerikDataControls:TreeViewDescriptor DisplayMemberPath="Name"
ItemsSourcePath="Children"
TargetType="{x:Type local:Category}"/>
<telerikDataControls:TreeViewDescriptor TargetType="{x:Type x:String}" />
</telerikDataControls:RadTreeView>
 

All that is left, is to set the BindingContext to the ViewModel:

C#
this.BindingContext = new ViewModel();
 

Where the telerikTreeView namespace is the following:

XAML
xmlns:telerikTreeView="clr-namespace:Telerik.XamarinForms.DataControls.TreeView;assemb
ly=Telerik.XamarinForms.DataControls"
 

Here is how the TreeView looks when load-on-demand is requested:

1717
Telerik UI for Xamarin

The sample here demonstrates only one-level hieararchy, however, in a real scenario you could use
multi-level hieararchy with lazy loading without a problem.
 
You can check a runnable demo in the Features section of the RadTreeView component in the SDK
Samples Browser application(can be found in the Examples folder of your local Telerik UI for
Xamarin installation)
 

See Also
 Expand/Collapse
 Commands

1718
Telerik UI for Xamarin

Programmatic Scrolling
RadTreeView exposes the following method for programmatic scrolling to a specific data item:

 bool ScrollItemIntoView(object item): Attempts to bring the specified data item into the view.
Returns false in case the item is not available (cannot be found in the ItemsSource or any of
its parents is not expanded).

Example
Here is a sample definition of the TreeView control:

XAML
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<StackLayout>
<Button Clicked="ScrollItemIntoViewClicked" Text="ScrollItemIntoView"/>
<Label x:Name="label"/>
</StackLayout>
<telerikDataControls:RadTreeView x:Name="treeView" Grid.Row="1"
ItemsSource="{Binding Source}">
<telerikDataControls:TreeViewDescriptor DisplayMemberPath="Name"
ItemsSourcePath="Children"
TargetType="{x:Type local:Item}"/>
</telerikDataControls:RadTreeView>
</Grid>
 

Inside ScrollItemIntoViewClicked event handler get the concrete item you'd need to navigate to and
call ScrollItemIntoView method of the TreeView:

C#
private void ScrollItemIntoViewClicked(object sender, EventArgs e)
{
var item = GetItemToScroll();
if (this.treeView.ScrollItemIntoView(item))
{
this.label.Text = "Scrolled to: " + item;
}
else
{
this.label.Text = item + " is either collapsed or does not exist";
}
}
private Item GetItemToScroll()

1719
Telerik UI for Xamarin

{
return ((treeView.ItemsSource as ObservableCollection<Item>).LastOrDefault() as
Item).Children.LastOrDefault();
}
 

And the end result:

Figure 1: Scrolling item into View

You can check a runnable demo in the Features section of the RadTreeView component in the SDK
Samples Browser application(can be found in the Examples folder of your local Telerik UI for
Xamarin installation)
 

See Also
 Expand/Collapse
 Commands

1720
Telerik UI for Xamarin

Events
RadTreeView exposes the following events:

 ItemTapped - occurs when an item is tapped. The ItemTapped event handler receives two
parameters:
 The sender argument which is of type object, but can be cast to the RadTreeView type.
 A TreeViewItemEventArgs object which has a reference to the tapped item through its
Item property.
 ItemHold - occurs when the item is held on. The ItemHold event handler receives two
parameters:
 The sender argument which is of type object, but can be cast to the RadTreeView type.
 A TreeViewItemEventArgs object which has a reference to the held item through its
Item property.
 ItemCollapsed - occurs when the item is collapsed. The ItemHold event handler receives
two parameters:
 The sender argument which is of type object, but can be cast to the RadTreeView type.
 A TreeViewItemEventArgs object which has a reference to the collapsed item through
its Item property.
 ItemExpanded - occurs when the item is expanded. The ItemHold event handler receives
two parameters:
 The sender argument which is of type object, but can be cast to the RadTreeView type.
 A TreeViewItemEventArgs object which has a reference to the expanded item through
its Item property.

See Also
 Expand/Collapse
 CheckBoxes
 Theming

1721
Telerik UI for Xamarin

Commands
The Command design-pattern is very important and widely used in the XAML and MVVM world.
RadTreeView follows these best practices and provides an intuitive and easy-to-use set of APIs that
allow different aspects of the RadTreeView control’s behavior to be handled and/or completely
overridden.

RadTreeView exposes a Commands collection that allows you to register custom commands with
each control’s instance through the RadTreeView.Commands property:

 Commands: Gets the collection with all the custom commands registered with the
CommandService.

Command Types
There are two types of commands:

 TreeViewCommand: All the default commands within RadTreeView derive from the base
TreeViewCommand. Think of this command as a UI-related command as it operates over the
RadTreeView instance that owns the command.
 TreeViewUserCommand: This type of command should be used when you would like to
modify the behavior of the control on any of the available actions. It exposes the following
properties:
 Id: The key that relates a command instance to a particular action/routine.
 Command: Gets or sets the generic ICommand implementation that may come from the
ViewModel.
 SuppressDefaultCommand: Gets or sets a value indicating whether the default(built-in)
UI command associated with the specified Id will be executed.

TreeViewCommandId Enumeration
All the predefined commands within a RadTreeView instance are identified by a member of the
TreeViewCommandId enumeration. This is actually the key that relates a command instance to a
particular action/routine within the owning element. In order to register a custom command within a
RadTreeView instance you should instantiate a TreeViewUserCommand instance and set its ID and
Command properties. Following are the members of the TreeViewCommandId enumeration:

 ItemTap
 ItemHold
 ItemCollapse
 ItemExpand
 LoadOnDemand
 Unknown

Custom TreeViewUserCommand Example

1722
Telerik UI for Xamarin

As a first step, you can create a command property which will invoke custom method on ItemTap.
Here is how this is done inside the ViewModel of the TreeView:

C#
public class ViewModel
{
public ObservableCollection<Item> Source { get; set; }
public ICommand MyTapCommand { get; set; }

public ViewModel()
{
this.MyTapCommand = new Command((p) => OnItemTap(p));

this.Source = new ObservableCollection<Item>();


this.Source.Add(new Item("Contacts")
{
Children = new List<Item>()
{
new Item("Bob Tony"),
new Item("Sue Winchell"),
new Item("Lui Sang")
}
});
this.Source.Add(new Item("Lists")
{
Children = new List<Item>()
{
new Item("Priorities"),
new Item("Opportunities"),
new Item("Issues")
}
});
this.Source.Add(new Item("Reports")
{
Children = new List<Item>()
{
new Item("December Sales"),
new Item("First Quarter Summary"),
new Item("Second Quarter Summary")
}
});
}
private void OnItemTap(object p)
{
var context = (TreeViewItemCommandContext)p;
//add your logic here
Application.Current.MainPage.DisplayAlert("", "You clicked on: " +
(context.Item as Item).Name, "OK");
}
}
 

Once you have created the custom command, you need to add it to the Commands collection of the

1723
Telerik UI for Xamarin

RadTreeView element:

XAML
<telerikDataControls:RadTreeView x:Name="treeView"
ItemsSource="{Binding Source}">
<telerikDataControls:RadTreeView.Commands>
<telerikTreeView:TreeViewUserCommand Id="ItemTap"
SuppressDefaultCommand="False"
Command="{Binding MyTapCommand}"/>
</telerikDataControls:RadTreeView.Commands>
<telerikDataControls:TreeViewDescriptor DisplayMemberPath="Name"
ItemsSourcePath="Children"
TargetType="{x:Type local:Item}"/>
</telerikDataControls:RadTreeView>
 

Where the telerikTreeView namespace is the following:

XAML
xmlns:telerikTreeView="clr-namespace:Telerik.XamarinForms.DataControls.TreeView.Comman
ds;assembly=Telerik.XamarinForms.DataControls"
 

You can check a runnable demo in the Features section of the RadTreeView component in the SDK
Samples Browser application(can be found in the Examples folder of your local Telerik UI for
Xamarin installation)
 

See Also
 Expand/Collapse
 CheckBoxes
 Theming

1724
Telerik UI for Xamarin

Theming
By applying a Telerik Theme to your Telerik controls you can easily propagate a common look and
feel throughout your application. The RadTreeView makes no exception and supports the theming
mechanism which is really straightforward to set.

As a first step, make sure that you have familiarized yourself with the Themes Overview topic. As a
next step, you can proceed with merging the required ResourceDictionaries into your application's
resources as explained in the Setting a Theme article.

Once you have completed the above steps, all you need to do is set the StyleClass property of the
RadTreeView so that the TelerikTheme is applied:

XAML
<telerikDataControls:RadTreeView x:Name="treeView"
ItemsSource="{Binding Source}"
StyleClass="TelerikTheme">
<telerikDataControls:TreeViewDescriptor DisplayMemberPath="Name"
ItemsSourcePath="Children"
TargetType="{x:Type local:Item}"/>
</telerikDataControls:RadTreeView>
 

You could check how RadTreeView looks below:

You can always modify the default theme resources in order to style the control so that it perfectly

1725
Telerik UI for Xamarin

fits the tone of your application. For more information, check the Create a Custom Theme topic.

See Also
 Commands
 Expand/Collapse
 CheckBoxes

1726
Telerik UI for Xamarin

Item Style
RadTreeView component provides styling mechanism for customizing the look of its items. To utilize
it you would need to set ItemStyle property of the control to TreeViewItemStyle object.

TreeViewItemStyle exposes the following styling options:

 BackgroundColor (Color): sets the background of the item(s).


 BorderColor (Color): sets the color of the border.
 BorderWidth (double): defines the width of the borer.
 BorderLocation (Location): describes an enumeration describing where the border should be
visible.

Location
This enumeration contains the following members:

 None - the border should not be visualized.


 Top - the border should be visualized only at the top side.
 Bottom - the border should be visualized only at the bottom side.
 Left - the border should be visualized only at the left side.
 Right - the border should be visualized only at the right side.
 All (default value) - the border should be visualized all around the item.

Example
The snippet below shows a sample RadTreeView definition with ItemStyle applied:

XAML
<telerikDataControls:RadTreeView x:Name="treeView"
ItemsSource="{Binding Source}">
<telerikDataControls:RadTreeView.Resources>
<ResourceDictionary>
<Style TargetType="telerikTreeView:ItemText">
<Setter Property="TextColor" Value="#0A3A82"/>
</Style>
<Style TargetType="telerikTreeView:ExpandCollapseIndicator">
<Setter Property="TextColor" Value="#0A3A82"/>
</Style>
</ResourceDictionary>
</telerikDataControls:RadTreeView.Resources>
<telerikDataControls:RadTreeView.ItemStyle>
<telerikTreeView:TreeViewItemStyle BackgroundColor="#96CCFF"
BorderColor="#0A3A82"
BorderWidth="2"
BorderLocation="All" />
</telerikDataControls:RadTreeView.ItemStyle>
<telerikDataControls:TreeViewDescriptor DisplayMemberPath="Name"

1727
Telerik UI for Xamarin

ItemsSourcePath="Children"
TargetType="{x:Type local:Item}"/>
</telerikDataControls:RadTreeView>
 

And here is the end result:

You can find a working demo labeled ItemStyle in the TreeView/Styling folder of the SDK Samples
Browser application.
 

See Also
 Theming
 ItemStyleSelector

1728
Telerik UI for Xamarin

ItemStyle Selector
RadTreeView component exposes conditional styling feature. It allows users to apply a different
Style to each item depending on a specific condition.

Example
The following example will demonstrate how to apply different styles on parent items and leaf items.

First, create a sample TreeViewStyleSelector class and override its OnSelectStyle method - in it you
will receive all the information on the current item through TreeViewStyleContext object, so you
could return different styling per your preferences:

C#
public class ExampleStyleSelector : TreeViewStyleSelector
{
protected override void OnSelectStyle(object item, TreeViewStyleContext
styleContext)
{
var dataItem = item as TreeViewDataItem;

if (dataItem != null)
{
var style = new TreeViewItemStyle();
if (dataItem.IsLeaf == true)
{
style.BackgroundColor = Color.FromHex("#96CCFF");
style.BorderColor = Color.FromHex("#0A3A82");
style.BorderLocation = Telerik.XamarinForms.Common.Location.All;
style.BorderWidth =5 ;
}
else
{
style.BackgroundColor = Color.FromHex("#356BFF");
style.BorderColor = Color.FromHex("#96CCFF");
style.BorderLocation = Telerik.XamarinForms.Common.Location.All;
style.BorderWidth = 5;
}
styleContext.ItemStyle = style;
}
}
}
 

All that is left is to set this custom style selector to the ItemStyleSelector property of the TreeView
control:

XAML
<telerikDataControls:RadTreeView ItemsSource="{Binding Source}">

1729
Telerik UI for Xamarin

<telerikDataControls:TreeViewDescriptor DisplayMemberPath="Name"
ItemsSourcePath="Children"
TargetType="{x:Type local:Item}"/>
<telerikDataControls:RadTreeView.ItemStyleSelector>
<styles:ExampleStyleSelector/>
</telerikDataControls:RadTreeView.ItemStyleSelector>
</telerikDataControls:RadTreeView>
 

This is how the RadTreeView control will look like when conditional styling is used.

SDK Browser application contains an example that shows StyleSelector feature in RadTreeView
cotrol. You can find the application in the Examples folder of your local Telerik UI for Xamarin
installation.
 

See Also
 Theming
 Item Style

1730
Telerik UI for Xamarin

Overview
RadWordsProcessing is part of the Telerik Document Processing libraries. The full documentation
for this component is available at
https://docs.telerik.com/devtools/document-processing/libraries/radwordsprocessing.
 
RadWordsProcessing is a processing library that allows to create, modify and export documents to a
variety of formats. Through the API, you can access each element in the document and modify,
remove it or add a new one. The generated content you can save as a stream, as a file, or send it to
the client browser.

Model
The model of RadWordsProcessing includes:

 Sections: You can customize the sections using the properties exposed by the corresponding

1731
Telerik UI for Xamarin

class. The library provides support for customizing the headers, footers, and watermarks for a
section as well.
 Paragraphs: The properties and methods related to paragraphs enable you to change its
collection of inlines and appearance.
 Tables: An API for inserting, editing and removing tables. You can also change their rows,
cells, appearance, and content.
 Inlines:
 Runs
 Images: Including inline and floating images.
 Fields: Merge fields, Document Variables and custom code fields, enabling you to insert
any fields using its code representation.
 Breaks: Support for different types of breaks, so you can achieve the desired layout.
 Bookmarks: Inserting, modifying and removing bookmarks.
 Hyperlinks: You can work with hyperlinks pointing to a website or to a bookmark inside
the document.
 Tab stops: Working with a tab stops collection for each paragraph.
 Styles
 The document model includes a repository of Style objects which contain sets of
character, paragraph or table style properties.
 The API allows you create custom styles and use them throughout the document.
 List styles.
 Content Controls: Content controls or Structured Document Tags (SDT) enable users to add
specific semantics to part of the document: restricting input, modifying editing behavior etc.
This functionality allows adding of checkboxes, combo boxes and other controls to the
document as well.

Features
 Mail Merge: Provides ability to produce personalized documents from a template holding
fixed content merged with variable data from a data source (database or any other collection
of data items).
 Merge documents: Insert a document into another one at the desired position, controlling the
way the styles of both are merged.
 Import of document elements: Import a document element from one document into another.
 Clone documents and document elements.
 Replace: RadWordsProcessing gives you the ability to search for a string in a
RadFlowDocument instance and replace all matches. The library also allows you to replace
the styling of the matches alone.
 RadFlowDocumentEditor: It is intended to simplify the process of creating and modifying a
document and achieve the same results as you would using the style properties and child
collections of the document elements with less amount of code.
 Formatting

In addition to the styles, RadWordsProcessing provides support for different types of


formatting so you can format any of the document elements:

 Character formatting: Font size, font color, font name, bold, italic, underline, etc.
 Paragraph formatting: Line spacing, alignment, indentation, spacing before and after, etc.
 Table formatting: Enables you to change the alignment, borders, shading, spacing and
padding, and more.

1732
Telerik UI for Xamarin

 Modifying the section properties to adjust the page size, orientation, margins, headers,
and footers, etc.

Supported formats
The library comes with support for the following document formats:

 DOC & DOT (import only)


 DOCX
 RTF
 HTML
 PDF (export only)
 Plain text

You can import and export documents of these formats as well as convert the format of the
document.

Required references
You have two options to add the required Telerik references to your Xamarin.Forms app in order to
use RadWordsProcessing:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadWordsProcessing you have to install the Telerik.Zip,
Telerik.Documents.Core, Telerik.Documents.Flow nuget packages. If you need to export documents
to PDF format, you will need to refer the Telerik.Documents.Flow.FormatProviders.Pdf and
Telerik.Documents.Fixed nuget packages.

 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadWordsProcessing:
 Telerik.Documents.Core.dll
 Telerik.Documents.Flow.dll
 Telerik.Zip.dll

If you need to import DOC or DOT files, you will need to refer the following assembly:

 Telerik.Documents.Flow.FormatProviders.Doc.dll

If you need to export documents to PDF format, you will need to refer the following
assemblies:

 Telerik.Documents.Flow.FormatProviders.Pdf.dll
 Telerik.Documents.Fixed.dll

Please keep in mind these assemblies are located in the Portable folder, still, you need to
add a reference to them in the Xamarin.Forms project as well as in each of the platform

1733
Telerik UI for Xamarin

projects (Android | iOS | UWP).


 

1734
Telerik UI for Xamarin

Overview
RadZipLibrary is part of the Telerik Document Processing libraries. The full documentation for this
component is available at https://docs.telerik.com/devtools/document-processing/libraries/radziplibrary.
 
Have you ever wondered how to increase the responsiveness of your applications by compressing
the data that you send over the internet? With the new Zip Library you can compress data like
images, docx or pdf files and send them over the wire. Thus, you will achieve fast and secure
transactions.

This is a list with short descriptions of the top-of-the-line features of Telerik's Zip Library control:

 Easy to use API: The library exposes flexible and easy API to provide you with full control
over the compressed data. The extension methods allow you to implement the most common
scenarios in a single line of code, like creating zip file from folder or extracting it.
 Load or create ZIP files: You can load data from existing ZIP files, create new ones and edit
ZIPs that can be used by other applications. You can also create ZIP files in memory or add
data to ZIP file from stream.
 Compress a stream: RadZipLibrary can significantly facilitate your efforts in compressing a
stream, for example to send it over the internet.
 Support for large files: The Zip Library works seamlessly with large files (over 4GB).
 Support for encryption: You can protect your ZIP file with password for more security.

Required references
You have two options to add the required Telerik references to your Xamarin.Forms app in order to
use RadZipLibrary:

 Add the Telerik UI for Xamarin Nuget package following the instructions in Telerik NuGet
package server topic.

If you don't want to add the all Telerik.UI.for.Xamarin nuget package, you have the option to add a
separate nuget package. For RadZipLibrary you have to install the Telerik.Zip nuget package.

 Add the references to Telerik assemblies manually, check below the required assembly for
RadZipLibrary:
 Telerik.Zip.dll

Please keep in mind this assembly is located in the Portable folder, still, you need to add a
reference to them in the Xamarin.Forms project as well as in each of the platform projects
(Android | iOS | UWP).
 

1735
Telerik UI for Xamarin

Xamarin Forms vs Xamarin Native(Xamarin.iOS &


Xamarin.Android)
If you are new to the Xamarin world and are still hesitating what approach to take for developing your
application, you should familiarize yourself with the strengths and weaknesses of the available
approaches for developing Xamarin applications. We are here summarizing the main points
discussed in the Xamarin.Forms introduction page.

Develop through Xamarin.Forms

Using this approach you can quickly achieve similar look and feel on all available platforms by
sharing the same code base. All controls and views are eventually translated to platform-specific
native elements without the need of any further actions from your side. You should consider this
approach for:

 Apps that require little platform-specific functionality


 Apps where code sharing is more important than custom UI and platform-specific features
 You feel comfortable creating your UI through XAML

If you choose this approach, you should refer to the available custom controls from the Xamarin
Forms Controls section.

For more details check the official Xamarin.Forms documentation.

Develop through Xamarin Native(Xamarin.iOS & Xamarin.Android)


By choosing this approach, you can take full advantage of each platform. You are free to create
platform-specific views to achieve the desired appearance in the smallest details. You can access
native APIs and utilize device-specific features. You should consider this approach for:

 Apps that require native behavior


 Apps that need to use platform-specific APIs
 Apps where you need to achieve custom UI according to the target platform

For more details check the official Xamarin.iOS and Xamarin.Android documentation pages.

Native Controls Wrappers


Aside from the Xamarin.Forms control that the Progress Telerik UI for Xamarin suite provides, you
can take advantage of the Native Controls Wrappers.

Android Controls
The Android Wrappers are built on top of the truly native controls from the UI for Android
suite(discontinued as a separate product as of April 20th 2017). The following controls are available
for Xamarin.Android development:

1736
Telerik UI for Xamarin

 AutoComplete
 Calendar
 Chart
 DataForm
 DataSource
 Gauges
 ListView
 NumberPicker
 ScrollView
 SideDrawer
 TabView

iOS Controls
The iOS Wrappers are built on top of the truly native controls from the UI for iOS suite(discontinued
as a separate product as of April 20th 2017). The following controls are available for Xamarin.iOS
development:

 Alert
 AutoCompleteTextView
 Calendar
 Chart
 DataForm
 DataSource
 Gauges
 ListView
 SideDrawer

Though the UI for iOS and UI for Android suites have been discontinued as available products we
are using them as basis for the Xamarin.Android and Xamarin.iOS controls. With this in mind, we are
still dedicated to improving their quality and features so they fit nicely and provide smooth
development experience in the Xamarin world.
 

1737
Telerik UI for Xamarin

Xamarin.Android Wrappers
Telerik UI for Xamarin suite includes Xamarin.Android wrappers built on top of truly native Android
components. Our Xamarin.Android controls deliver fast loading, excellent drawing capabilities,
pixel-perfectness and sleek interactivity on any device and screen-size running Android. The product
bridges missing controls and functionalities in the Android native offering including charts, calendar,
list and more.

To learn more please visit the Telerik UI for Xamarin product overview page.

Download Free TrialDownload Free Trial

Controls Overview
Our suite features the following controls for development with Xamarin.Android:

 AutoComplete: An input control that provides users with suggestions, based on the text or
characters they’ve already typed into the search bar. Once the autocomplete shows a list of
suggestions, the user can select one or more of them. The control provides means for easy
customization and data management.
 CalendarView: A calendar control which provides different date representations (in a week,
month or year), different selection modes and events integration.
 ChartView: A charting control that supports different chart types (and series) organized in
hierarchies, depending on the coordinate system, used to plot the data points—for example
Cartesian (RadCartesianChartView) and radial (RadPieChartView) coordinate systems.
 DataForm: A control that provides an easy and versatile approach to processing data objects’
public members and building mobile forms fast.
 DataSource: It is a non-UI control for working with in-memory data which makes it easy for
developers to perform sorting, filtering and grouping operations.
 Gauge: A highly customizable component that allows you to show the current status of a
value within a range of upper and lower bounds, illustrate progress towards a goal or a
summary of a fluctuating metric.
 NumberPicker: An editing component that allows users to select a number with incremental
step adjustments.
 TabView: Allows developers to create user interfaces similar to the android tab view (view
pager and app bar combo) but is a lot easier to use. On top of that, the tabs of RadTabView
can be positioned on all four sides of the parent view (typically of the main view).
 ListView: A list control which provides popular list features that you will need in you app like:
selection, item reordering, loading items on demand, etc.
 SideDrawer: The control is a highly customizable drawer that uses slide-out design pattern
and allows developers to embed any content inside the sliding panel from text and icons to
sliders and filters.
 ScrollView: A layout container for a view hierarchy that can be scrolled by the user both
horizontally and vertically, allowing it to be larger than the physical display.

Trial Version and Commercial License

1738
Telerik UI for Xamarin

Telerik UI for Xamarin library is a commercial UI library. You are welcome to explore its full
functionality and get technical support from the team when you register for a free 30-day trial. To use
it commercially, you need to purchase a license. Feel free to review the Telerik UI for Xamarin
License Agreement to get acquainted with the full terms of use.

Support Options
For any issues you might encounter while working with Telerik UI for Xamarin, use any of the
available support channels:

 UI for Xamarin license holders and active trialists can take advantage of the outstanding
customer support delivered by the developers building the library. To submit a support ticket,
use the UI for Xamarin dedicated support system.
 UI for Xamarin forums are part of the free support you can get from the community and from
the UI for Xamarin team on all kinds of general issues.
 UI for Xamarin feedback portal provides information on the features in discussion and also the
planned ones for release.
 You may still need a tailor-made solution for your project. In such cases, go straight to
Progress Services.

Learning Resources
 Knowledge Base
 Support Resources Hub Page

1739
Telerik UI for Xamarin

Telerik UI for Xamarin.Android: Getting Started


This article explains how to start using Telerik UI for Xamarin.Android controls.

The Telerik UI for Xamarin.Android Xamarin distribution comes as a set of Dynamic Link Libraries.
To be able to use Telerik UI for Xamarin.Android controls, you will need to complete the following
steps:

1. Add references to the libraries inside your project.


2. Add the required AndroidX packages using the NuGet.

With R3 2020 release we have migrated our Xamarin.Android components to use AndroidX. This
allows to use all the latest development in Android extensions (AndroidX) along with our controls.

You can read more on AndroidX and Xamarin here:


https://docs.microsoft.com/en-us/xamarin/android/platform/androidx

System Requirements
Check below the requirements for using our Xamarin.Android components:

 Visual Studio 2019 - On Windows update to Visual Studio 2019 version 16.4 or later. On
macOS, update to Visual Studio 2019 for Mac version 8.4 or later.
 Xamarin.Android - Xamarin.Android 10.0 or later must be installed with Visual Studio
(Xamarin.Android is automatically installed as part of the Mobile Development With .NET
workload on Windows and installed as part of the Visual Studio for Mac Installer)
 Java Developer Kit - Xamarin.Android 10.0 development requires JDK 8. Microsoft's
distribution of the OpenJDK is automatically installed as part of Visual Studio.
 Android SDK - Android SDK API 28 or higher must be installed via the Android SDK
Manager.

Referencing the libraries from your project


Check Download Product Files topic for detailed instructions on how to navigate to Telerik UI for
Xamarin download page. Download "Telerik_UI_for_Xamarin_[version]_[license].zip" file which
contains the needed assemblies for Xamarin.Android development inside Binaries/Android folder.
 

1. Click on Android App (Xamarin) project template in Visual Studio to create a new
Xamarin.Android solution:

1740
Telerik UI for Xamarin

2. Go through the next steps to configure the solution location, minimum Android version, etc.
3. Add references to the Telerik.Xamarin.Android.* libraries by right-clicking the References of
your project and selecting Edit References....

4. Add the following AndroidX packages using the NuGet:


 Xamarin.AndroidX.RecyclerView

1741
Telerik UI for Xamarin

 Xamarin.AndroidX.AppCompat.Resources
 Xamarin.AndroidX.Lifecycle.LiveData
 Xamarin.AndroidX.Browser
 Xamarin.AndroidX.Legacy.Support.V4
 Xamarin.Google.Android.Material
 Xamarin.AndroidX.Migration

5. Your solution is now ready to use Telerik UI for Xamarin.Android.

Opening the Samples solution


Samples solution that shows how to use the controls when developing through Xamarin.Android is

1742
Telerik UI for Xamarin

included in the Telerik UI for Xamarin zip file provided for manual installation.

Telerik_UI_for_Xamarin_[version]_[license].zip, where [version] marks the release and [license] is


replaced with Dev or Trial depending on the license, is available for download from the Downloads
section of your Telerik account. Unzip the archive and go to Examples folder - Xamarin.Android
solution is available in the Android folder.

In addition, the Samples solution is included as part of the Telerik UI for Xamarin MSI installation. You
can find it in the "[installation-path]/Telerik UI for Xamarin [version]/Examples" folder.

1743
Telerik UI for Xamarin

AutoComplete for Xamarin.Android:


Overview
RadAutoCompleteTextView can automatically complete user input string by comparing the text being
entered to all strings in the associated data source. The control provides means for easy
customization and data management.

RadAutoCompleteTextView supports also:

 Customizable Tokens
 Token Layout Modes
 Suggest Modes
 Suggestion Match Highlighting
 Completion Modes
 Display Modes

1744
Telerik UI for Xamarin

AutoComplete for Xamarin.Android: Getting Started


In this article you will learn how to initialize RadAutoCompleteTextView and use it with its basic
configuration.

Initialization
In order to use RadAutoCompleteTextView you need to add references to the Input, Common, List
and Primitives libraries which are part of Telerik UI for Xamarin.Android suite.

After your project is set up and ready to use TelerikUI, you need to create an instance of
RadAutoCompleteTextView. The common way to do this is to create an RauAutoCompleteTextView
in the XML layout of your activity.

XML
<com.telerik.widget.autocomplete.RadAutoCompleteTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:id="@+id/autocmp">
</com.telerik.widget.autocomplete.RadAutoCompleteTextView>
 

Then you should access the autocomplete object in your activity/fragment and populate it with data.

C#
this.autocomplete =
(RadAutoCompleteTextView)rootView.FindViewById(Resource.Id.autocmp);
 

Populate with data


In order to populate the autocomplete you need to create an AutoCompleteAdapter object and
pass it the array of suggestions which should be TokenModel objects. The TokenModel is a unified
object used by the autocomplete to represent data objects as suggestions or tokens.

We will use the following list of string for the purposes of the examples.

C#
this.data = new List<string>() { "Australia", "Albania","Austria", "Argentina",
"Maldives",
"Bulgaria","Belgium","Cyprus","Italy","Japan",
"Denmark","Finland","France","Germany","Greece","Hungary","Ireland",
"Latvia","Luxembourg","Macedonia","Moldova","Monaco","Netherlands","Norway",
"Poland","Romania","Russia","Sweden","Slovenia","Slovakia","Turkey","Ukraine",
"Vatican City", "Chad", "China", "Chile" };
 

1745
Telerik UI for Xamarin

Then we will create TokenModel object out of the original data array.

C#
private List<TokenModel> GetTokenObjects()
{
List<TokenModel> feedData = new List<TokenModel>();
for (int i = 0; i < this.data.Count; i++)
{
TokenModel token = new TokenModel(this.data[i], null);
feedData.Add(token);
}

return feedData;
}
 

Finally, we will create a AutoCompleteAdapter with the list of TokenModel objects.

C#
this.adapter = new AutoCompleteAdapter(this.Context, this.GetTokenObjects(),
Java.Lang.Integer.ValueOf(Resource.Layout.suggestion_item_layout));
this.adapter.CompletionMode = CompletionMode.StartsWith;
this.autocomplete.Adapter = this.adapter;
 

Autocomplete is now ready to be used. You can additionally set up its suggest and display modes
according to your needs.

C#
this.autocomplete.SuggestMode = SuggestMode.Suggest;
this.autocomplete.DisplayMode = DisplayMode.Plain;
 

1746
Telerik UI for Xamarin

1747
Telerik UI for Xamarin

AutoComplete for Xamarin.Android: Completion modes


RadAutoCompleteTextView has two modes for filtering suggestions.

 StartsWith
 Contains

The completion mode can be changed with the CompletionMode property of the
AutoCompleteTextView's adapter (of type AutoCompleteAdapter). The default value is
CompletionMode.StartsWith.

C#
this.adapter.CompletionMode = CompletionMode.StartsWith;
 

StartsWith Mode
In CompletionMode.StartsWith mode the autocomplete shows only suggestions that start with
the typed phrase.

Contains Mode
In CompletionMode.Contains mode the autocomplete shows only suggestions that contain the
typed phrase.

1748
Telerik UI for Xamarin

Contains Mode is not intended to work with the APPEND and SUGGEST_APPEND modes. Since both
these modes append the rest of the suggestion to the typed text, the combination between these
modes won't be helpful, it will be rather confusing.

1749
Telerik UI for Xamarin

AutoComplete for Xamarin.Android: Display Modes


RadAutoCompleteTextView has two predefined display modes.

 Plain
 Tokens

Display mode can be changed with the DisplayMode property of the RadAutoCompleteTextView.
The default value is DisplayMode.Plain.

C#
this.autocomplete.DisplayMode = DisplayMode.Tokens;
 

Plain mode
In plain mode RadAutoCompleteTextView displays chosen item as plain text. When this mode only
one item can be chosen.

Tokens mode
Tokens mode allows multiple choice of items. Chosen items are displayed as tokens which can be
modified or completely changed with custom ones.

1750
Telerik UI for Xamarin

When RadAutoCompleteTextView is working in DisplayMode.Tokens, you can apply two different


behaviors for token arrangement.

 Wrap
 Horizontal

The layout mode of the tokens can be changed with the LayoutMode property of the
RadAutoCompleteTextView. The default value is DisplayMode.Wrap.

C#
this.autocomplete.TokensLayoutMode = LayoutMode.Horizontal;
 

Wrap layout
In wrap mode tokens are arranged on multiple lines. Every time a new line is started the
RadAutoCompleteTextView is expanding in order to show all tokens. When expand limit is reached
the RadAutoCompleteTextView stops expanding and allows only scrolling. The expand limit can be
set with the MaximumWrapHeight property of the autocomplete. Default value is three times the
initial height of the RadAutoCompleteTextView.

1751
Telerik UI for Xamarin

Horizontal layout
In horizontal layout tokens are displayed on single line which can be scrolled horizontally in order to
display all tokens.

1752
Telerik UI for Xamarin

1753
Telerik UI for Xamarin

AutoComplete for Xamarin.Android: Suggest Modes


RadAutoCompleteTextView has three different modes for providing suggestions, namely:

 Suggest
 Append
 SuggestAppend

The suggest mode can be changed with the SuggestionMode property of the
AutoCompleteTextView. The default value is SuggestMode.Suggest.

C#
this.autocomplete.SuggestMode = SuggestMode.Suggest;
 

Suggest Mode
In SuggestMode.Suggest the autocomplete represents the filtered suggestions, matching the typed
text, in a pop-up view, which contains list of the suggestions.

Append Mode

1754
Telerik UI for Xamarin

In SuggestMode.Append mode the autocomplete shows only the first suggestion matching the
typed text, which is represented as direct suffix of the typed text.

SuggestAppend Mode
In SuggestMode.SuggestAppend mode the autocomplete combines both upper-mentioned modes.
It shows all matching suggestions in a pop-up view and the first of them is appended to the typed
text.

1755
Telerik UI for Xamarin

1756
Telerik UI for Xamarin

AutoComplete for Xamarin.Android: Using Remote Data


In this article, you are going to learn how to load and filter suggestions from a remote provider
according to the text typed by the user.

How does it work


There are multiple scenarios where we need to represent data loaded from remote provider like a
web service. Dynamic loading of items, based on the user input could be quite useful when we are
working with sets of data that are not available locally.

In order to provide this feature, the RadAutoCompleteTextView allows you to take full control over
it's filtering logic.In your custom filtering logic you should include the remote request to the server
based on the current user input. Once the server has returned response, you need to parse the data
into TokenModel objects and notify the RadAutoCompleteTextView that the remote loading is over.

In the next few sections we will discuss the process of working with remote data in details with
step-by-step explanations.For the purpose of the example we will use .json data containing
description of airports.

Step-by-step: Enable asynchronous loading


In order to start loading remote data into the RadAutoCompleteTextView you need to notify the
control that you will provide the suggestions on later point of the execution. Meaning, you will
initialize the adapter with empty collection of suggestions and then, every time the user types a
character, you will update the control with the loaded suggestions from your request.

All you need to do is set the UsingAsyncData property to true. This way the
RadAutoCompleteTextView will be aware of the remote data loading and will operate in a tolerant
manner.

C#
this.autocomplete.UsingAsyncData = true;
this.adapter = new AutoCompleteAdapter(
this.Context, new List<TokenModel>(),
Integer.ValueOf(Resource.Layout.suggestion_item_layout));
 

Step-By-Step: Completion mode implementation


The Completion mode is the piece of code, responsible for providing filtered list with TokenModel
objects, which is used to populate the suggestionsView.By default the autocomplete supports two
completion modes - StartsWith and Contains, differing from each other by the rule on which
items are being filtered.

To plug your logic into the RadAutoCompleteTextView workflow you should implement custom
completion mode and execute the remote request logic in it.

1757
Telerik UI for Xamarin

C#
public class StartsWithRemote : Java.Lang.Object, IFunction2Async
{
private RadAutoCompleteTextView autocomplete;

public StartsWithRemote(RadAutoCompleteTextView autocomplete)


{
this.autocomplete = autocomplete;
}

public void Apply(Java.Lang.Object autoCompleteText,


Java.Lang.Object originalCollection, IProcedure finishedCallback)
{
IList list = originalCollection as IList;

if (list == null)
{
FeedAutoCompleteTask task = new FeedAutoCompleteTask(
finishedCallback, (string)autoCompleteText, this.autocomplete);
task.Execute();
}
}
}
 

Step-By-Step: Remote request logic


In order to achieve a smooth behavior you will need to create a class responsible for the connection
to the remote server and the processing of the request. This class should extend the AsyncTask
class and implement the RunInBackground and OnPostExecute methods.

In the RunInBackground method is placed the request to the server. In case the request has
succeeded we are saving the response as JSONArray.

C#
protected override Java.Lang.Void RunInBackground(params string[] @params)
{
HttpURLConnection urlConnection = null;
try
{
URL url = new URL

("http://www.telerik.com/docs/default-source/ui-for-ios/airports.json?sfvrsn=2");

urlConnection = (HttpURLConnection)url.OpenConnection();

urlConnection.RequestMethod = "GET";
urlConnection.UseCaches = false;
urlConnection.AllowUserInteraction = false;
urlConnection.Connect();
HttpStatus status = urlConnection.ResponseCode;

1758
Telerik UI for Xamarin

if (status.Equals(HttpStatus.Ok))
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(urlConnection.InputStream));
char[] buffer = new char[1024];
int n;
Writer writer = new Java.IO.StringWriter();

while ((n = reader.Read(buffer)) != -1)


{
writer.Write(buffer, 0, n);
}

string json = writer.ToString();

try
{
JSONObject jObj = new JSONObject(json);
data = jObj.GetJSONArray("airports");
}
catch (JSONException ex)
{
ex.PrintStackTrace();
}
}

}
catch (Java.IO.IOException e)
{
e.PrintStackTrace();
}
finally
{
if (urlConnection != null)
{
urlConnection.Disconnect();
}
}

return null;
}
 

Right after the RunInBackground method has finished execution the OnPostExecute callback will
be triggered.After you have obtained the suggestions, you should filter them according the user input
and notify the autocomplete that the suggestion data is available.

C#
protected override void OnPostExecute(Java.Lang.Void result)
{
ArrayList filtered = new ArrayList();
remoteData = GetTokenModelObjects(data);

1759
Telerik UI for Xamarin

foreach (TokenModel item in remoteData)


{
string text = item.Text;
if (text.ToLower().StartsWith(filter.ToLower()))
{
filtered.Add(item);
}
}
remoteCallback.Apply(filtered);
autocomplete.ResolveAfterFilter(autocomplete.TextField.Text.ToString(), true);
}
 

Have in mind these few notes on the snippet above:

 Although we are performing the filtering logic in the OnPostExecute method, it is best to be
performed on the server side whenever possible.
 GetTokenModelObjects is a helper method used to convert the raw JSONArray data to
List.
 The remoteCallback variable holds callback provided by the autocomplete which contains
logic for updating the source of the adapter with the provided parameter.
 The ResolveAfterFilter method used to notify the RadAutoCompleteTextView that the
remote data is available and it should complete the cycle of showing suggestions. The
second parameter is a boolean flag used by the RadAutCompleteTextView to make
difference between manual invocation of the ResolveAfterFilter method and invocation
by the control itself.

Whenever you are using the ResolveAfterFilter method, you should pass true as second
parameter. The false value is reserved for internal invocations.

Full implementation
This is the full code for the custom completion mode and the custom aync task.

C#
public class StartsWithRemote : Java.Lang.Object, IFunction2Async
{
private RadAutoCompleteTextView autocomplete;

public StartsWithRemote(RadAutoCompleteTextView autocomplete)


{
this.autocomplete = autocomplete;
}

public void Apply(Java.Lang.Object autoCompleteText,


Java.Lang.Object originalCollection, IProcedure finishedCallback)
{
IList list = originalCollection as IList;

if (list == null)
{

1760
Telerik UI for Xamarin

FeedAutoCompleteTask task = new FeedAutoCompleteTask(


finishedCallback, (string)autoCompleteText, this.autocomplete);
task.Execute();
}
}
}

class FeedAutoCompleteTask : Android.OS.AsyncTask<string, string, Java.Lang.Void>


{
JSONArray data;
List<TokenModel> remoteData;
private IProcedure remoteCallback;
private string filter;
private RadAutoCompleteTextView autocomplete;

public FeedAutoCompleteTask(IProcedure callback, string filter,


RadAutoCompleteTextView autocomplete)
{
this.remoteCallback = callback;
this.filter = filter;
this.autocomplete = autocomplete;
this.data = new JSONArray();
}

protected override Java.Lang.Void RunInBackground(params string[] @params)


{
HttpURLConnection urlConnection = null;
try
{
URL url = new URL

("http://www.telerik.com/docs/default-source/ui-for-ios/airports.json?sfvrsn=2");

urlConnection = (HttpURLConnection)url.OpenConnection();

urlConnection.RequestMethod = "GET";
urlConnection.UseCaches = false;
urlConnection.AllowUserInteraction = false;
urlConnection.Connect();
HttpStatus status = urlConnection.ResponseCode;

if (status.Equals(HttpStatus.Ok))
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(urlConnection.InputStream));
char[] buffer = new char[1024];
int n;
Writer writer = new Java.IO.StringWriter();

while ((n = reader.Read(buffer)) != -1)


{
writer.Write(buffer, 0, n);
}

1761
Telerik UI for Xamarin

string json = writer.ToString();

try
{
JSONObject jObj = new JSONObject(json);
data = jObj.GetJSONArray("airports");
}
catch (JSONException ex)
{
ex.PrintStackTrace();
}
}

}
catch (Java.IO.IOException e)
{
e.PrintStackTrace();
}
finally
{
if (urlConnection != null)
{
urlConnection.Disconnect();
}
}

return null;
}

protected override void OnPostExecute(Java.Lang.Void result)


{
ArrayList filtered = new ArrayList();
remoteData = GetTokenModelObjects(data);
foreach (TokenModel item in remoteData)
{
string text = item.Text;
if (text.ToLower().StartsWith(filter.ToLower()))
{
filtered.Add(item);
}
}
remoteCallback.Apply(filtered);
autocomplete.ResolveAfterFilter(autocomplete.TextField.Text.ToString(), true);
}
 

In case you want to see this scenario in action, you should check our SDK examples repo on
GitHub. You will find there this and a lot of more practicle examples with Telerik UI.

 Android implementation
 Xamarin implementation

1762
Telerik UI for Xamarin

AutoComplete for Xamarin.Android: Event Listeners


In this article you are going to learn about the RadAutoCompleteTextView's event listeners.

The event listeners are designed to notify you whenever a particular action, in the workflow of the
control, has happened. They are quite useful when it comes to executing logic based on the
RadAutoCompleteTextView's state.

Available listeners
RadAutoCompleteTextView control exposes five different event listeners:

 TokenRemovedListener - triggered whenever a token is removed.


 TokenAddedListener - triggered whenever a token is added.
 TokenSelectedListener - triggered whenever a token is selected (highlighted)
 TokenDeselectedListener - triggered whenever a token is deselected (back to normal
state)
 ShowSuggestionListListener - triggered whenever the suggestion view is about to
become visible.

All five of the listeners have identical logical structure and identical workflow, the only difference
between them is the event which they are observing and notifying you about.

Usage
In order to get notified when one of the above-mentioned events occur, you should use the following
structure with the type of listener you want to use.

C#
this.autocomplete.AddTokenAddedListener(new TokenAddedListenerImpl());

class TokenAddedListenerImpl : Java.Lang.Object, ITokenAddedListener


{
public void OnTokenAdded(RadAutoCompleteTextView p0, TokenModel p1)
{
// do something
}
}
 

1763
Telerik UI for Xamarin

CalendarView for Xamarin.Android:


Overview
RadCalendarView for Android is a calendar component that has been designed for the mobile
environment. It offers great performance, powerful customization options and various features.The
dates in the calendar can be presented with different modes which visualize Month, Week, Year,
Day, MultiDay Views and Agenda. The user can provide a selection in different selection modes -
Single, Multiple or Range depending on the required results.Different scroll modes are available
including but not limited to: Sticky, Combo and Stacked.The calendar also offers events integration.

Display Modes
RadCalendarView provides different display modes, which allow you to present dates from a month,
a week or an year, depending on you preferences:

1764
Telerik UI for Xamarin

Selection Modes
RadCalendarView can be setup to provide different selection capabilities to the user. Depending on
the current scenario and the required input from the user, the selection can be Single (to pick just a
single date),multiple (to pick many dates) or range (to select a range of consecutive dates, for
example to choose the period of a vacation). Hereyou can read more about the types of selection.

Events
The control can present information about events related with each date. The event's information
can be presented with various shapes and styles. You can read more about the events integration
here.

Disabled Dates
You can restrict the dates presented by RadCalendarView by setting values for min and max dates
as well as marking specific dates as disabled. More about disabling dates is available here.

Customizations
RadCalendarView provides different ways for customizing its appearance. You can disable some of
the visible elements like title, day names, grid lines, cell decorations or alter the way they look. You
can also applycustomizations to the calendar cells depending on the dates they represent. Here's a
more descriptive information about the customizable options.

Gestures and Transitions


The calendar control handles different manipulations performed by the user like swiping horizontally

1765
Telerik UI for Xamarin

or vertically, pinching open or close, tapping or double tapping. You can easily select which of these
gestures willbe handled in a way which changes the calendar's properties with nice transitions. You
can also trigger the transitions programmatically. More information is available inthis article.

Localizations
RadCalendarView follows the locale information provided from the user's device settings. If you
want, you can easily apply locale of your choice so that the information that is displayed is translated
and formattedaccording to your preferences. Here's more about the calendar's localizations
capabilities.

Xamarin.Android Examples
Xamarin.Android examples that show how to use RadCalendarView for Xamarin.Android are
included in the Telerik UI for Xamarin zip file provided for manual installation.

Telerik_UI_for_Xamarin_[version]_[license].zip, where [version] marks the release and [license] is


replaced with Dev or Trial depending on the license, is available for download from the Downloads
section of your Telerik account. Unzip the archive and go to Examples/Android folder to access our
Samples Xamarin.Android solution.

1766
Telerik UI for Xamarin

CalendarView for Xamarin.Android: Getting


Started
In this article, you will learn how to get started with RadCalendarView for Android: how to initialize
the calendar, how to set the dates that are displayed and how to create a calendar that looks like this
one:

Project Setup
For CalendarView you will need the following Telerik references:

 Telerik.Xamarin.Android.Common
 Telerik.Xamarin.Android.Data
 Telerik.Xamarin.Android.Input
 Telerik.Xamarin.Android.List
 Telerik.Xamarin.Android.Primitives

1767
Telerik UI for Xamarin

Adding the calendar instance


You can easily add RadCalendarView in the layout file for the main activity of your project:

xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<com.telerik.widget.calendar.RadCalendarView
android:id="@+id/calendarView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

</RelativeLayout>
 

You can access the control from the activity in order to be able to apply further modifications:

C#
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);

RadCalendarView calendarView = FindViewById<RadCalendarView> (


Resource.Id.calendarView);
}
 

Display Date
By default when the calendar is loaded, it shows the current month. If you need to change the month
that is currently visible, you can use the DisplayDate(of type long) property.

Here is an example how to set the DisplayDate property:

C#
RadCalendarView calendarView = new RadCalendarView (Activity);
calendarView.DisplayDate = new GregorianCalendar (2022, Calendar.October,
1).TimeInMillis;
 

Week numbers
At this point the calendar already looks like the screen shot from the beginning of the article. The
only difference is that we still don't see the week numbers. You can show the weeknumbers using

1768
Telerik UI for Xamarin

the WeekNumbersDisplayMode property.

RadCalendarView provides three options for the week numbers:

 None: Week numbers are not displayed


 Inline: Week numbers are displayed inside the first cell of each week
 Block: Week numbers are displayed inside a separate cell in the beginning of each week

By default the selected option is None which explains why the numbers are not currently visible.

C#
RadCalendarView calendarView = new RadCalendarView();
calendarView.WeekNumbersDisplayMode = WeekNumbersDisplayMode.Inline;
 

xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:calendar="http://schemas.android.com/apk/res-auto"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<com.telerik.widget.calendar.RadCalendarView
android:id="@+id/calendarView"
android:layout_width="match_parent"
android:layout_height="match_parent"
calendar:weekNumberDisplayMode="Inline"/>

</RelativeLayout>
 

and the final result:

1769
Telerik UI for Xamarin

1770
Telerik UI for Xamarin

CalendarView for Xamarin.Android: Visual Structure


In this article, you will learn how the RadCalendarView for Android is structured and what manages
its core functionality.

Visual Structure

The calendar is constructed using the following elements:

 Title - holds the title corresponding for the current date and display mode.
 Day Names - displays the names of the days in a week.
 Three fragments - previous fragment holding the date before the current date, current or
active fragment holding the current date and next fragment holding the date after the current
date.

1771
Telerik UI for Xamarin

Title
The title holds information about the current display date. It differs according to the current display
mode.

Day Names
The day names are holding the current set of day names in a single week according to the current
local.

Fragments
The fragments are designed to hold a date and being able to snap to each other. This makes them
perfect for scrolling. At the point of switching the current date to the previous or the next one, the
correspondingfragment is being updated with the new date and snapped on the opposite side of the
current fragment. This virtualization ensures seamless transition between dates, optimizes the use of
resources and minimizes the cpu calculations.In some cases the fragments are not perfectly square
and follow the shape of the cells of their current display date. This applies as seen in the picture
above. This applies when the calendar is in month display mode, the scrolling is vertical and the
scroll modeis not set to Overlap or Stack. When the scroll mode is either Overlap or Stack or the
scroll direction is horizontal, then the fragments are perfectly rectangular holding dates from both
their display date as well as the previous andthe next one as well. This is done to ensure the correct
behaviour when the months are 'linked' together in vertical scrolling.

Managers
There are several managers that together ensure the proper behaviour of the calendar. They
oversee the scrolling, the gestures and the animations.

 Scrolling manager - responsible for applying scrolling, updating and positioning of the
fragments as well as holding the biggest area of the calendar including all calendar cells.
 Gestures manager - handles all the gestures performed on the calendar and triggers the
scrolling and the animation managers.
 Animations manager - performs all animations and transitions such as changing display
modes and animating to next or previous date.

1772
Telerik UI for Xamarin

CalendarView for Xamarin.Android: DisplayMode


RadCalendarView provides various modes for displaying dates. They are Month, Week, Year, Day,
MultiDayand Agenda and are included in the CalendarDisplayMode enumeration.These modes
represent the period that is displayed at once by the control. To change the current mode use the
CalendarView DisplayMode property. If there is no DisplayMode set, the default value is Month

Month
This is the default display mode for RadCalendarView and means that the control displays a
representation of one month.

C#
RadCalendarView calendarView = new RadCalendarView();
 

This is the result:

1773
Telerik UI for Xamarin

Week
This mode represents the dates from one week and they look as one of the rows that are displayed
while the control is in Month display mode. Let's set the display mode of our RadCalendarView
instance to Week:

C#
RadCalendarView calendarView = new RadCalendarView();
calendarView.DisplayMode = CalendarDisplayMode.Week;
 

Here's the result:

Year
This mode represents all dates from one year grouped in months in a way similar to a calendar that
stands on the wall. Here's how it looks:

1774
Telerik UI for Xamarin

C#
RadCalendarView calendarView = new RadCalendarView();
calendarView.DisplayMode = CalendarDisplayMode.Year;
 

How the Year Mode looks:

Since the default look of the year view contains a lot of dates it may seem too overcrowded on
smaller devices. This is why this view also has a compact mode, where the months are represented
only by their names and the exact dates are not drawn.Whether the Year view is in compact mode
can be changed through the YearCompactMode(bool) property.

C#
RadCalendarView calendarView = new RadCalendarView();
calendarView.DisplayMode = CalendarDisplayMode.Year;
calendarView.YearModeCompact = true;
 

1775
Telerik UI for Xamarin

Day
Day ViewMode allows you to display the schedule for a specific day in RadCalendarView.

C#
RadCalendarView calendarView = new RadCalendarView();
calendarView.DisplayMode = CalendarDisplayMode.Day;
 

Here is how the DisplayMode Day looks:

1776
Telerik UI for Xamarin

Sample Day View example can be found in our Xamarin.Android Samples inside the
/Calendar/DayView folder.
 

MultiDay
RadCalendarView comes with MultiDay view mode which enables you to create a detailed view of
the schedule for a specific day (or days).

C#
RadCalendarView calendarView = new RadCalendarView();
calendarView.DisplayMode = CalendarDisplayMode.MultiDay;
 

Here is how the MultiDay DisplayMode looks:

1777
Telerik UI for Xamarin

Sample MultiDay GettingStarted example can be found in our Xamarin.Android Samples inside the
/Calendar/MultiDayView folder.
 

Agenda
Agenda display mode shows a list of the scheduled appointments grouped by date. With Agenda
you can enable the app users to quickly check on everything coming up in their calendars.

C#
RadCalendarView calendarView = new RadCalendarView();
calendarView.DisplayMode = CalendarDisplayMode.Agenda;
 

Here is how the Agenda Display Mode looks:

1778
Telerik UI for Xamarin

Sample DisplayMode example with Agenda can be found in our Xamarin.Android Samples inside the
/Calendar/DisplayMode folder.
 

Change Display Mode


The CalendarView DisplayMode can be easily changed using the
CalendarView.ChangeDisplayMode method.

Example:

C#
RadCalendarView calendarView = new RadCalendarView();

If(calendarView.DisplayMode == CalendarView.Month)
{
calendarView.ChangeDisplayMode(CalendarView.Agenda, false);
}
 

1779
Telerik UI for Xamarin

Sample DisplayMode example can be found in our Xamarin.Android Samples inside the
/Calendar/DisplayMode folder.
 

See Also
 Events
 Selection

1780
Telerik UI for Xamarin

CalendarView for Xamarin.Android:


Selection
RadCalendarView provides three different types of selection: Single, Multiple and Range. They are
contained in the CalendarSelectionMode enumeration.The default value is Multiple and you
can change it either using the XML attribute selectionMode or using the property
SelectionMode(CalendarSelectionMode).

The selected dates change when the user taps on a cell of the calendar. The selected dates can
also be set by the SelectedDates(List) property.

Multiple Selection
This is the default calendar selection mode. When the calendar is using this mode each cell that is
tapped changes its selected state, this means that when a cell is tapped for first time it gets added to
the current selection andwhen it is tapped again it is removed from the selection. Here's an example
of how to select the Monday, Wednesday and Friday from the current week:

C#
Calendar calendar = Calendar.Instance;
List<Java.Lang.Long> dates = new List<Java.Lang.Long>();

calendar.Set(CalendarField.DayOfWeek, Calendar.Monday);
dates.Add((Java.Lang.Long)calendar.TimeInMillis);

calendar.Set(CalendarField.DayOfWeek, Calendar.Wednesday);
dates.Add((Java.Lang.Long)calendar.TimeInMillis);

calendar.Set(CalendarField.DayOfWeek, Calendar.Friday);
dates.Add((Java.Lang.Long)calendar.TimeInMillis);

calendarView.SelectedDates = dates;
 

Here's the result:

1781
Telerik UI for Xamarin

Single Selection
When RadCalendarView's selection mode is set to Single, each time a cell is tapped it becomes
selected and if another cell has already been selected it is unselected.

Range Selection
The Range selection mode allows the users to pick a range of consecutive dates, for example to
book a hotel for this period. Here's how the control reacts to the user's gestures while in this mode.
The first cell that is tappedgets selected and is considered start of the range. When another cell is
tapped, it is considered end of the range and all dates between the start and the end of the range
become selected. In order to obtain or determine theselected range programmatically, you can use
the same methods as in the other modes: getSelectedDates() and setSelectedDates(List). Your
other option is to use the methods getSelectedRange() andsetSelectedRange(DateRange) to get or
set the range that is selected. They use an object of type DateRange to represent the selection. This
is a simple type which contains information about the start and the end of one range of dates.Here's
an example of how to use the DateRange to set the selection to the three dates which start from
today:

1782
Telerik UI for Xamarin

C#
calendarView.SelectionMode = CalendarSelectionMode.Range;

Calendar calendar = Calendar.Instance;


long start = calendar.TimeInMillis;

calendar.Add(CalendarField.Date, 2);
long end = calendar.TimeInMillis;

DateRange dateRange = new DateRange(start, end);


calendarView.SelectedRange = dateRange;
 

It is also possible to use the range selection gesture to select a range of dates. It can be enabled by
using the setUsingDragToMakeRangeSelection(boolean) method in the gesture manager. The
gesture manager can be obtained from the calendar's method getGestureManager().Setting this to
true will enable the range selection gesture and will prevent the calendar from scrolling. It is however
recommended that you disable the scrolling manually to be extra safe. This is done by using the
setScrollMode(ScrollMode) and passing None as current scroll mode.You can read more about scroll
modes here's

If you try to use the methods getSelectedRange or setSelectedRange(DateRange) while calendar's


selection mode is not Range, an Exception will be thrown.
 

Callback
You can use the RadCalendarView.OnSelectedDatesChangedListener to get notified about changes
in the selection. For example here's how to show a Toast with the selected date:

C#
calendarView.SelectionMode = CalendarSelectionMode.Single;
calendarView.OnSelectedDatesChangedListener =
new SelectedDatesChangedListenerExample();

...

//SelectedDatesChagedListenerExample sample implementation:


class SelectedDatesChangedListenerExample : Java.Lang.Object,
Com.Telerik.Widget.Calendar.RadCalendarView.IOnSelectedDatesChangedListener
{
public void OnSelectedDatesChanged (RadCalendarView.SelectionContext context)
{
if (context.NewSelection ().Count > 0) {
Calendar calendar = Calendar.Instance;
foreach(long item in context.NewSelection()) {
calendar.TimeInMillis = item;
DateTime selectedDateTime = new DateTime (
calendar.Get (CalendarField.Year),
calendar.Get (CalendarField.Month) + 1,
calendar.Get (CalendarField.DayOfMonth));

1783
Telerik UI for Xamarin

String formattedDateTime =
String.Format ("{0:yyyy-MM-dd}", selectedDateTime);
Toast.MakeText (Application.Context, formattedDateTime,
ToastLength.Short).Show ();
}
}
}
}
 

In this example we used the NewSelection list, part of the SelectionContext. The selection context
also contains other information about the selection that is presented with four lists of dates:

 OldSelection: list of the items that were selected before the occurrence of this event.
 NewSelection: list of the items that are now selected.
 DatesAdded: list of the items that are currently being added to the selection.
 DatesRemoved: list of items that are currently being removed from the selection.

In order to better understand the difference between these lists consider the following scenario. The
calendar's selection mode is Range and the selected dates are January 1st, 2nd and 3rd. The user
taps on January 15th.At this point the SelectionContext will contain the following lists —
OldSelection: January 1st, 2nd and 3rd; NewSelection: January 15th; DatesAdded: January 15th;
DatesRemoved: January 1st, 2nd and 3rd. As you can seein this case there is a full match between
the DatesAdded and the NewSelection and between the DatesRemoved and the OldSelection lists.
However, this is not always the case. Let's say now the user taps on January 17th. Here isthe
content of the lists now: OldSelection: January 15th; NewSelection: January 15th, 16th and 17th;
DatesAdded: January 16th and 17th; DatesRemoved is empty. Usually you will not be interested in
the content of all of the lists,but depending on your desired experience you can use the information
that you need.

RadCalendarView: Selection Decorators


There are a few decorators offering the functionality of decorating the currently selected cells. The
decorators are currently in three groups:

 Segmented decorators - decorators which draw borders around the selected cells.
 Cell decorators - decorators which draw directly on top of the selected cell.
 Range decorators - decorators which draw on top of the selected cells in a range selection
by combining a shape for the range and an indicator for the last date in the selection.

Segmented decorator

1784
Telerik UI for Xamarin

This is the default decorator of the RadCalendarView. It is used for any type of selection in the
calendar. The way to set it is the following:

C#
SegmentDecorator decorator = new SegmentDecorator(calendarView);
decorator.Color = Android.Graphics.Color.ParseColor("#009688");
decorator.StrokeWidth = 5;

calendarView.CellDecorator = decorator;
 

Cell decorators

1785
Telerik UI for Xamarin

The cell decorators are ideal for single selection mode. However they can be used in any of the
available selection modes.

The current cell decorators are:

 CircularCellDecorator - renders a circle on top of the selected cell.


 RectangularCellDecorator - renders a rectangle on top of the selected cell.
 SquareCellDecorator - renders a square on top of the selected cell.

Here is an example of how the set one:

C#
calendarView.Adapter.DateTextPosition = CalendarElement.Center;
calendarView.Adapter.SetDateCellBackgroundColor(Android.Graphics.Color.White,
Android.Graphics.Color.White);

calendarView.Adapter.SelectedCellBackgroundColor = Android.Graphics.Color.White;

CellDecorator decorator = new CircularCellDecorator(calendarView);


decorator.Color = (Android.Graphics.Color.ParseColor("#ed742c"));
decorator.StrokeWidth = 2;
decorator.Scale = .75f;

calendarView.CellDecorator = decorator;
 

Cell decorators can be either stroked or filled. This is determined by the stroked property:

C#
decorator.Stroked = false;

1786
Telerik UI for Xamarin

This code will cause the decorator to draw its shapes filled instead of stroked.

Range decorators

These decorators are only available for range selection mode. They are used to visualize the range
selection with a shape going from the first date of the selection to the last one. They also have an
indicator rendered on the last date of the selection.The range decorators that are currently available
are:

 CircularRangeDecorator - draws a rounded shape and a circular indicator.


 SquareRangeDecorator - draws a rectangular shape and a square indicator.

Here is an example of a circular decorator:

C#
calendarView.Adapter.DateTextPosition = CalendarElement.Center;
calendarView.Adapter.SetDateCellBackgroundColor(Android.Graphics.Color.White,
Android.Graphics.Color.White);

calendarView.Adapter.SelectedCellBackgroundColor = Android.Graphics.Color.White;
calendarView.Adapter.SelectedCellTextColor = Android.Graphics.Color.White;
calendarView.SelectionMode = CalendarSelectionMode.Range;

RangeDecorator decorator = new CircularRangeDecorator(calendarView);


decorator.Color = Android.Graphics.Color.ParseColor("#f85725");
decorator.ShapeColor = Android.Graphics.Color.ParseColor("#8bcc46");
decorator.StrokeWidth = 2;

1787
Telerik UI for Xamarin

decorator.Scale = .65f;
decorator.ShapeScale = .75f;
decorator.Stroked = false;

calendarView.CellDecorator = decorator;
 

Extending the decorator

Every of the different types of decorators is designed for easy and seamless extension. Before
deciding to extend one of them the developer must decide which functionality is needed and to turn
to the one that is closer to the final goal.In this case the desired decorator is a flag-like decorator,
which goes all the way on the vertical axis, but has a little space on the sides. Since it will be applied
to all cells separately it is a good idea to extend the CellDecorator:

C#
public override View OnCreateView (LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
RadCalendarView calendarView = new RadCalendarView (Activity);

calendarView.Adapter.DateTextPosition = CalendarElement.Center;
calendarView.Adapter.SetDateCellBackgroundColor(Android.Graphics.Color.White,
Android.Graphics.Color.White);

calendarView.Adapter.SelectedCellBackgroundColor =
Android.Graphics.Color.White;

calendarView.Adapter.SelectedCellTextColor = Android.Graphics.Color.White;
calendarView.SelectionMode = CalendarSelectionMode.Range;

1788
Telerik UI for Xamarin

calendarView.GridLinesLayer.Width = 2;

CellDecorator decorator = new FlagCellDecorator(calendarView);


decorator.Color = Android.Graphics.Color.ParseColor("#2babda");
decorator.StrokeWidth = 2;
decorator.Scale = .45f;
decorator.Stroked = false;

calendarView.CellDecorator = decorator;

return calendarView;
}

private class FlagCellDecorator : CellDecorator


{
private float offsetVertical;

public FlagCellDecorator(RadCalendarView owner) : base(owner)


{
this.offsetVertical = owner.GridLinesLayer.Width / 2;
}

protected override void RenderDecorationForCell(Canvas canvas,


CalendarCell cell) {

int offsetHorizontal =
(cell.Width - (int)(cell.Width * this.Scale)) / 2;

canvas.DrawRect(
cell.VirtualLeft() + offsetHorizontal,
cell.VirtualTop() + this.offsetVertical,
cell.VirtualRight() - offsetHorizontal,
cell.VirtualBottom() - this.offsetVertical,
this.Paint
);

canvas.DrawText(cell.Text,
cell.TextPositionX() + cell.VirtualOffsetX,
cell.TextPositionY() + cell.VirtualOffsetY,
cell.TextPaint);
}
}
 

1789
Telerik UI for Xamarin

CalendarView for Xamarin.Android: Events


RadCalendarView has a built-in infrastructure for handling events. The events that are presented are
handled by an EventAdapter and the way they are rendered is handled by an EventRenderer.Both
classes have their default implementation so that you can simply provide a list of events and the
calendar will take care of the rest.

Adding the events


The Event class that is used by the calendar contains the following information about an event:

 Title: The title of the event.


 StartDate: The time of the start of the event.
 EndDate: The time of the end of the event.
 AllDay: Whether this event is occurring during the whole day.
 CalendarId: The id of the calendar that contains this event.
 EventColor: The color of the event.

The first three are mandatory and must be provided as parameters of the event's constructor. Here's
a simple example of how to create an event and add it to the instance of the calendar:

C#
RadCalendarView calendarView = new RadCalendarView (Activity);

Calendar calendar = Java.Util.Calendar.Instance;


long start = calendar.TimeInMillis;
calendar.Add (CalendarField.Hour, 3);
long end = calendar.TimeInMillis;
Event newEvent = new Event ("Enjoy Life", start, end);

calendar.Add (CalendarField.Hour, 1);


start = calendar.TimeInMillis;
calendar.Add (CalendarField.Hour, 1);
end = calendar.TimeInMillis;
Event newEvent2 = new Event("Walk to work", start, end);
newEvent2.EventColor = Android.Graphics.Color.Green;

IList<Event> events = new List<Event> ();


events.Add (newEvent);
events.Add (newEvent2);

calendarView.EventAdapter.Events = events;

return calendarView;
 

Here's the result:

1790
Telerik UI for Xamarin

You need to call NotifyDataChanged() when the events' information is updated.


 
If you would like to present more information about the events for a certain cell when it's pressed,
you can use a RadCalendarView.SetOnCellClickListener to get notified when this happens. Here's
an example which demonstrates how to display moreinformation about the event that we have just
added when the user taps on the cell that contains it:

C#
calendarView.SetOnCellClickListener(new CellClickListenerExample());

...

//CellClickListenerExample sample implementation


class CellClickListenerExample : Java.Lang.Object,
Com.Telerik.Widget.Calendar.RadCalendarView.IOnCellClickListener
{
public void OnCellClick (CalendarCell calendarCell)
{
if (calendarCell.Class.SimpleName == "CalendarMonthCell") {
return;

1791
Telerik UI for Xamarin

CalendarDayCell calendarDayCell = calendarCell.JavaCast<CalendarDayCell> ();


if(calendarDayCell.Events != null && calendarDayCell.Events.Count > 0) {
StringBuilder eventsInfo = new StringBuilder ();
foreach (Event e in calendarDayCell.Events) {
if (eventsInfo.Length > 0) {
eventsInfo.AppendLine ();
}
eventsInfo.Append(String.Format("{0} - {1}: {2}",
GetFormattedTime("{0:HH:mm}", e.StartDate),
GetFormattedTime("{0:HH:mm}", e.EndDate),
e.Title));
}
Toast.MakeText(Application.Context, eventsInfo.ToString(),
ToastLength.Short).Show();
}
}

private String GetFormattedTime(String format, long time)


{
Calendar calendar = Calendar.Instance;
calendar.TimeInMillis = time;
DateTime dateTime = new DateTime(
calendar.Get (CalendarField.Year),
calendar.Get (CalendarField.Month) + 1,
calendar.Get (CalendarField.DayOfMonth),
calendar.Get (CalendarField.HourOfDay),
calendar.Get (CalendarField.Minute),
calendar.Get (CalendarField.Second));
return String.Format (format, dateTime);
}
}
 

You can easily extend this logic so that the Toast contains information about all events from the
pressed cell even if they are more than one. You can also choose a more appropriate way to present
and format this information.

Customizing the events


The default EventRenderer provides three way of presentation of the events, you can easily change
them to the one that you like most or determine dynamically which one will be used depending on
device's size, density and/or orientation.The different modes are: Text, Shape, ShapeAndText.
They are included in the EventRenderMode enumeration. It also contains None so you can decide
not to show the events if certain conditions are (not) met.The default value is ShapeAndText, which
as you can see from the previous example means that the events are presented with a small shape
(a square) and the text of their title. When the mode is Text, the events will be presentedsimply with
the text of their title written with their event color. When the mode is Shape, they will be presented
with a rectangle which indicates their duration and the time of their occurrence. For example if one
eventlasts longer than another, it will consume more space. Also, if time when one event is
happening is before the time of another it will be drawn higher. Here's how to set the render mode to

1792
Telerik UI for Xamarin

Shape:

C#
calendarView.EventAdapter.Renderer.EventRenderMode = EventRenderMode.Shape;
 

and the result:

You can get the current mode when set the renderer's EventRenderMode property.

If the modes provided by the default event renderer do not suit your needs, you can extend it and
override its RenderEvents(Canvas, CalendarCell) method. This method is responsible for the
drawing of the event representationof the events from the cell that is the second parameter to the
canvas that is the first. Here's an example which draws a circle for each of the events:

C#
public class MyEventRenderer : EventRenderer
{

int shapeSpacing = 25;

1793
Telerik UI for Xamarin

int shapeRadius = 10;


Paint paint;

public MyEventRenderer(Context context)


: base(context)
{

paint = new Paint();


paint.AntiAlias = true;
}

public override void RenderEvents(Canvas canvas, CalendarDayCell cell)


{
int startX = cell.Left + shapeSpacing;
int startY = cell.Top + shapeSpacing;

Rect drawTextRect = new Rect();


if (cell.Text != null)
{
String text = cell.Text;
cell.TextPaint.GetTextBounds(text, 0, text.Length, drawTextRect);
}

int x = startX;
int y = startY;

int spacingForDate = drawTextRect.Width();

for (int i = 0; i < cell.Events.Count; i++)


{
Event e = cell.Events[i];
paint.Color = new Color(e.EventColor);
canvas.DrawCircle(x, y, shapeRadius, paint);
x += shapeSpacing;
if (x > cell.Right - spacingForDate - shapeSpacing)
{
x = startX;
y += shapeSpacing;
}
}
}
 

When your custom renderer is created you can set it to the EventAdapter by using its
Renderer(EventRenderer) property:

C#
MyEventRenderer eventRenderer = new MyEventRenderer(Context);
calendarView.EventAdapter.Renderer = eventRenderer;
 

and the result:

1794
Telerik UI for Xamarin

Extending the events


If the provided event infrastructure is not enough to suit your needs you can easily extend the Event
type and add your own properties.You can also extend the EventAdapter class and set an instance
of your adapter to the calendar by using its EventAdapter(EventAdapter) method.However, the
default event adapter should be enough for most scenarios. The default implementation determines
this list by each event's start date and end date, however, if you add some recurrence information to
the events, you will probably want to use it when determining the list of events for a date.This is
when extending the EventAdapter may be useful as you will be able to provide your custom logic for
the GetEventsForDate(long) method and take your recurrence rules into consideration.

1795
Telerik UI for Xamarin

CalendarView for Xamarin.Android: Special Slots


With R3 2019 release of Telerik UI for Xamarin RadCalendarView for Xamarin.Android provides the
option to define a collection of special and restricted time slots in order to make them noticeable
across the timeline of the Day and MultiDay views.

You just need to prepare a collection of Com.Telerik.Widget.Calendar.Slots.SpecialSlot


objects, create a Com.Telerik.Widget.Calendar.Slots.SlotAdapter object and assign the
SpecialSlots collection to its Slots property.

Every SpecialSlot has the following properties:

 StartDate;
 EndDate;
 IsReadOnly: When set to True the slot is disabled (restricted), meaning the end user
wouldn't be able to create or modify appointments at that slot;
 SlotColor: the background color applied to the defined slot;

Below you can find a quick example how to create special slots.

C#
RadCalendarView calendarView = new RadCalendarView(Activity);
calendarView.DisplayMode = CalendarDisplayMode.Day;

Calendar calendar = Calendar.Instance;


calendar.TimeInMillis = calendarView.DisplayDate;

calendar.Add(CalendarField.Hour, 12);
long startTime = calendar.TimeInMillis;
calendar.Add(CalendarField.Hour, 2);
long endTime = calendar.TimeInMillis;

SpecialSlot lunchSlot = new SpecialSlot(startTime, endTime) { SlotColor =


Color.LightPink };
var slotAdapter = new SlotAdapter(calendarView);
slotAdapter.Slots = new List<SpecialSlot>() { lunchSlot };
calendarView.SlotAdapter = slotAdapter;
 

Here is the result:

1796
Telerik UI for Xamarin

1797
Telerik UI for Xamarin

CalendarView for Xamarin.Android:


Disabled Dates
RadCalendarView allows you to restrict the dates that can be displayed and selected by the users.
This can be achieved by setting minimum date and maximum date for the calendar. The default
values for these properties are 0.This means that there are no restrictions. If you would like to use
the calendar for hotel/flight reservation, you wouldn't want the selection to be possible for dates that
are in the past. In this scenario the minimum datecomes useful.

The followinmg propertiest allows you to set disabled dates:

 MinDate: Specifies the minimum selectable date


 MaxDate: Specifies the maximum selectable date

Here's the example:

C#
RadCalendarView calendarView = new RadCalendarView (Activity);
calendarView.DisplayDate = new GregorianCalendar (2022, Calendar.October,
1).TimeInMillis;
calendarView.MinDate = new GregorianCalendar(2022, Calendar.October, 18).TimeInMillis;
calendarView.MaxDate = new GregorianCalendar(2022, Calendar.October, 27).TimeInMillis;

return calendarView;
 

And here's how the calendar looks when the dates before today are disabled:

1798
Telerik UI for Xamarin

1799
Telerik UI for Xamarin

CalendarView for Xamarin.Android:


Displaying events in the calendar
RadCalendarView can be used to display the events for a single cell, that is currently selected.
There are currently two ways for displaying the events, which are being set by using a single
property of the calendar.

Inline events
In this mode the calendar will crack open below the selected cell and will display the events as a
scrollable list, which will fill the entire width of the calendar. The height will be determined by the
height and the number of events, that need to be displayed. It will however be limited to the height of
4 calendar rows.

C#
calendarView.EventsDisplayMode = EventsDisplayMode.Inline;
 

and the result:

1800
Telerik UI for Xamarin

Popup events
In this mode the events will be displayed as a popup window, which will load at most four of the cell's
events inside a list view and will take place at the lower part of the cell's location.

C#
calendarView.EventsDisplayMode = EventsDisplayMode.Popup;
 

and the result:

1801
Telerik UI for Xamarin

Please note that both modes are only available when using Single selection mode. An exception will
be thrown otherwise.
 
In both modes it is valid that all scrolling will be disabled and only selections will be permitted. Once
the events are no longer displayed the calendar will restore its original behaviour.Switching to year
display mode is possible, but the events will be closed first, and then the switching will perform.

Displaying Events Programmatically


EventsManager class exposes the following methods for

programmatically show or hide events for a specific date/cell by using the following two methods:

 ToggleEventsVisibilityForDate(long date)
 ToggleEventsVisibilityForCell(CalendarCell cell)

additionally check if events are shown for a specific date/cell by using the
following methods:

1802
Telerik UI for Xamarin

 EventsForDateVisible(long date)
 EventsForCellVisible(CalendarCell cell)

Customizing the display of the events for Popup and Inline


Modes
Customization is being done using the calendar Adapter for both modes. The properties for the two
modes are different and are as follows:

 PopupEventsWindowBackgroundColor - the background color for the events popup


window;
 InlineEventsBackgroundColor - the background color for the inline events;
 PopupEventTitleTextSize - the text size for the event title in popup mode;
 PopupEventTimeTextSize - the text size for the event time in popup mode;
 InlineEventTitleTextSize - the text size for the event title in inline mode;
 InlineEventTimeStartTextSize - the text size for the event start time in inline mode;
 InlineEventTimeEndTextSize - the text size for the event end time in inline mode;
 InlineEventTimeStartTextColor - the text color for the event start time in inline mode;
 InlineEventTimeEndTextColor - the text color for the event end time in inline mode;

Example:
C#
calendarView.Adapter.PopupEventsWindowBackgroundColor = Color.Black;
calendarView.Adapter.PopupEventTitleTextSize = 22.0F;
calendarView.Adapter.PopupEventTimeTextSize = 14.0F;
 

If this is not enough, you can further customize the events by setting a new adapter which extends
ArrayAdapter for the inline events. Here's an example which shows how to use a single view to show
both start and end time of an event:

C#
public class MyInlineEventsAdapter : ArrayAdapter
{
private LayoutInflater layoutInflater;

public MyInlineEventsAdapter(Context context)


: base(context, Resource.Layout.custom_inline_event_layout)
{
this.layoutInflater = LayoutInflater.From(context);
}

public override View GetView(int position, View convertView, ViewGroup parent)


{
View view = convertView;
ViewHolder holder;

if (view == null)

1803
Telerik UI for Xamarin

{
view = layoutInflater.Inflate(
Resource.Layout.custom_inline_event_layout, parent, false);

holder = new ViewHolder();


holder.eventTitle = (TextView)view.FindViewById(Resource.Id.event_title);
holder.eventTime = (TextView)view.FindViewById(Resource.Id.event_time);

view.Tag = holder;
}
else {
holder = (ViewHolder)view.Tag;
}

EventsManager.EventInfo eventInfo = (EventsManager.EventInfo)GetItem(position);


Event event1 = eventInfo.OriginalEvent();
holder.eventTitle.SetTextColor(new Color(event1.EventColor));
holder.eventTitle.Text = event1.Title;
String eventTime = String.Format("{0} - {1}",
eventInfo.StartTimeFormatted(), eventInfo.EndTimeFormatted());
holder.eventTime.Text = eventTime;

return view;
}

class ViewHolder : Java.Lang.Object


{
public TextView eventTitle;
public TextView eventTime;
}
}
 

This example is using a resource file with the following content:

XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="12dp">

<TextView
android:id="@+id/event_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minEms="4"
android:textSize="12sp"
android:padding="12dp"/>

<TextView
android:id="@+id/event_title"
android:layout_width="match_parent"

1804
Telerik UI for Xamarin

android:layout_height="wrap_content"
android:layout_marginStart="12dp"
android:layout_marginLeft="12dp"
android:layout_marginEnd="12dp"
android:layout_marginRight="12dp"
android:textSize="18sp" />

</LinearLayout>
 

You can use an instance of the new adapter and set it to your calendar's event manager:

C#
MyInlineEventsAdapter adapter = new MyInlineEventsAdapter(Context);
calendarView.EventsManager().Adapter = adapter;
 

Please note that the event manager exists only when the calendar's EventDisplayMode is Inline or
Popup.
 

Handling event clicks


If you need to display additional information about events, you can listen for item clicks. Here's an
example to show a toast that an event is clicked:

C#
calendarView.EventsManager ().SetOnItemClickListener (new MyClickListener());

public class MyClickListener : Java.Lang.Object, AdapterView.IOnItemClickListener {


public void OnItemClick (AdapterView parent, View view, int position, long id)
{
Toast.MakeText (parent.Context, (((ArrayAdapter)((ListView)parent).Adapter)).
GetItem(position).ToString(), ToastLength.Short).Show ();
}
}
 

1805
Telerik UI for Xamarin

CalendarView for Xamarin.Android:


Reading events from other calendars
RadCalendarView can be set up to read and display the events from other calendars on the device.
The process is managed by the EventReadAdapter which is responsible for connecting to the
calendar content provider and reading the requested events.There is no need for the developer to
bother using any SQL queries since the default scenarios are provided out of the box. It is however
possible for the queries to be fully customized as needed.

Setting the read adapter


The read adapter is rather easy to be set in the default scenario. All that has to be done is to set an
instance of the adapter to the calendar and to trigger the reading of events like this:

C#
EventReadAdapter eventAdapter = new EventReadAdapter (calendarView);
calendarView.EventAdapter = eventAdapter;
eventAdapter.ReadEventsAsync();
 

Please note that since API 23, you need to ensure that your app has the proper permission before
attempting to read events. In other words, before calling the ReadEventsAsync method, ensure that
you haveREAD_CALENDAR permission as shown here.
 
This will get the events from the calendar with id 1, or the first calendar on the device. This will not
be always the desired result, since the first calendar might not be the one that the developer needs.

Setting the query options


The events are being collected by the read adapter using queries. By changing the queries the
developer can determine the set of events, that will be red and displayed in the calendar. There is a
set of basic queries,that will cover most scenarios. Here is an example for getting the events from
today to a week from today for the first three calendars on the device:

C#
EventQueryToken token = EventQueryToken.GetCalendarsById(new String[]{"1", "2", "3"});
Calendar calendar = Calendar.Instance;
long start = calendar.TimeInMillis;
calendar.Add(CalendarField.Date, 7);
long end = calendar.TimeInMillis;
token.SetRange(start, end);

eventAdapter.EventsQueryToken = token;
 

Here is how to get all calendars belonging to a specific user using the provided helper methods:

1806
Telerik UI for Xamarin

C#
public override View OnCreateView (LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
RadCalendarView calendarView = new RadCalendarView(Activity);
this.eventAdapter = new EventReadAdapter(calendarView);
calendarView.EventAdapter = eventAdapter;

EventReadAdapter.GetCurrentUserAsync(Activity, new CustomAsyncCallback


(this.eventAdapter));

return calendarView;
}

private class CustomAsyncCallback : Java.Lang.Object, IAsyncCallback


{
EventReadAdapter adapter;

public CustomAsyncCallback(EventReadAdapter adapter)


{
this.adapter = adapter;
}

public void OnResult(Java.Lang.Object result)


{
EventQueryToken token = EventQueryToken.GetCalendarsByOwner
(result.ToString());
this.adapter.EventsQueryToken = token;
this.adapter.ReadEventsAsync();
}
}
 

Please note that since API 23, you need to ensure that your app has the proper permission before
attempting to read events. In other words, before calling the GetCurrentUserAsync method, ensure
that you haveGET_ACCOUNTS permission as shown here.
 
However since there is no standard on the order or the owners of calendars there are some
scenarios where the developer must decide what to do with the available calendars manually. There
are devices of which the first calendar (with id of 1) is the Outlook calendar and others where there is
only one user, which doesn't own the calendar of the device, but the owner is rather something like
"Phone".

In these cases there can be a more controlled selection of events as presented in this example:

C#
EventReadAdapter eventAdapter;

public override View OnCreateView (LayoutInflater inflater, ViewGroup container,


Bundle savedInstanceState)
{
RadCalendarView calendarView = new RadCalendarView(Activity);

1807
Telerik UI for Xamarin

this.eventAdapter = new EventReadAdapter(calendarView);


calendarView.EventAdapter = eventAdapter;

EventReadAdapter.GetAllCalendarsAsync(Activity, new
CustomAsyncCallback(this.eventAdapter));

return calendarView;
}

private class CustomAsyncCallback : Java.Lang.Object, IAsyncCallback {


EventReadAdapter adapter;

public CustomAsyncCallback(EventReadAdapter adapter)


{
this.adapter = adapter;
}

public void OnResult(Java.Lang.Object result)


{
List<String> calendarsFromResult = new List<String>();
EventReadAdapter.CalendarInfo[] calendars =
result.ToArray<EventReadAdapter.CalendarInfo>();

for (int i = 0; i < calendars.Length; i++) {


if (true) // add custom logic here
{
calendarsFromResult.Add(calendars[i].Id);
}
}

String[] selectedCalendars = calendarsFromResult.ToArray();

EventQueryToken token = EventQueryToken.GetCalendarsById(selectedCalendars);


this.adapter.EventsQueryToken = token;
this.adapter.ReadEventsAsync();
}
}
 

In any case the events are being red after the method for asynchronous reading is being invoked.
This will automatically refresh the calendar once the events are loaded.

Please note that you must set everything before calling the method for reading the events
asynchronously.
 

Recurring events
The recurring events are also available for reading and displaying in the RadCalendarView, however
the rules are not complete and will be updated with the following releases of the calendar. The
recurring events can be stopped or enabled using the setReadingRecurringEvents(boolean) method
of the adapter. The functionality can be easily extended by providing manual implementation over

1808
Telerik UI for Xamarin

the existing one like this:

C#
public class CustomEventReadAdapter : EventReadAdapter
{
public CustomEventReadAdapter(RadCalendarView owner) : base (owner){}

protected override bool EventShouldRecur (RecurringEvent recurringEvent, long


date)
{
// Add custom logic here...
return base.EventShouldRecur (recurringEvent, date);
}
}
 

The RecurringEvent class is simply a data holder of all the tokens stored in a RRULE according to
the iCalendar specification. It is used for judging the recurrence of the events red from the other
calendars.It holds all the fields needed to store the elements of the RRULE:

 ByDayModifier(int day) - returns the modifier if such exists for the passed day like in -1SA,
where SA is the day and -1 is the modifier.
 int[] BySecond() holds a collection of seconds for the BYSECOND token.
 int[] ByMinute() holds a collection of minutes for the BYMINUTE token.
 int[] ByHour() holds a collection of hours for the BYHOUR token.
 int[] ByMonthDay() holds a collection of month days for the BYMONTHDAY token.
 int[] ByYearDay() holds a collection of year days for the BYYEARDAY token.
 int[] ByWeekNo() holds a collection of week numbers for the BYWEEKNO token.
 String Rule() holds the whole RRULE in its original form.
 boolean ByDay(int day) checks if the passed day is present in the BYDAY token.
 boolean ByMonth(int month) checks if the passed month is present in the BYMONTH token.
 long RepeatUntilDate() holds the date until the event can repeat according to the UNTIL
token.
 int Count() holds the count according to the COUNT token.
 int WeekStartDay() holds the week start day according to the WKST token.
 int Interval() holds the interval according to the INTERVAL token.
 boolean IsBySecond states whether BYSECOND token is present.
 boolean IsByMinute states whether BYMINUTE token is present.
 boolean IsByHour states whether BYHOUR token is present.
 boolean IsByMonthDay states whether BYMONTHDAY token is present.
 boolean IsByYearDay states whether BYYEARDAY token is present.
 boolean IsByWeekNo states whether BYWEEKNO token is present.
 boolean IsBySetPos states whether BYSETPOS token is present.
 boolean IsByDay states whether BYDAY token is present.
 boolean IsByMonth states whether BYMONTH token is present.
 boolean IsModified states whether the BYDAY had a modified value (-1SA) or the
BYSETPOS is present.
 boolean IsByDayModified states whether the BYDAY had a modified value (-1SA).
 Frequency Frequency() holds the frequency according to the FREQ token.
 int[] BySetPos() holds the positions according to the BYSETPOS token.

1809
Telerik UI for Xamarin

CalendarView for Xamarin.Android: Customizations


RadCalendarView provides various ways to alter its look. It allows you to define dates which use
special visuals, additional decorations and coloring, etc. Another customization option is todefine
which of its elements should be visible and even alter their appearance.

Special Dates
The special dates are these dates which require special decoration to mark something important, for
example birthdays or holidays. You can perform a set of rules that should be applied for a cell or
simply define the color that should be used for the text of a date depending on its value.

Defining set of cell styles


You can define styles that are applied to all cells that meet a certain critiria. For example style which
is applied for cells that contain a date or cells that contain weekend dates (Saturday and Sunday) or
cells that contain today, etc. Using this approach you can customize borders, background, text, etc.

Here are the methods for the CalendarDayCellFilter which allow you to filter the cells that use a
certain style:

 CellType - to apply style to dates, dayNames, weekNumbers or titles; default is Date


 IsSelected - to apply style only to cells which are selected
 IsFromCurrentMonth - to apply style only to cells from the current month and not to the
visible cells from the previous and the next months
 IsToday - to apply the style only to the today cell
 IsWeekend - to apply the style only to cells used to display Saturdays and Sundays
 Custom - if none of the above works for you, you can add a custom function which based on
a passed cell, returns true or false, depending on whether the cell should be customized.

And here's what you can customize with a CalendarDayCellStyle:

 BorderColor
 BorderWidth
 BackgroundColor
 TextColor
 TextSize
 FontStyle - must be one of: Typeface.NORMAL, Typeface.BOLD, Typeface.ITALIC,
Typeface.BOLD_ITALIC
 FontName - must be one of: sans-serif, sans-serif-light, sans-serif-condensed,
sans-serif-thin, sans-serif-medium
 PaddingHorizontal
 PaddingVertical
 TextPosition - must be one of or a combination of: CalendarElement.AlignTop,
CalendarElement.AlignBottom, CalendarElement.Center, CalendarElement.AlignLeft,
CalendarElement.AlignRight, CalendarElement.CenterHorizontal,
CalendarElement.CenterVertical

1810
Telerik UI for Xamarin

Here's an example that changes the text color for weekends to RED and the border for today to
GREEN, 4 dps wide:

C#
CalendarDayCellFilter weekendCellFilter = new CalendarDayCellFilter();
weekendCellFilter.IsWeekend = new Java.Lang.Boolean(true);
CalendarDayCellStyle weekendCellStyle = new CalendarDayCellStyle();
weekendCellStyle.Filter = weekendCellFilter;
weekendCellStyle.TextColor = new Java.Lang.Integer(Color.Red.ToArgb());
calendarView.AddDayCellStyle(weekendCellStyle);

CalendarDayCellFilter todayCellFilter = new CalendarDayCellFilter();


todayCellFilter.IsToday = new Java.Lang.Boolean(true);
CalendarDayCellStyle todayCellStyle = new CalendarDayCellStyle();
todayCellStyle.Filter = todayCellFilter;
todayCellStyle.BorderColor = new Java.Lang.Integer(Color.Green.ToArgb());
float widthInDp = 4;
float widthInPixels = (int) TypedValue.ApplyDimension(ComplexUnitType.Dip,
widthInDp, Resources.DisplayMetrics);
todayCellStyle.BorderWidth = new Java.Lang.Float(widthInPixels);
calendarView.AddDayCellStyle(todayCellStyle);
 

And this is the result:

1811
Telerik UI for Xamarin

Similarly, you can use CalendarMonthCellStyle and CalendarMonthCellFilter to apply styles for the
month cells that are used while calendar is is Year mode.

While the styles for the month cells are very similar to the day cell style, the filtering differs in order to
allow you to change color, size and/or fonts for a specific text inside the month cell. Here are the
filtering options for CalendarMonthCellFilter:

 TextIsDate - to apply the style only to the text of the dates


 TextIsDayName - to apply the style only to the text of the day names
 TextIsMonthName - to apply the style only to the text of the month names
 TextIsToday - to apply the style only to the text of the date that is today
 TextIsWeekend - to apply the style only to the text of the weekends (saturday and sunday)
 MonthIsCurrent - to apply the style only to the cell that holds the current month
 MonthIsCompact - to apply special style to cells when year mode of the calendar is compact
 MonthIsCustomDate - in none of the above fits your needs, you can add a custom function
so that based on the value of the month returns true or false to determine whether the style
should be applied
 TextIsCustomDate - similar to the previous but can be used for the text of specific dates

Here's an example that changes the text color of the month names for all month cells to BLUE:

1812
Telerik UI for Xamarin

C#
CalendarMonthCellFilter monthCellTitleFilter = new CalendarMonthCellFilter();
monthCellTitleFilter.TextIsMonthName = new Java.Lang.Boolean(true);
CalendarMonthCellStyle monthCellTitleStyle = new CalendarMonthCellStyle();
monthCellTitleStyle.Filter = monthCellTitleFilter;
monthCellTitleStyle.TextColor = new Java.Lang.Integer(Color.Blue.ToArgb());
calendarView.AddMonthCellStyle(monthCellTitleStyle);
 

And this is the result:

Please note that the more styles you add, the more checks before rendering each date will be
performed to determine whether this date meets the style's filter, so you should use these styles
sparingly.
 

Defining set of customization rules


You can define a customization rule which contains a list of operations that should be performed on
a calendar cell if it meets certain requirements and apply it to the calendarthrough the method
CustomizationRule(Procedure). For example, if we want to mark a specific important date with
custom background,here's how we can do it:

C#
Calendar calendar = Calendar.GetInstance(Java.Util.TimeZone.Default);
calendarView.CustomizationRule = new CustomizationRuleExample ();
// ...

class CustomizationRuleExample : Java.Lang.Object, IProcedure


{
private Java.Util.Calendar calendar = Java.Util.Calendar.Instance;
public void Apply (Java.Lang.Object p0)

1813
Telerik UI for Xamarin

{
CalendarCell calendarCell = p0.JavaCast<CalendarCell>();
if (calendarCell.CellType != CalendarCellType.Date) {
return;
}
calendar.TimeInMillis = calendarCell.Date;
if (calendar.Get (Java.Util.CalendarField.DayOfMonth) == 21 &&
calendar.Get (Java.Util.CalendarField.Month) ==
Java.Util.Calendar.Instance.Get(Java.Util.CalendarField.Month))
{
calendarCell.SetBackgroundColor (
Android.Graphics.Color.ParseColor("#FF00A1"),
Android.Graphics.Color.ParseColor("#F988CF"));
}
}
}
 

This example changes the background of the cell which contains the 21st day of the current month:

1814
Telerik UI for Xamarin

Changing the color of a date


If the required change for marking a cell as special is simply changing the text color you can use the
method DateToColor(Function) to define a color that is used for a date. Here's an example, which
marksall Sundays in Red:

C#
Calendar calendar = Calendar.GetInstance(Java.Util.TimeZone.Default);
calendarView.DateToColor = new DateToColorExample ();
// ...

class DateToColorExample : Java.Lang.Object, IFunction


{
private Java.Util.Calendar calendar = Java.Util.Calendar.Instance;

public Java.Lang.Object Apply (Java.Lang.Object timeInMillis)


{
calendar.TimeInMillis = (long)timeInMillis;
if(calendar.Get(CalendarField.DayOfWeek) == Calendar.Sunday) {
return Color.Red.ToArgb();
}
return null;
}
}
 

When the returned value is null the default value is used:

1815
Telerik UI for Xamarin

Editing the visible elements


Title and DayNames
The Week and the Month views of RadCalendarView contain three visual elements: title, a row with
the names of the days and the actual dates from the month. The Year view contains two elements:
title and months.

 disable the title that is presented in all of the modes by using the ShowTitle(boolean)
property
 remove the row with the names of the days which is present in both week and month views
by using ShowDayNames(boolean).
 setting whether the title and the day names are visible. Their names are ShowTitle and
ShowDayNames.

Grid Lines
Another visual element of RadCalendarView is the layer which is responsible for drawing grid lines.
You can easily remove the grid lines by using the method ShowGridLines(boolean).

1816
Telerik UI for Xamarin

The XML attribute which can be used to control whether the grid lines are visible is ShowGridLines.
The default GridLinesLayer provides method for changing the color that is used for the grid lines, as
well as their width. These methods are Color(int) and Width(float).

C#
calendarView.GridLinesLayer.Color = Color.Green;
 

If you are not happy with the default implementation of this layer, you can create your own layer
which extends GridLinesLayer and override its methods.

Cell Decorations
When a cell in RadCalendarView is selected it can get additional decoration. This decoration is
provided by the CellDecorationLayer. The default implementation provides a border around the cells
that are selected.

You can easily remove this decoration by using calendar's ShowCellDecorations(boolean). You can
also easily change the color or the width of the decorations with CellDecorationLayer's setColor(int)
and setStrokeWidth(float).

Here's how you can change the decorations around the selected cells to Green, for example:

C#
calendarView.CellDecorationsLayer.Color = Color.Green;
 

You can see a custom implementation of the decoration layer in our examples solution, which
provides this type of decorations:

Further customizations

1817
Telerik UI for Xamarin

For more sophisticated customizations and scenarios it is recommended to use the calendar
adapter, which can be obtained by using the Adapter property. It provides various customization
features, that can be applied and preserved over the recreation of the calendar.

Customizations applied by using the adapter will be stored in the current calendar style and will not
be lost after calendar recreation, for example when switching between display modes.

1818
Telerik UI for Xamarin

CalendarView for Xamarin.Android: Gestures and


Transitions
RadCalendarView provides different types of transitions which are played when certain gestures are
executed by the user.These gestures can change the display date and display mode of the control.
The other way to play transitions are by using the corresponding methods which force animation
while changing the display date or display mode.

Handled gestures
RadCalendarView has an intuitive gesture handling mechanism, which allows the user to easily
advance to next or previous months (or weeks, or years, depending on the display mode) and
change the display mode to Week or Year.If you want to change the list of handled gestures, you
can use the calendar's GestureManager(of type
Com.Telerik.Widget.Calendar.CalendarGestureManager)property. This manager allows you to
disable the handling of some gestures and enabling others. Here's a list of gestures along with
themanager's methods that you can use to get or set whether these gestures are enabled:

 pinch open to change display mode: when the user pinches open (zooms in) while the
display mode is Year, it is changed to Month —
SetPinchOpenToChangeDisplayMode(boolean) — by default is true

C#
RadCalendarView calendarView = new RadCalendarView (Activity);
calendarView.GestureManager.SetPinchOpenToChangeDisplayMode(false);
 

 pinch close to change display mode: when the user pinches close (zooms out) while the
display mode is Month, it is changed to Year —
SetPinchCloseToChangeDisplayMode(boolean) — by default is true.

C#
RadCalendarView calendarView = new RadCalendarView (Activity);
calendarView.GestureManager.SetPinchCloseToChangeDisplayMode(false);
 

 swipe up to change display mode: when the user swipes up from the bottom of the view
while the display mode is Month, it is changed to Week —
SetSwipeUpToChangeDisplayMode(boolean) — by default is true.

C#
RadCalendarView calendarView = new RadCalendarView (Activity);
calendarView.GestureManager.SetPinchOpenToChangeDisplayMode(false);
 

 swipe down to change display mode: when the user swipes down while the display mode is
Week, it is changed to Month — SetSwipeDownToChangeDisplayMode(boolean) — by

1819
Telerik UI for Xamarin

default is true
 tap to change display mode: when the user taps on a month in the Year view, the display
date is changed to a date from the tapped month and the display mode is changed to Month
— SetTapToChangeDisplayMode(boolean) — by default is false
 double tap to change display mode: when the user double taps on a month in the Year view,
the display date is changed to a date from the tapped month and the display mode is
changed to Month, if the gesture is performed while the calendar is in Month view, it is
changed to Year — SetDoubleTapToChangeDisplayMode(boolean) — by default is true
 drag to make range selection: when the user drags a range selection is performed following
the user's finger. The scrolling will not be processed if the drag selection is active, but it is
recommended that the scrolling is disabled manually as well, by setting it to None. —
SetUsingDragToMakeRangeSelection(boolean) — by default it is false

Scrolling and scroll modes


The calendar is fully suited to be scrolled both horizontally and vertically. It has several different
scroll modes giving the freedom of customizing the scroll experience to the customer's needs. The
calendar has been optimized so that it follows the user's gestures without delay or unwanted
memory performance issues.

The currently provided scroll modes are:

 None - this simply disables the scrolling of the calendar and leaves the developer with the
option to trigger the date changes programmatically. See the next section for more info on
that.
 Plain - in plain mode the calendar will simply follow the scroll gesture without any additional
behaviour.
 Sticky - the calendar will be following the gesture again, but will snap the current month after
the gesture is done.
 Free - in free mode the calendar will follow the user's gesture, but will allow flinging action as
well.
 Combo - this mode combines plain, where the gesture is followed, free, where flinging is
handled and sticky, where the current fragment is being snapped when the gesture is over.
 Overlap - in the overlap mode the calendar behaves as if the next and previous months are
being dragged on top of the current one.
 Stack - in the stack mode, the next dates will be dragged on top of the calendar and going
back to previous dates will 'unstack' the current date from the calendar by bringing it down.
This creates the feeling of a stack.

Example
C#
RadCalendarView calendarView = new RadCalendarView (Activity);
calendarView.ScrollMode = ScrollMode.Sticky;
 

You can use the calendar's properties for setting the direction of the scrolling and the scrolling as
follows:

 setting scrolling direction: the direction is determined by setting the HorizontalScroll(boolean)

1820
Telerik UI for Xamarin

property of the calendar. Passing true will cause the calendar to scroll horizontally while
passing false will result in vertical scrolling — the default setting is false or vertical scrolling.
 setting the scroll mode: the scroll mode is easily set by using the calendar's
setScrollMode(ScrollMode) and passing an enumeration value from the ScrollMode
enumeration — the default scroll mode is set to Sticky.

Example
C#
RadCalendarView calendarView = new RadCalendarView (Activity);
calendarView.HorizontalScroll = true;
 

Please have in mind, that in horizontal scrolling the current date will always be snapped regardless
of the scroll mode. Also when the calendar is in week display mode, the scrolling will always be
horizontal regardless of the settings.
 

Triggering the transitions programmatically


You can use methods provided by RadCalendarView to change the value of the display date or
display mode and apply the corresponding transition. The method
ChangeDisplayMode(CalendarDisplayMode, boolean) can be usedto change the display mode with
transition between the modes. The first parameter is the display mode that needs to be set and the
second parameter specifies whether the transition will be played. Here's an example ofa call which
sets the display mode to Year with animation between the states:

C#
RadCalendarView calendarView = new RadCalendarView (Activity);
calendarView.ChangeDisplayMode(CalendarDisplayMode.Year, true);
 

Similarly you can use the methods AnimateToNext(boolean) and AnimateToPrevious(boolean) to


change the display date with transition. The current value of the display mode will be used for
determination of the new valuefor the display date. For example, if the current display mode is Year,
the new value for display date will be the old with one year added (if animateToNext is used) or
subtracted (if animateToPrevious is used). The booleanparameter allows you to determine the
direction of the transition. If the provided value is true, the transition will be horizontal and otherwise
the transition will be vertical.

1821
Telerik UI for Xamarin

CalendarView for Xamarin.Android:


Localization
By default RadCalendarView uses the current device's locale to initialize the values that are
displayed along with some other calendar specifics like which is the first day of the week. Here's an
example with of the calendarrun on a device where the language is set to English (United States):

Locale
If you want to provide a static locale which disregards the user's preferences, you can use the
calendar's Locale(Locale) property and set the locale of your preference. Here's an example with the
local France:

C#
calendarView.Locale = Java.Util.Locale.France;
 

The result will be that the calendar will display the names of the days and the month in French and
the first day of the week will not be Sunday as with the previous example but Monday:

1822
Telerik UI for Xamarin

Calendar
RadCalendarView displays the dates in accordance with the java.util.GregorianCalendar. If
you would like to use another Calendar implementation you can apply it with calendar's
Calendar(Calendar) property.

1823
Telerik UI for Xamarin

ChartView for Xamarin.Android: Overview


RadChartView for Xamarin.Android is a charting component that has been designed for the mobile
environment. It offers great performance in loading time, drawing capabilities and real-time updates.
Its intuitive object model and public API allow you to easily setup complex chart objects and integrate
them into your application.

The control supports different chart types (and series) organized in hierarchies, depending on the
coordinate system, used to plot the data points—for example Cartesian (RadCartesianChartView)
and radial (RadPieChartView) coordinate systems.

1824
Telerik UI for Xamarin

A charting component in general is used to visualize (or plot) some data in a human-readable way
through different representations like lines, areas, bars, pies, etc. Each series has a collection of
data points—the data equivalent of a 2D point—and knows how to visualize them. Different series
types may process certain types of data points—for example categorical series may contain
categorical data points. An intuitive data binding mechanism transforms the raw data to appropriate
data points depending on the chosen series.

Chart Types
Depending on the coordinate system that you want to use for visualization of the data points, you
can use the following chart types:

 RadCartesianChartView: As the name hints, this concrete chart control uses the Cartesian
coordinate system to plot the data points in its chart series. The X and Y axes define how
each point’s coordinates in the plot area are calculated.
 RadPieChartView: This concrete chart control visualizes its data points using radial
coordinate system. Each data point is represented as a slice from a pie. The ratio between
the space consumed by each slice and the space consumed by the whole chart is the same
as the ratio between the value of the data point that it represents and the total value of all
data points in the series.

RadCartesianChartView
If you choose the Cartesian chart, you need to specify the type of each of the axes—horizontal and
vertical—and the type of the series. Depending on the type of the series, you will need to choose
axes that can visualize category or value (usually one axis to visualize the category and one to
visualize value).

Axes that can visualize category

 CategoricalAxis: Arranges the plotted data points in categories where the key of each
category is the point's value (if available) for that axis or its index within the points collection.
The point's coordinate, specified by this axis is discrete and is calculated depending on the
size of the category slot where the point resides.
 DateTimeCategoricalAxis: This is a special categorical axis that expects each data point to
provide a java.util.Calendar structure as its value for this axis. The points are grouped
by a user-defined date-time component (Year, Month, Day, etc.) and then the groups are
sorted chronologically.
 DateTimeContinuousAxis: This is a special axis that expects each data point to provide a
java.util.Calendar structure as its value for this axis. You can think of
DateTimeContinuousAxis as a timeline where the coordinate of each data point is calculated
depending on the position of its associated DateTime on the timeline. The base unit (or the
timeline step) of the axis is calculated depending on the smallest difference between any two
dates.

Axes that can visualize value

 LinearAxis: Calculates the coordinate of each data point, depending on the actual numerical
value this point provides for the axis. A LinearAxis exposes Minimum and Maximum
properties to allow for explicit definition of the range of values visible on this axis. If these

1825
Telerik UI for Xamarin

properties are not specified, the axis will automatically calculate the range, depending on the
minimum and maximum data point values.
 LogarithmicAxis: Special linear axis that will transform each data point value using the
logarithm function. Using LogarithmicAxis allows your app to show numerical data with huge
delta between the minimum and the maximum to be visualized in a readable way.

Series supported by RadCartesianChartView

 LineSeries: Visualizes a collection of data points using a Line.


 SplineSeries: Visualizes a collection of data points using a Curve.
 AreaSeries: Represents a chart series that are visualized like an area figure in the Cartesian
space.
 SplineAreaSeries: Represents series which define an area with smooth curves among points.
 BarSeries: Represents a chart series that plot their points using rectangular shapes, named
"Bars". RadCartesianChartView can display BarSeries both horizontally and vertically. If the
series are more than one, they can be stacked.
 RangeBarSeries: Represents a chart range bar series. Both BarSeries and RangeBarSeries
display its data points as bars. However the bars in BarSeries represent just a single value
and the bars in RangeBarSeries represent low value and high value.

RadPieChartView
The Pie chart doesn't have any axes. You just need to define the series that will contain the data.
This chart supports these types of series:

 PieSeries: The PieSeries are used to visualize a single series of data in a pie chart. The
sweep of a pie's slices is directly proportional to the magnitude of the data points' values.
 DoughnutSeries: The DoughnutSeries are similar to the PieSeries with the difference that the
data points are visualized in doughnut segments.

Behaviors
Each chart can support different behaviors, which allow a certain interactivity. A behavior is generally
an abstraction that handles user input in a RadChartView instance and optionally provides visual
feedback upon some action. Currently RadChartView supports the following behavior:

 PanAndZoomBehavior: This behavior handles touch events to enable panning and zooming
of the associated chart plot area.
 TrackballBehavior: This behavior is responsible for rendering concise information about
several data points in a small popup which displays over its relevant data points. A vertical
line is also drawn through the data points for maximum clarity.
 TooltipBehavior: This behavior is used for rendering concise information about a data point in
a small popup.
 ChartSelectionBehavior: Handles selecting and deselecting of either data points or series.

Grid
RadChartView allows custom decoration over its plot area. You can add lines and stripes which
connect the ticks of each axis. You can create a new CartesianChartGrid and set it to the Grid

1826
Telerik UI for Xamarin

property of your Chart instance. Read the Grid Section for more information.

Palettes
The Chart Palettes are a set of predefined values that you can use to set colors of a chart.
RadChartView gives you options to define your own palettes and to use the ones we have prepared
for you as well: "Light" and "Dark".

Annotations
Another feature of RadChartView is the ability to show annotations. They are visual elements that
can be used to highlight certain areas on the plot area and denote statistical significance. The
provided types of annotations include:

 CartesianGridLine: In the case of the Cartesian chart, the grid line represents a vertical or
horizontal line which crosses the entire plot area.
 CartesianPlotBand: The Cartesian Plot Band annotation is either a horizontal or a vertical
stripe that crosses entirely the vertical or horizontal axis, respectively.
 CartesianCustomAnnotation: This class exposes the functionality of adding user-defined
annotations to the RadCartesianChart.

Labels
RadChartView can display different labels for the series and axes that are displayed. The labels can
be fully customized according to your preferences.

Legend
RadChartView supports a legend that facilitates the reading and understanding of the displayed
information. The legend can be used to easily associate the displayed visualizations with the actual
data.

Xamarin.Android Examples
Xamarin.Android examples that show how to use RadChartView for Xamarin.Android are included in
the Telerik UI for Xamarin zip file provided for manual installation.

Telerik_UI_for_Xamarin_[version]_[license].zip, where [version] marks the release and [license] is


replaced with Dev or Trial depending on the license, is available for download from the Downloads
section of your Telerik account. Unzip the archive and go to Examples/Android folder to access our
Samples Xamarin.Android solution.

1827
Telerik UI for Xamarin

ChartView for Xamarin.Android: Getting Started


In this article, you will learn how to get started with RadChartView for Xamarin.Android: how to
initialize the chart, how to create the data series, how to use the different axes and how to create a
chart that looks like this:

Chart Initialization
The easiest way to add an instance of RadChartView is to find the root view by id and add the chart
as a child view, for example in the method onCreate() of your Activity. Here's how to add a Cartesian
chart, to the root view (with id container):

1828
Telerik UI for Xamarin

C#
RadCartesianChartView chartView = new RadCartesianChartView(this);

ViewGroup rootView = (ViewGroup)FindViewById(Resource.Id.container);


rootView.AddView(chartView);
 

At this point that chart will be added to the view, but it will simply indicate that there is no data and no
axes defined.

Adding Data
Let's create a method that will initialize some data items:

C#
private Java.Util.ArrayList monthResults;

private void InitData() {


monthResults = new Java.Util.ArrayList();
monthResults.Add(new MonthResult("Jan", 12));
monthResults.Add(new MonthResult("Feb", 5));
monthResults.Add(new MonthResult("Mar", 10));
monthResults.Add(new MonthResult("Apr", 7));
}
 

Here, MonthResult is a custom type that we have defined as follows. Additionally, in C#, you will
need a class that inherits from DataPointBinding that will be used for the proper data retrieval:

C#
public class MonthResult : Java.Lang.Object {

public string Month { get; set; }


public double Result { get; set; }

public MonthResult(string month, double result) {


this.Month = month;
this.Result = result;
}
}

class MonthResultDataBinding : DataPointBinding {

private string propertyName;

public MonthResultDataBinding(string propertyName)


{
this.propertyName = propertyName;
}

public override Java.Lang.Object GetValue (Java.Lang.Object p0)

1829
Telerik UI for Xamarin

{
if(propertyName == "Month")
{
return ((MonthResult)(p0)).Month;
}
return ((MonthResult)(p0)).Result;
}
}
 

Now that we have the data, we need to add it to a series instance.

Creating Series
For this example we will create a chart with LineSeries. After we create the series, we need to define
data point bindings for both value and category, which will determine how this information will be
extracted from each of the data items.

C#
InitData();

LineSeries lineSeries = new LineSeries();


lineSeries.CategoryBinding = new MonthResultDataBinding ("Month");
lineSeries.ValueBinding = new MonthResultDataBinding ("Result");
lineSeries.Data = (Java.Lang.IIterable)this.monthResults;
chartView.Series.Add(lineSeries);
 

All that's left is to define what will be type of the axes. For the LineSeries, we will need one axis that
can visualize category and one that can visualize value.

Creating Axes
In this example, we will use one CategoricalAxis and one LinearAxis.

C#
CategoricalAxis horizontalAxis = new CategoricalAxis();
chartView.HorizontalAxis = horizontalAxis;

LinearAxis verticalAxis = new LinearAxis();


chartView.VerticalAxis = verticalAxis;
 

And that's all now when you run the application, you will see an instance of RadCartesianChart with
one CategoricalAxis and one LinearAxis that visualizes LineSeries and looks like the image from the
beginning of the article.

1830
Telerik UI for Xamarin

ChartView for Xamarin.Android: Visual Structure


In this article, you will learn which are the visual elements and terms used in RadChartView for
Xamarin.Android.

Visual Structure

Legend
 PlotArea: The area that contains the data series (on the image it is the area inside the
rectangle defined by the axes).
 Series: The visual representation of the data.
 SeriesLabel: Labels that provide specific information about the data points in the series.
 VerticalAxis/HorizontalAxis: Axes that define the coordinate system used to plot the data.
 Tick: Marks specific values on the axes.
 AxisLabel: Labels for specific values on the axes.
 ChartGrid: Grid lines that mark specific values on the chart area.

1831
Telerik UI for Xamarin

ChartView for Xamarin.Android: Grid


In this article, you will learn how to display the grid lines in RadChartView for Xamarin.Android.

CartesianChartGrid
The CartesianChartGrid represents a decoration over the plot area of RadCartesianChartView. Adds
major and minor lines, connected to each Major and Minor tick of each axis. You can set a new grid
by setting Grid property of your Chart instance.

Example
Here's an example of grid lines on the Y-axis (actually horizontal lines) in a chart with bar series:

1832
Telerik UI for Xamarin

In order to create such a chart you can start from the Bar Series Example and add the following code:

C#
CartesianChartGrid grid = new CartesianChartGrid();
grid.MajorYLinesRenderMode = GridLineRenderMode.InnerAndLast;
grid.LineThickness = 1;
grid.LineColor = Color.White;
grid.MajorLinesVisibility = GridLineVisibility.Y;
grid.StripLinesVisibility = GridLineVisibility.Y;
ObservableCollection yBrushes = grid.YStripeBrushes;
yBrushes.Clear();
chartView.Grid = grid;
 

1833
Telerik UI for Xamarin

Let's check in more details the provided API related to CartesianChartGrid;

 MajorYLinesRenderMode property allows you to define which of the lines on the Y-axis will
be drawn. You can choose from GridLineRenderMode.First,
GridLineRenderMode.Inner, GridLineRenderMode.Last options and their
combinations. MajorXLinesRenderMode property can be used in a similar way for the vertical
lines.
 LineThickness is used to change the thickness of the grid lines.
 LineColor is used to change the color of the grid lines.
 MajorLinesVisibility and StripLinesVisibility allow you to specify the visibility of the lines and
the stripes, where stripe is the segment between two lines. The possible values for both
properties are GridLineVisibility.X, GridLineVisibility.Y,
GridLineVisibility.None, GridLineVisibility.Xy, which respectively set the display
mode to: vertical lines, horizontal lines, no lines and lines in both directions.
 You can use the YStripeBrushes property to access the collection of paint objects used to
draw the stripes. You can clear the collection and/or add custom Paint objects. You can use
XStripeBrushes in a similar way for the vertical stripes.

1834
Telerik UI for Xamarin

ChartView for Xamarin.Android: Palettes


In this article you will learn to use the predefined palettes in RadChartView for Xamarin.Android and
also how to create custom palettes.

Default Palette
In order to provide the default styles for its series, RadChartView uses palettes. Each palette defines
a set of styles for the different series and axes types. Here's a demonstration for some of the colors
which are provided by the default palette:

Creating Custom Palettes


All chart objects (RadPieChartView and RadCartesianChartView) have a Palette property which
allows you to apply a new palette that you have defined.

Here's an example of setting a custom palette to an instance of RadCartesianChartView.

Let's start with the chart created in the Bar Series example:

C#
// Use a copy of the existing palette in order to avoid redefining the whole palette.
// We are only interested in changing the color of the bar series.
ChartPalette customPalette = chartView.Palette.ClonePalette();

1835
Telerik UI for Xamarin

// Get the entry for the first bar series.


PaletteEntry barEntry = customPalette.GetEntry(ChartPalette.BarFamily);
barEntry.Fill = Color.Green;

// Also if there are more than one bar series we can get the entry for any of them
with their index in the collection.
// Edit the entry for the second bar series.
barEntry = customPalette.GetEntry(ChartPalette.BarFamily, 1);
barEntry.Fill = Color.Cyan;

chartView.Palette = customPalette;
 

Here is the result:

It is important to note that the chart palette will override all settings set manually by the developer. To
prevent the chart palette from overriding the manual settings, developers must set the
chartElement.CanApplyPalette to False. This prevents the palette from being applied to the given
chart element (axis, series etc.) and the developer can take full control over the visual customization.
 

Custom Palette Family


Finally, developers can take advantage of custom palette families. Each chart element (axis, series,
etc.) has a PaletteFamily property that can be used to set a custom family. This is useful when we

1836
Telerik UI for Xamarin

want to style different elements in the same way.

For example in a scenario where we have multiple axes, each series can be paired with its relevant
axis by using the same color. To apply the fill or stroke to both the axis and the series developers
must call series.PaletteFamily = "CustomFamily" and axis.PaletteFamily = "CustomFamily".

1837
Telerik UI for Xamarin

ChartView for Xamarin.Android: Annotations


In this article, you will learn to use the annotations feature in RadChartView for Xamarin.Android and
also how to create custom annotations.

Overview
Annotations are visual elements used to highlight certain areas on the plot. They can be used as
comments or as markers for specific values on the plot. You can practically use any visual element
as template for the annotation.

RadChartView provides support for the following types of annotations:

 GridLineAnnotations: this annotation is visually represented by straight lines across the chart
that marks a specific value on the associated Cartesian axis.
 PlotBandAnnotations: this annotation is visually represented by a band across the chart that
marks a specific range on the associated Cartesian axis.
 CustomAnnotations: this annotation marks a specific point on the Cartesian chart. It requires
both horizontal and vertical coordinates to be specified.

You can read from the Bar Series page how to create a simple chart with BarSeries which we will
now extend to include annotations.

Grid Line Annotations


The GridLineAnnotation represents a vertical or horizontal line that crosses the entire plot area.

Here is an example that demonstrates how to define a vertical CartesianGridLineAnnotation in the


chart that we have created. In the constructor of the annotation you need to specify the axis that will
be annotated and the value which determines the position.

C#
CartesianGridLineAnnotation annotation = new CartesianGridLineAnnotation(verticalAxis,
8);

chartView.Annotations.Add(annotation);
annotation.StrokeColor = Color.Green;
annotation.StrokeWidth = 4;
 

Here's the result:

1838
Telerik UI for Xamarin

You can modify the width and the color of the annotation with the StrokeWidth and StrokeColor
properties of the annotation as shown in the example.

Optionally you can also provide a PathEffect that will be used for the line that is drawn by using
the StrokeEffect property. For example if you want to have a dashed line, instead of solid, you can
use the following approach:

C#
annotation.StrokeEffect = new DashPathEffect (new float[] { 20, 10 }, 0);
 

Plot Band Annotations

1839
Telerik UI for Xamarin

The PlotBandAnnotation represents a vertical or horizontal area that crosses the entire plot area.

Here is an example that demonstrates how to define a vertical CartesianPlotBandAnnotation in the


chart that we have created. In the constructor of the annotation you need to specify the axis that will
be annotated and the two values that will determine the range for the annotation.

C#
CartesianPlotBandAnnotation annotation = new CartesianPlotBandAnnotation(verticalAxis,
6, 8);

chartView.Annotations.Add(annotation);
annotation.FillColor = Color.Green;
annotation.StrokeColor = Color.Cyan;
annotation.StrokeWidth = 4;
 

Here's the result:

1840
Telerik UI for Xamarin

You can modify the fill of the annotation as well as the width and the color of its stroke with the
methods FillColor, StrokeWidth and StrokeColor properties as shown in the example.

Additionally, you can also provide a PathEffect that will be used for the line that is drawn by using the
StrokeEffect property.

Custom Annotations
The CustomAnnotation provides a way to draw custom annotations. In the constructor of the
annotation you need to specify both vertical and horizontal axes as well as values for both of them.
They will be used to determine the position for the annotation.

1841
Telerik UI for Xamarin

Here's the constructor for CartesianCustomAnnotation to better prepare you for using it.

csharp
//API Reference
public CartesianCustomAnnotation(
CartesianAxis p0, // Vertical Axis
CartesianAxis p1, // Horizontal Axis
Java.Lang.Object p2, // Annotation vertical axis value
Java.Lang.Object p3, // Annotation horizontal axis value
Java.Lang.Object p4 // Annotation content value
)
 

When the axis is numerical (Linear or Logarithmic) a numeric value is expected, and when it is
categorical - a category is expected.

You also need to set the content for the annotation, which can be text or something more complex
like a Bitmap. Let's explore both of those possibilities.

Custom Text Annotation


Here's an example which adds a text annotation to a specific position in the chart that we have
created.

C#
var annotationValue = 6;
var annotationCategory = "Feb";
var annotationContent = "TARGET";

var annotation = new CartesianCustomAnnotation(


verticalAxis,
horizontalAxis,
annotationValue,
annotationCategory,
annotationContent);

chartView.Annotations.Add(annotation);
 

Now the annotation will be the text TARGET and it will be drawn where the vertical axis has value 6
and the horizontal axis has value Feb. Additionally, you can provide a custom renderer for the
annotation with the property ContentRenderer. The custom renderer must implement the interface
CustomAnnotationRenderer.

Here is an example for such a renderer which draws a text annotation with custom style:

csharp
using Android.Graphics;
using Com.Telerik.Android.Common.Math;
using Com.Telerik.Widget.Chart.Engine.Decorations.Annotations.Custom;

1842
Telerik UI for Xamarin

public class CustomTextRenderer : Java.Lang.Object, ICustomAnnotationRenderer


{
private readonly Paint contentPaint = new Paint();

public CustomTextRenderer()
{
contentPaint.TextSize = 36;
contentPaint.Color = Color.Red;
contentPaint.SetTypeface(Typeface.Create("sans-serif-light",
TypefaceStyle.Normal));
}

public RadSize MeasureContent(Java.Lang.Object content)


{
if (content == null)
{
return RadSize.Empty;
}

var text = content.ToString();


var textBounds = new Rect();

contentPaint.GetTextBounds(text, 0, text.Length, textBounds);

return new RadSize(textBounds.Width(), textBounds.Height());


}

public void Render(


Java.Lang.Object content,
RadRect layoutSlot,
Canvas canvas,
Paint paint)
{

if (content == null)
{
return;
}

var text = content.ToString();

canvas.DrawText(
text,
(float)layoutSlot.GetX() - (float)(layoutSlot.Width / 2.0),
(float)layoutSlot.Bottom - (float)layoutSlot.Height / 2,
contentPaint);
}
}
 

Now, use a new instance of the CustomTextRenderer with the CartesianCustomAnnotation


ContentRenderer property.

1843
Telerik UI for Xamarin

C#
var annotationValue = 6;
var annotationCategory = "Feb";
var annotationContent = "TARGET";

var annotation = new CartesianCustomAnnotation(


verticalAxis,
horizontalAxis,
annotationValue,
annotationCategory,
annotationContent);

// Now you can set the ContentRenderer to a new instance of the custom text renderer
annotation.ContentRenderer = new CustomTextRenderer();

chartView.Annotations.Add(annotation);
 

Here's the result:

1844
Telerik UI for Xamarin

Custom Image Annotation


You can use the same code we just used for the Text annotation. However, this time we'll use a
Bitmap instead of a string for the content.

csharp
using Android.Graphics;
using Com.Telerik.Android.Common.Math;
using Com.Telerik.Widget.Chart.Engine.Decorations.Annotations.Custom;

public class ImageAnnotationRenderer : Java.Lang.Object, ICustomAnnotationRenderer


{
public RadSize MeasureContent(Java.Lang.Object content)

1845
Telerik UI for Xamarin

{
if (content == null)
{
return RadSize.Empty;
}

// Cast the content as Bitmap


var imgBitmap = (Bitmap)content;

// Get the bitmap dimensions to measure the size of the contents.


return new RadSize(imgBitmap.Width, imgBitmap.Height);
}

public void Render(


Java.Lang.Object content,
RadRect layoutSlot,
Canvas canvas,
Paint paint)
{
if (content == null)
{
return;
}

// Cast the content as Bitmap


var imgBitmap = (Bitmap)content;

// Draw the bitmap to the Canvas


canvas.DrawBitmap(
imgBitmap,
(float)layoutSlot.GetX() - (float)(layoutSlot.Width / 2.0),
(float)layoutSlot.Bottom - (float)layoutSlot.Height / 2,
paint);

}
}
 

Notice in the Render method, you are given a Canvas parameter? This is what you are drawing the
custom content to. You can use any of the Android Canvas's features, such as DrawBitmap.
 
To use it, pass it a valid Bitmap object to the CartesianCustomAnnotation and set the
ContentRender to a new instance of custom ImageAnnotationRenderer class.

csharp
Bitmap myImage = GetImage();

// Use a Bitmap for the content parameter


var annotation = new CartesianCustomAnnotation(
chartView.VerticalAxis,
chartView.HorizontalAxis,
8,

1846
Telerik UI for Xamarin

"Feb",
myImage);

// Set the ContentRenderer to the new one that can draw the bitmap to the canvas
annotation.ContentRenderer = new ImageAnnotationRenderer();

chartView.Annotations.Add(annotation);
 

Here's the result at runtime:

1847
Telerik UI for Xamarin

1848
Telerik UI for Xamarin

ChartView for Xamarin.Android: Animations


In this article, you will learn to use the animations feature in RadChartView for Xamarin.Android.

Overview
The animations for RadChartView are enabled by a class called ChartAnimationPanel. The
animation panel is a custom layout to which the chart must be added.

You can either use АddView() to add the ChartView instance (this means the panel can also be
configured through XML) or also through the Chart property. For example:

C#
ChartAnimationPanel animationPanel = new ChartAnimationPanel(this.Activity);
animationPanel.Chart = chartView;
// or animationPanel.AddView(chartView);
 

Then when the ChartView is added, you have to add animations for each series. The animations are
added with the animationPanel.AaddAnimation() method:

C#
animationPanel.AddAnimation(new ChartFadeAnimation(series));
 

Note that the ChartFadeAnimation constructor accepts a series object. If a chart animation is
initialized without a series object and this animation isadded directly to the animation panel an
exception will be thrown. Animations without associated series can only be used with
ChartAnimationGroup whichprovides its associated series to its child animations as will be shown
later.
 

Supported Animations
The currently supported animations are ChartFadeAnimation, ChartTranslateAnimation,
ChartRotateAnimation, ChartScaleAnimation and ChartAnimationGroup.

ChartFadeAnimation
C#
ChartFadeAnimation fade = new ChartFadeAnimation(series);
fade.StartOpacity = 0.3f;
 

ChartTranslateAnimation

1849
Telerik UI for Xamarin

ChartTranslateAnimation is used, as the name suggests, to move a series into view.

C#
ChartTranslateAnimation translateAnimation = new ChartTranslateAnimation(series);
translateAnimation.StartX = -200;
translateAnimation.StartY = -200;
 

ChartRotateAnimation
C#
ChartRotateAnimation rotateAnimation = new ChartRotateAnimation(series);
rotateAnimation.StartAngle = -90f;
rotateAnimation.PivotX = 500;
rotateAnimation.PivotY = 500;
 

ChartAnimationGroup
ChartAnimationGroup does not animate the chart by itself since it is a container for multiple
animations. The child animations can be started either in SEQUENTIAL or CONCURRENT mode.
This is done with the SequenceMode property.

If the sequence mode is SEQUENTIAL the duration of group itself will be divided by the number of
children and each child animation will be as long as the result from that division.

C#
ChartAnimationGroup group = new ChartAnimationGroup(series);
group.SequenceMode = ChartAnimationSequenceMode.SEQUENTIAL;
group.AddAnimation(new ChartFadeAnimation());
group.AddAnimation(new ChartScaleAnimation());
 

Common API
Finally every animation has a common API. Each animation implements the IChartAnimation
interface which looks like this:

C#
public interface IChartAnimation
{
long Duration {get; set;} //defines the duration of the animation
long InitialDelay {get; set;} //delays the start of the animation
IInterpolator Interpolator {get; set;} //defines the rate of change of the
animation
ChartSeries Series {get;}

void AddAnimationFinishedListener(IChartAnimationFinishedListener listener);

1850
Telerik UI for Xamarin

void RemoveAnimationFinishedListener(IChartAnimationFinishedListener listener);


void SetInitialValues(SeriesAnimationView view);
ViewPropertyAnimatorCompat Start(SeriesAnimationView viewToAnimate);
}
 

1851
Telerik UI for Xamarin

ChartView for Xamarin.Android: Axes


RadCartesianChartView plots data points in a coordinate system defined by its two axes. Usually,
one data point has category and value, which define its Cartesian coordinates. This means that your
chart will need one axis that can visualize the category and another which can visualize the value.
CartesianAxis is the base class for all axes that RadCartesianChartView can plot.

Category axes
The axes that can be used to visualize the category of a data point are:

 CategoricalAxis: The CategoricalAxis extends the CartesianAxis. It is the base axis that can
be used to display category of any kind.
 DateTimeCategoricalAxis: The DateTimeCategoricalAxis extends the CategoricalAxis. It can
be used if the category of the data points is of type Calendar.
 DateTimeContinuousAxis: The DateTimeContinuousAxis extends the CartesianAxis. It may be
considered as a hybrid between a categorical and a numerical (linear) axis.
DateTimeContinuousAxis works with categorical data but instead of categories, the axis
builds time slots depending on its Minimum, Maximum and MajorStep values.

Value axes
The axes that can be used to visualize the value of a data point extend the NumericalAxis class.
They are:

 LinearAxis: The LinearAxis extends the NumericalAxis class and plots the associated data
points using each point's actual value, provided for the axis.
 LogarithmicAxis: The LogarithmicAxis is used to display values that cover several orders of
magnitude in a more manageable way. This is a special numerical axis that transforms the
actual values of the data points using logarithm function with a specific base.

Features
Each axis provides several important properties you can use to customize the axis' appearance.
Here is a list of all properties that can be set on an Axis object:

 Related to axis ticks: MajorTickOffset (Sets the major value step between two ticks. By
default the axis itself will calculate the
 major step, depending on the plotted data points), TickThickness, TickColor
 Related to axis labels:

ShowLabels, LabelFont, LabelMargin, LabelTextColor, LabelFontStyle, LabelSize, ,


LabelRotationAngle, LastLabelVisibility, LabelFormat, LabelOffset, , LabelFitMode,
LabelLayoutMode, LabelInterval, LabelRendererLabelValueToStringConverter

Below is a description with examples of several properties which accept complex objects instead of
simple values.

1852
Telerik UI for Xamarin

LabelValueToStringConverter
This is an interface that can be used to convert the actual label to value to an arbitrary string before
rendering.

C#
LinearAxis verticalAxis = new LinearAxis();
verticalAxis.LabelValueToStringConverter = new LabelValueConverter();

private class LabelValueConverter : Java.Lang.Object, IFunction


{
public Java.Lang.Object Apply(Java.Lang.Object argument)
{
double labelValue = (argument.JavaCast<MajorTickModel>()).Value();
String format = "Value is: {0}";
return String.Format(format, labelValue);
}
}
 

LabelRenderer
An interface that allows developers to swap the label rendering with their own implementation.

C#
public class MyLabelRenderer : CartesianAxisLabelRenderer
{
public MyLabelRenderer(CartesianAxis axis):base(axis)
{
}

protected override void RenderLabelNoFitMode(Android.Graphics.Canvas canvas,


RadRect p1, string p2, AxisLabelModel p3)
{
// Draw something only when label fit mode is None
Paint pink = new Paint();
pink.Color = Color.ParseColor("#ff69b4");
canvas.DrawRect(new RectF((float)p1.GetX(), (float)p1.GetY(), (float)p1.Right,
(float)p1.Bottom), pink);
base.RenderLabelNoFitMode(canvas, p1, p2, p3);
}

protected override void RenderLabelMultiLine(Canvas canvas, RadRect p1, string


p2, AxisLabelModel p3)
{
// Draw something only when label fit mode is Multiline
Paint khaki = new Paint();
khaki.Color = Color.ParseColor("#f0e68c");
canvas.DrawRect(new RectF((float)p1.GetX(), (float)p1.GetY(), (float)p1.Right,
(float)p1.Bottom), khaki);

1853
Telerik UI for Xamarin

base.RenderLabelMultiLine(canvas, p1, p2, p3);


}

protected override void RenderLabelRotate(Canvas canvas, RadRect p1, string p2,


AxisLabelModel p3)
{
// Draw something only when label fit mode is ROTATE
Paint moccasin = new Paint();
moccasin.Color = Color.ParseColor("#ffe4b5");
canvas.DrawRect(new RectF((float)p1.GetX(), (float)p1.GetY(), (float)p1.Right,
(float)p1.Bottom), moccasin);
base.RenderLabelRotate(canvas, p1, p2, p3);
}

public override void RenderLabel(Canvas p0, ChartNode p1)


{
// Always draw something before the given label is drawn.
base.RenderLabel(p0, p1);
}

public override Com.Telerik.Android.Common.Math.RadSize


MeasureLabel(AxisLabelModel p0, Java.Lang.Object p1)
{
// Plug some logic when the label is being measured.
return base.MeasureLabel(p0, p1);
}
}
 

Finally, developers can use this custom label renderer by calling axis.setLabelRenderer(new
MyLabelRenderer(axis)) or axis.LabelRenderer = new MyLabelRenderer(axis); for
Xamarin.

1854
Telerik UI for Xamarin

ChartView for Xamarin.Android: CategoricalAxis


When RadCartesianChartView visualizes CategoricalSeries, it needs an axis that can represent the
different categories. The CategoricalAxis extends the base CartesianAxis class and is used to
displays a range of categories. Categories are built depending on the Category value of each
CategoricalDataPoint present in the owning CategoricalSeries chart series. The axis is divided into
discrete slots and each data point is visualized in the slot corresponding to its categorical value.

The CategoricalAxis extends the base CartesianAxis class and is used to displays a range of
categories. Categories are built depending on the Category value of each
CategoricalDataPoint present in the owning CategoricalSeries chart series. The axis is divided
into discrete slots and each data point is visualized in the slot corresponding to its categorical value.

Example
You can read from the Getting Started page how to define the MonthResult type and declare the
initData() method.

After you create the method for initialization of sample data, you can create a
RadCartesianChartView with LineSeries by adding the following code to the onCreate() method of
your Activity.

C#
InitData();

RadCartesianChartView chartView = new RadCartesianChartView(this);

LineSeries lineSeries = new LineSeries();


lineSeries.CategoryBinding = new MonthResultDataBinding ("Month");
lineSeries.ValueBinding = new MonthResultDataBinding ("Result");
lineSeries.Data = (Java.Lang.IIterable)this.monthResults;

chartView.Series.Add(lineSeries);

CategoricalAxis horizontalAxis = new CategoricalAxis();


chartView.HorizontalAxis = horizontalAxis;

LinearAxis verticalAxis = new LinearAxis();


chartView.VerticalAxis = verticalAxis;

ViewGroup rootView = (ViewGroup)FindViewById(Resource.Id.container);


rootView.AddView(chartView);
 

Here's the result:

1855
Telerik UI for Xamarin

Features
Plot Mode
The CategoricalAxis allows you to define how exactly the axis will be plotted on the viewport of the
chart through its PlotMode property. The possible values are:

 AxisPlotMode.BetweenTicks: Points are plotted in the middle of the range, defined between
each two ticks.
 AxisPlotMode.OnTicks: Points are plotted over each tick.
 AxisPlotMode.OnTicksPadded: Points are plotted over each tick with half a step padding
applied on both ends of the axis.

1856
Telerik UI for Xamarin

Gap Length
Defines the distance (in logical units) between two adjacent categories. Default value is 0.3. For
example if you have BarSeries, you can decrease the space between the bars from the different
categories by setting the GapLength property to a value lower than 0.3.

Major Tick Interval


MajorTickInterval property defines the step at which major ticks are generated. The default and also
minimum value is 1. This property also affects axis labels as they are generated on a per major tick
basis. For example, if you don't want to display all ticks, but instead only half of them (display the
first, third, fifth, etc. ticks), you should set the major tick interval to 2:

C#
horizontalAxis.MajorTickInterval = 2;
 

1857
Telerik UI for Xamarin

ChartView for Xamarin.Android: DateTimeCategoricalAxis


When RadCartesianChartView visualizes CategoricalSeries, it needs an axis that can represent the
different categories. The CategoricalAxis extends the base CartesianAxis class and is used to
displays a range of categories. Categories are built depending on the Category value of each
CategoricalDataPoint present in the owning CategoricalSeries chart series. The axis is divided into
discrete slots and each data point is visualized in the slot corresponding to its categorical value.

The DateTimeCategoricalAxis is a special axis that extends the CategoricalAxis class and adds
notation for the java.util.Calendar structure. The axis works with the CategoricalSeries and
expects each CategoricalDataPoint to provide a valid java.util.Calendar value as its Category.
Once built, the groups are sorted in chronological order.

Example
Again, we will use the MonthResult type as defined in the Getting Started page but this type we will
extend this typewith additional field which will contain our Calendar component:

C#
public class ExtendedMonthResult : MonthResult
{
public Java.Util.Calendar Date { get; set;}

public ExtendedMonthResult (String month, double result, Java.Util.Calendar date)


:base(month, result)
{
this.Date = date;
}
}
 

We will also need a list of items from the new type and initialize it with proper data:

C#
private Java.Util.ArrayList extendedMonthResults;

private void InitCalendarData() {


extendedMonthResults = new Java.Util.ArrayList();

extendedMonthResults.Add(new ExtendedMonthResult(
"Jan", 5, new Java.Util.GregorianCalendar(2014, Java.Util.Calendar.January,
5)));

extendedMonthResults.Add(new ExtendedMonthResult(
"Feb", 8, new Java.Util.GregorianCalendar(2014, Java.Util.Calendar.February,
8)));

extendedMonthResults.Add(new ExtendedMonthResult(
"Mar", 3, new Java.Util.GregorianCalendar(2014, Java.Util.Calendar.March, 3)));

1858
Telerik UI for Xamarin

extendedMonthResults.Add(new ExtendedMonthResult(
"Mar", 12, new Java.Util.GregorianCalendar(2014, Java.Util.Calendar.March,
22)));
}

class ExtendedMonthResultDataBinding : DataPointBinding {

private string propertyName;

public ExtendedMonthResultDataBinding(string propertyName)


{
this.propertyName = propertyName;
}

public override Java.Lang.Object GetValue (Java.Lang.Object p0)


{
if(propertyName == "Date")
{
return ((ExtendedMonthResult)(p0)).Date;
}
return ((ExtendedMonthResult)(p0)).Result;
}
}
 

Now we can go to the Activity where we want to add a RadCartesianChartView with


DateTimeCategoricalAxis and add the following code:

C#
InitCalendarData();

RadCartesianChartView chartView = new RadCartesianChartView(this);

BarSeries barSeries = new BarSeries();


barSeries.CategoryBinding = new ExtendedMonthResultDataBinding ("Date");
barSeries.ValueBinding = new ExtendedMonthResultDataBinding ("Result");
barSeries.Data = (Java.Lang.IIterable)this.extendedMonthResults;
chartView.Series.Add(barSeries);

DateTimeCategoricalAxis horizontalAxis = new DateTimeCategoricalAxis();


horizontalAxis.DateTimeComponent = DateTimeComponent.Month;
horizontalAxis.DateTimeFormat = new SimpleDateFormat("MMM-yyyy");
chartView.HorizontalAxis = horizontalAxis;

LinearAxis verticalAxis = new LinearAxis();


chartView.VerticalAxis = verticalAxis;

ViewGroup rootView = (ViewGroup)FindViewById(Resource.Id.container);


rootView.AddView(chartView);
 

Here is the result:

1859
Telerik UI for Xamarin

Features
The DateTimeCategoricalAxis extends CategoricalAxis so you can use the same features.
Additionally, you can set the date time format and component.

Date Time Component


DateTimeComponent property defines the component of each Calendar structure that participates
in the grouping process. The possible values: Year, Quarter, Month, Week, Hour, Minute, Second,
Millisecond, Date, TimeOfDay, Day, DayOfWeek, DayOfYear. You can see in the previous example
we have added four items and they are in three groups, because the date time component is set to
Month.

1860
Telerik UI for Xamarin

Date Time Format


DateTimeFormat property defines the format of the Calendar structure that will be used for the
categories. The default value is "M/d/yy h:mm a". You can see in the previous example how we used
the date time format in order to display only month and year.

1861
Telerik UI for Xamarin

ChartView for Xamarin.Android: DateTimeContinuousAxis


When RadCartesianChartView visualizes CategoricalSeries, it needs an axis that can represent the
different categories. The CategoricalAxis extends the base CartesianAxis class and is used to
displays a range of categories. Categories are built depending on the Category value of each
CategoricalDataPoint present in the owning CategoricalSeries chart series. The axis is divided into
discrete slots and each data point is visualized in the slot corresponding to its categorical value.
These are the axes which can plot categorical data:

DateTimeContinuousAxis is a special axis that extends the base CartesianAxis class and may be
considered as a hybrid between a categorical and a value axis. DateTimeContinuousAxis works with
categorical data but instead of categories, the axis builds time slots depending on its Minimum,
Maximum and MajorStep values. DateTimeContinuousAxis also expects valid Calendar values so
that the data could be plotted correctly. Think of DateTimeContinuousAxis as a timeline where each
data point has a certain position, depending on its Calendar value. The timeline range properties'
values are automatically calculated if not set explicitly by the user: the default value of the major step
is the smallest difference between any two Calendar values. Because this axis behaves like a
numerical one, there might be empty time slots if no data falling into them is found.

Example
We are going to use the initCalendarData() method and the ExtendedMonthResult type like in the
example with DateTimeCategoricalAxis. But this time we will use the LineSeries in order to better
indicate the continuity of the axis. Go to the Activity where we want to add a RadCartesianChartView
with DateTimeContinuousAxis and add the following code:

C#
InitCalendarData();

RadCartesianChartView chartView = new RadCartesianChartView(this);

LineSeries lineSeries = new LineSeries();


lineSeries.CategoryBinding = new ExtendedMonthResultDataBinding ("Date");
lineSeries.ValueBinding = new ExtendedMonthResultDataBinding ("Result");
lineSeries.Data = (Java.Lang.IIterable)this.extendedMonthResults;
chartView.Series.Add(lineSeries);

DateTimeContinuousAxis horizontalAxis = new DateTimeContinuousAxis();


horizontalAxis.LabelFitMode = AxisLabelFitMode.Rotate;
chartView.HorizontalAxis = horizontalAxis;

LinearAxis verticalAxis = new LinearAxis();


chartView.VerticalAxis = verticalAxis;

ViewGroup rootView = (ViewGroup)FindViewById(Resource.Id.container);


rootView.AddView(chartView);
 

And here is the result:

1862
Telerik UI for Xamarin

Notice how the ticks are not based on the actual values of the data items. Instead they aim to
represent the actual time frames between the date values of the data items.

Features
Maximum Ticks
You can set a maximum number of ticks that will be used in a DateTimeContinuousAxis with the
MaximumTicks property. This will not affect the way the series look, but it will change the number of
labels on the axis.

Gap Length

1863
Telerik UI for Xamarin

Defines the distance (in logical units) between two adjacent categories. Default value is 0.3. For
example if you have BarSeries, you can decrease the space between the bars from the different
categories by setting the Gap Length to a value lower that 0.3. You can specify the current value
with GapLength property. The possible values are from the (0, 1) interval.

Major Step
The major step represents the value difference between two visible ticks on the axis. The major step
unit is used to determine what exactly the value of the major step represents. For example if you
want to have 10 days between two ticks on the axis you need to use both MajorStep and
MajorStepUnit properties:

C#
horizontalAxis.MajorStepUnit = TimeInterval.Day;
horizontalAxis.MajorStep = 10;
 

Minimum and Maximum


You can define explicitly the dates where the axis starts and ends. By default the start and end are
determined by the values of the data items. If you want to change it, you can use Minimum and
Maximum properties.

PlotMode
DateTimeContinuousAxis allows you to define how exactly the axis will be plotted on the viewport of
the chart through the PlotMode property. The possible values are:

 AxisPlotMode.BetweenTicks: Points are plotted in the middle of the range, defined between
each two ticks.
 AxisPlotMode.OnTicks: Points are plotted over each tick.
 AxisPlotMode.OnTicksPadded: Points are plotted over each tick with half a step padding
applied on both ends of the axis.

1864
Telerik UI for Xamarin

ChartView for Xamarin.Android: LinearAxis


RadCartesianChartView needs an axis that can represent the values of the data points. The base
class for the axes that can represent value is NumericalAxis.It is an abstract class which extends the
base CartesianAxis class and is used to represent the value of a data point.

The LinearAxis extends the base CartesianAxis class and plots the associated data points using
each point's actual value, provided for the axis. The axis works with categorical data and uses the
Value property of each CategoricalDataPoint that needs to be plotted. It will build a numerical range
(user-defined or automatically calculated) and will determine each data point X or Y coordinate
(depending on whether the axis is specified as Horizontal or as Vertical).

Example
You can read from the Getting Started page how to define the MonthResult type and declare the
initData() method.

After you create the method for initialization of sample data, you can create a
RadCartesianChartView with LinearAxis by adding the following code to the onCreate() method of
your Activity.

C#
InitData();

RadCartesianChartView chartView = new RadCartesianChartView(this);

LineSeries lineSeries = new LineSeries();


lineSeries.CategoryBinding = new MonthResultDataBinding ("Month");
lineSeries.ValueBinding = new MonthResultDataBinding ("Result");
lineSeries.Data = (Java.Lang.IIterable)this.monthResults;
chartView.Series.Add(lineSeries);

CategoricalAxis horizontalAxis = new CategoricalAxis();


chartView.HorizontalAxis = horizontalAxis;

LinearAxis verticalAxis = new LinearAxis();


chartView.VerticalAxis = verticalAxis;

ViewGroup rootView = (ViewGroup)FindViewById(Resource.Id.container);


rootView.AddView(chartView);
 

Here's the result:

1865
Telerik UI for Xamarin

Major Step
Major Step specifies the step at which the major ticks are positioned on the axis. If this property is
set to 0 (by default), the axis automatically calculates the step so that the data will be visualized in
the best possible way. For example, if you want to set the distance between the ticks to a fixed value
like 10, you will need to apply MajorStep property:

C#
verticalAxis.MajorStep = 10;
 

1866
Telerik UI for Xamarin

ChartView for Xamarin.Android: LogarithmicAxis


RadCartesianChartView needs an axis that can represent the values of the data points. The base
class for the axes that can represent value is NumericalAxis.It is an abstract class which extends the
base CartesianAxis class and is used to represent the value of a data point.

The LogarithmicAxis is used to display values that cover several orders of magnitude in a more
manageable way. This is a special NumericalAxis that transforms the actual values of the data points
using logarithm function with a specific base. For example if the base of the logarithm is 10, then the
axis will be scaled to show equally spaced powers of 10. The Richter scale and the Decibel scale are
examples of logarithmic scale.

Example
You can read from the Getting Started page how to define the MonthResult type and declare the
initData() method.

After you create the method for initialization of sample data, you can create a
RadCartesianChartView with LogarithmicAxis by adding the following code to the onCreate() method
of your Activity.

C#
InitData();

RadCartesianChartView chartView = new RadCartesianChartView(this);

LineSeries lineSeries = new LineSeries();


lineSeries.CategoryBinding = new MonthResultDataBinding ("Month");
lineSeries.ValueBinding = new MonthResultDataBinding ("Result");
lineSeries.Data = (Java.Lang.IIterable)this.monthResults;
chartView.Series.Add(lineSeries);

CategoricalAxis horizontalAxis = new CategoricalAxis();


chartView.HorizontalAxis = horizontalAxis;

LogarithmicAxis verticalAxis = new LogarithmicAxis();


verticalAxis.LogarithmBase = 2;
chartView.VerticalAxis = verticalAxis;

ViewGroup rootView = (ViewGroup)FindViewById(Resource.Id.container);


rootView.AddView(chartView);
 

Customization
You can easily modify the base of the logarithmic function used to calculate the value by using the
LogarithmBase property. The default value is 10, but in our example we have set it to 2, because our
values are relatively small. You can also specify the exponent step between the axis ticks with the

1867
Telerik UI for Xamarin

ExponentStep property. The default value of the exponent step is 0 which means that the axis itself
will calculate an exponent step that will visualize the points in the best possible way.

1868
Telerik UI for Xamarin

ChartView for Xamarin.Android: Multiple Axes


RadCartesianChartView can visualize multiple axes simultaneously. You can add vertical and
horizontal axes per chart basis and per series basis. This means that if you have two series in one
chart instance, you can use different horizontal and vertical axes for each series. Depending on the
requirements, the axes can be plot independently, or relatively to each other.

Example
The image below illustrates a scenario in which we have two series - LineSeries and BarSeries. The
LineSeries will use a DateTimeCategoricalAxis positioned on the Top and a LinearAxis on the Left.
The BarSeries will use a CategoricalAxis positioned at the Bottom and another LinearAxis
positioned on the Right:

1869
Telerik UI for Xamarin

In order to achieve this, you need to create two series and set their own axes. You also need to set
their location. In this case you don't need to set axes to the whole chart. You can read from the
Getting Started page how to define the MonthResult type and declare the initData() and
initCalendarData() methods. Then you can add the following code to your Activity:

C#
InitData();
InitCalendarData();

RadCartesianChartView chartView = new RadCartesianChartView(this);

BarSeries barSeries = new BarSeries();


barSeries.CategoryBinding = new MonthResultDataBinding ("Month");

1870
Telerik UI for Xamarin

barSeries.ValueBinding = new MonthResultDataBinding ("Result");


barSeries.Data = (Java.Lang.IIterable)this.monthResults;
chartView.Series.Add(barSeries);

LineSeries lineSeries = new LineSeries();


lineSeries.CategoryBinding = new ExtendedMonthResultDataBinding ("Date");
lineSeries.ValueBinding = new ExtendedMonthResultDataBinding ("Result");
lineSeries.Data = (Java.Lang.IIterable)this.extendedMonthResults;
chartView.Series.Add(lineSeries);

CategoricalAxis horizontalAxisBar = new CategoricalAxis();


horizontalAxisBar.VerticalLocation = AxisVerticalLocation.Bottom;
barSeries.HorizontalAxis = horizontalAxisBar;

LinearAxis verticalAxisBar = new LinearAxis();


verticalAxisBar.HorizontalLocation = AxisHorizontalLocation.Right;
barSeries.VerticalAxis = verticalAxisBar;

DateTimeCategoricalAxis horizontalAxisLine = new DateTimeCategoricalAxis();


horizontalAxisLine.DateTimeComponent = DateTimeComponent.Day;
horizontalAxisLine.DateTimeFormat = new SimpleDateFormat("dd-MM");
horizontalAxisLine.VerticalLocation = AxisVerticalLocation.Top;
lineSeries.HorizontalAxis = horizontalAxisLine;

LinearAxis verticalAxisLine = new LinearAxis();


verticalAxisLine.HorizontalLocation = AxisHorizontalLocation.Left;
lineSeries.VerticalAxis = verticalAxisLine;

ViewGroup rootView = (ViewGroup)FindViewById(Resource.Id.container);


rootView.AddView(chartView);
 

1871
Telerik UI for Xamarin

ChartView for Xamarin.Android: Behaviors


Each chart can be enabled with interactivity through its Behaviors. A behavior is generally an
abstraction that handles user input in a RadChartView instance and optionally provides visual
feedback upon some action. The following behaviors are available:

 PanAndZoomBehavior: When this behavior is added to RadCartesianChartView, the gestures


drag, pinch open and pinch close respectively cause panning, zooming in and zooming out
of the associated chart plot area.
 TrackballBehavior: This behavior is responsible for rendering concise information about
several data points in a small popup which displays over its relevant data points. A vertical
line is also drawn through the data points for maximum clarity.
 TooltipBehavior: This behavior is used for rendering concise information about a data point in
a small popup.
 ChartSelectionBehavior: Handles selecting and deselecting of either data points or series.

Getting Started
In order to add a behavior, you simply need to add a new behavior of the desired type to the
behaviors collection of your chart instance:

C#
RadCartesianChartView chartView = new RadCartesianChartView(this);

ChartPanAndZoomBehavior behavior = new ChartPanAndZoomBehavior();


chartView.Behaviors.Add(behavior);
 

1872
Telerik UI for Xamarin

ChartView for Xamarin.Android: PanAndZoomBehavior


With PanAndZoomBehavior, RadCartesianChartView handles the gestures drag, pinch open and
pinch close which respectively cause panning, zooming in and zooming out of the associated chart
plot area.

Getting Started
You can read from the Getting Started page how to define the MonthResult type and declare the
initData() method.

After you create the method for initialization of sample data, you can create a
RadCartesianChartView with LineSeries and add a ChartPanAndZoomBehavior by adding the
following code to the onCreate() method of your Activity.

C#
InitData();

RadCartesianChartView chartView = new RadCartesianChartView(this);

ChartPanAndZoomBehavior behavior = new ChartPanAndZoomBehavior();


chartView.Behaviors.Add(behavior);

LineSeries lineSeries = new LineSeries();


lineSeries.CategoryBinding = new MonthResultDataBinding ("Month");
lineSeries.ValueBinding = new MonthResultDataBinding ("Result");
lineSeries.Data = (Java.Lang.IIterable)this.monthResults;
chartView.Series.Add(lineSeries);

CategoricalAxis horizontalAxis = new CategoricalAxis();


chartView.HorizontalAxis = horizontalAxis;

LinearAxis verticalAxis = new LinearAxis();


chartView.VerticalAxis = verticalAxis;

ViewGroup rootView = (ViewGroup)FindViewById(Resource.Id.container);


rootView.AddView(chartView);
 

Features
Pan Mode and Zoom Mode
You can specify whether the Pan /Drag/ gesture will be handled for all directions, only for one, or for
none. This behavior can be modified with PanMode property.The same is applicable for the pinch
in/out gesture, which can be modified with ZoomMode property. The possible values for both modes
are:

1873
Telerik UI for Xamarin

 ChartPanZoomMode.Both: the default mode, where the chart can be panned and zoomed in
both directions
 ChartPanZoomMode.Horizontal: the chart will be able to be panned or zoomed only
horizontally
 ChartPanZoomMode.Vertical: the chart will be able to be panned or zoomed only vertically
 ChartPanZoomMode.None: the chart will NOT be panned or zoomed in either direction

Zoom Strategy
ChartPanZoomBehavior supports two zoom strategies out of the box. These are
ChartZoomStrategy.Immediate and ChartZoomStrategy.Deferred.

In Immediate mode, the chart reacts to every pinch gesture and redraws the chart accordingly. This
can become troublesome if you need to zoom a lot, since you will have to do a lot of pinching to get
to the desired zoom level. In this case the Deferred strategy would be more useful since you can
simply pinch to create a zoom rectangle. This rectangle defines the area which will be stretched to fill
the whole chart plot area, the smaller the chosen rectangle, the larger the zoom will be.

You can set the zoom strategy like so:

C#
panZoomBehavior.ZoomStrategy = ChartZoomStrategy.Deferred;
 

Here is what the zoom rect looks like:

1874
Telerik UI for Xamarin

Double Tap
By default, the pan and zoom behavior also provides zooming capabilities for the double tap gesture.
This means that the chart will be zoomed in or zoomed out when this gesture occurs. This can be
changed with the HandleDoubleTap property:

C#
behavior.HandleDoubleTap = false;
 

1875
Telerik UI for Xamarin

ChartView for Xamarin.Android: ChartTrackBallBehavior


ChartTrackBallBehavior is responsible for rendering concise information about several data points in
a small popup which displays over its relevant data points. A horizontal or vertical line is also drawn
through the data points for maximum clarity.

1876
Telerik UI for Xamarin

Getting Started
ChartTrackballBehavior is used in the exact same way as ChartTooltipBehavior, for example:

1877
Telerik UI for Xamarin

C#
ChartTrackBallBehavior trackballBehavior = new ChartTrackBallBehavior(this);
chartView.Behaviors.Add(trackballBehavior);
 

This code example assumes that there is an existing instance of RadCartesianChartView which is
initialized and populated with data. You can see how to do this ChartView: Getting Started.

Features
The trackball is always shown via the hold gesture. When the behavior detects a hold, it displays the
trackball and hides it when the user stops touching the screen. This is in contrast with the tooltip,
since the tooltip remains shown even after the hold gesture has completed.

ChartTrackBallBehavior provides a ShowTrackInfo property which allows you to show or hide the
popup information. Sometimes only point indicators are necessary so the track info can be hidden.
The aforementioned point indicators are small customizable visual cues that are displayed on top of
the relevant data points.

C#
trackballBehavior.ShowIntersectionPoints = true;
 

1878
Telerik UI for Xamarin

C#
trackballBehavior.ShowTrackInfo = false;
 

1879
Telerik UI for Xamarin

ChartTrackBallBehavior has two hit test modes - Logical and Physical. The logical mode finds and
highlights points based on the closest category. This is the default mode.cThe physical mode
matches the datapoints by their physical location.

C#
trackballBehavior.PointHitTestMode = TrackBallHitTestMode.Physical;
 

1880
Telerik UI for Xamarin

ChartView for Xamarin.Android: ChartTooltipBehavior


ChartTooltipBehavior is responsible for rendering concise information about a data point in a small
popup which displays close to its relevant data point.

Getting Started
The ChartTooltipBehavior class is used by creating an instance of it and adding the instance to the
behaviors collection of a chart view, for example:

C#
ChartTooltipBehavior tooltipBehavior = new ChartTooltipBehavior(this);
chartView.Behaviors.Add(tooltipBehavior);
 

This code example assumes that there is an existing instance of RadCartesianChartView which is
initialized and populated with data. You can see how to do this here.

Here is the tooltip in action:

Features
ChartTooltipBehavior has several options for configuration. The most commonly used would
probably be the tooltip trigger mode. The chart tooltip can be triggered either with a hold or a tap
gesture. This is controlled with the TriggerMode property. The tooltip behavior can display its tooltip

1881
Telerik UI for Xamarin

through code via the Open(DataPoint p0) and Close() methods.

Finally ChartTooltipBehavior is integrated with the chart palettes, which means simple color
modifications of the existing tooltip view canbe quickly achieved by simple modification of the
existing palette as shown here.

1882
Telerik UI for Xamarin

ChartView for Xamarin.Android: ChartSelectionBehavior


ChartSelectionBehavior is responsible for selecting, deselecting and reporting the selection of either
data points or series. In other words,the selection behavior can target data points, series or both if
required.

Getting Started
ChartSelectionBehavior does not have any special initialization requirements. Simply create an
instance of it and add it to the behaviors collection of RadChartView.

For example:

C#
chartView.Behaviors.Add(new ChartSelectionBehavior());
 

This code example assumes that there is an existing instance of RadCartesianChartView which is
initialized and populated with data. You can see how to do this here.

Features
The selection behavior can be set to select data points, whole series or both. This can be done by
using SeriesSelectionMode and DataPointsSelectionMode properties. The selection mode for both
methods is the same enum which contains three values: Single, Multiple and None.

The selection always works in toggle mode. If you select a data point or a series, you can always
deselect it as well. The end-user can never end up with a selected series or data point that they can't
deselect.

Here is an example of how to set the selection mode:

C#
selectionBehavior.SeriesSelectionMode = ChartSelectionMode.Multiple;
selectionBehavior.DataPointsSelectionMode = ChartSelectionMode.None;
 

1883
Telerik UI for Xamarin

1884
Telerik UI for Xamarin

You can also listen for selection changes by calling the SetSelectionChangeListener() method and
providing an implementation of the IChartSelectionChangeListener interface, for example:

C#

1885
Telerik UI for Xamarin

selectionBehavior.SetSelectionChangeListener(new MySelectionChangedListener());
 

A simple implementation of ChartSelectionChangeListener would look like this:

C#
class MySelectionChangedListener : Java.Lang.Object, IChartSelectionChangeListener
{
public void OnSelectionChanged(ChartSelectionContext p0)
{
DataPoint selectedPoint = p0.SelectedDataPoint();
if(selectedPoint == null) {
return;
}

// Display some detailed information about the data point.


// selectedPoint.DataItem would return the actual data object
// that the point represents.
}
}
 

Note that selection context returns a selected data point. But if many points are selected and you
need to get all of them, you will have to access the selection behavioritself. It has two methods called
SelectedSeries() and SelectedDataPoints(). A reference to the selection behavior is actually included
in the selection context. For example:
 
C#
public void OnSelectionChanged(ChartSelectionContext p0)
{
Java.Lang.IIterable selectedPoints = p0.SelectionBehavior().SelectedDataPoints();

// Do something with the selected points.


}
 

Finally the selected state of all series and data points is defined within the chart palettes so
customization of simple colors is quick an easy.

1886
Telerik UI for Xamarin

ChartView for Xamarin.Android: Series Overview


The data visualization in RadChartView is done by a hierarchy of classes that inherit from the
ChartSeries class. Each series has a collection of data items which provide the data. Concrete
series types are available for specific charts. For example, there is a set of CartesianSeries
applicable in the context of a RadCartesianChartView.

Abstract Series:
These are the base series that are extended by the actual series implementations in order to provide
a clear level of abstraction and define more clearly the common features among the different series
types.

 ChartSeries: The ChartSeries class is a base class for all types of series used in
RadChartView.
 PointTemplateSeries: The PointTemplateSeries class extends ChartSeries with capabilities
for customization of the visualization.
 CartesianSeries: The CartesianSeries class extends PointTemplateSeries and it is the base
class for series used by RadCartesianChartView.
 CategoricalSeries: The CategoricalSeries class extends CartesianSeries. These series
present the data in a chart with Cartesian coordinates, where one of the axes is categorical
and the other is linear. They can visualize categorical data that has category and value
properties.
 CategoricalStrokedSeries: The CategoricalStrokedSeries extends CategoricalSeries and it is
a base class for series that are visually represented by data points connected with strokes.
 RangeSeriesBase: The RangeSeriesBase extends CartesianSeries and it is a base class for
range series which present categorical data with more than one value property.

CategoricalSeries
The CategoricalSeries is an abstract class which is extended by series which can present
categorical data. This data needs category and value properties which determine the Cartesian
coordinates of each data point.

Bindings

The CategoricalSeries class contains CategoryBinding and ValueBinding properties of type


DataPointBinding - these properties define the way the necessary information will be extracted
from each data item. For example if our data item type is defined as follows:

C#
public class MonthResult : Java.Lang.Object {

public double Result { get; set; }


public String Month { get; set; }

public MonthResult(String month, double result) {


this.Month = month;

1887
Telerik UI for Xamarin

this.Result = result;
}
}
 

If we want to use the result of the data item as a value for our data points that will be visualized by
the chart, we can define the DataPointBinding object for the value like this:

C#
class MonthResultDataBinding : DataPointBinding {

private string propertyName;

public MonthResultDataBinding(string propertyName)


{
this.propertyName = propertyName;
}

public override Java.Lang.Object GetValue (Java.Lang.Object p0)


{
if(propertyName == "Month")
{
return ((MonthResult)(p0)).Month;
}
return ((MonthResult)(p0)).Result;
}
}
 

Similarly, if we want to use the month of the data item as a category for our data points that will be
visualized by the chart, we can define the DataPointBinding object for the category like this:

C#
class MonthResultDataBinding : DataPointBinding {

private string propertyName;

public MonthResultDataBinding(string propertyName)


{
this.propertyName = propertyName;
}

public override Java.Lang.Object GetValue (Java.Lang.Object p0)


{
if(propertyName == "Month")
{
return ((MonthResult)(p0)).Month;
}
return ((MonthResult)(p0)).Result;
}
}
 

1888
Telerik UI for Xamarin

Then, we can use these objects with series that extend CategoricalSeries, for example LineSeries:

C#
LineSeries lineSeries = new LineSeries();
lineSeries.CategoryBinding = new MonthResultDataBinding ("Month");
lineSeries.ValueBinding = new MonthResultDataBinding ("Result");
 

Combine Mode

When the series in a RadCartesianChartView are more than one, a few different drawing strategies
can be used. The possible strategies are:

 None: The series are not combined - each series is plotted independently.
 Cluster: Series are combined next to each other (applicable for BarSeries).
 Stack: Series form stacks.
 Stack100: Series form stacks that occupy 100% of the plot area and the characteristic size of
each series is proportional to its relative value.

The default combine mode is None. You can modify the current value through the CombineMode
property. For example if you have two BarSeries, you need to set the combine mode to both of them
if you want to make them stacked:

C#
barSeries1.CombineMode = ChartSeriesCombineMode.Stack;
barSeries2.CombineMode = ChartSeriesCombineMode.Stack;
 

Here's how a chart with two BarSeries looks with the different combine modes:

RangeSeriesBase
The RangeSeriesBase is an abstract class which is extended by series which can present
categorical data with more than one value property. The data needs not only category, but also 2
value properties: low value and high value. The series visaulize the whole range between the low
value and the high value.

1889
Telerik UI for Xamarin

The binding mechanism in RangeSeriesBase is the same as in CategoricalSeries. The methods that
set the bindings are setCategoryBinding(DataPointBinding), setHighBinding(DataPointBinding) and
setLowBinding(DataPointBinding). These series need two value bindings — low and high — in order
to determine the start point and the end point of each data point.

RadCartesianChartView Series
RadCartesianChartView is a RadChartView which visualizes series as data points with Cartesian
coordinates. Here is a list with the series types which provide data that can be plot on
RadCartesianChartView:

 LineSeries: The LineSeries extend CategoricalStrokedSeries. RadCartesianChartView


visualizes these series as data points connected with straight line segments.
 SplineSeries: The SplineSeries extend LineSeries. RadCartesianChartView visualizes these
series as data points connected with curved line segments.
 AreaSeries: The AreaSeries also extend CategoricalStrokedSeries. RadCartesianChartView
visualizes these series as the area on the chart that is enclosed by the coordinate axes and
straight line segments that connect the data points represented by these series.
 SplineAreaSeries: The SplineAreaSeries extend AreaSeries. The difference with the
AreaSeries is that the segments that connect the data points are connected with curved line
segments.
 BarSeries: The BarSeries extend the CategoricalSeries, which means that they also need to
have one categorical and one linear axis. The data points are represented by rectangle
shapes.
 RangeBarSeries: The RangeBarSeries extend the RangeSeriesBase. They represent the
data by rectangle shapes in a way similar to BarSeries. The difference is that the bars are
not necessarily drawn from the beginning of the categorical axis, unless the low value of the
data point, that they represent, has a value of 0.

RadPieChartView Series
 PieSeries: The PieSeries extend ChartSeries and are used by RadPieChartView to represent
data in the shape of a pie. Each data item is visually represented by a pie slice. The ratio
between the space consumed by each slice and the space consumed by the whole chart is
the same as the ratio between the value of the data point that it represents and the total
value of all data points in the series.
 DoughnutSeries: The DoughnutSeries extend PieSeries. The difference is that an instance of
RadPieChartView with DoughnutSeries will have a blank portion in the center.

1890
Telerik UI for Xamarin

ChartView for Xamarin.Android: LineSeries


RadCartesianChartView visualizes each data item from the LineSeries and connects them with
straight line segments. The LineSeries extend CategoricalStrokedSeries, so they are also
CategoricalSeries and require one CategoricalAxis and one LinearAxis.

Example
You can read from the Getting Started page how to define the MonthResult type and declare the
initData() method.

After you create the method for initialization of sample data, you can create a
RadCartesianChartView with LineSeries by adding the following code to the onCreate() method of
your Activity.

C#
InitData();

RadCartesianChartView chartView = new RadCartesianChartView(this);

LineSeries lineSeries = new LineSeries();


lineSeries.CategoryBinding = new MonthResultDataBinding ("Month");
lineSeries.ValueBinding = new MonthResultDataBinding ("Result");
lineSeries.Data = (Java.Lang.IIterable)this.monthResults;
chartView.Series.Add(lineSeries);

CategoricalAxis horizontalAxis = new CategoricalAxis();


chartView.HorizontalAxis = horizontalAxis;

LinearAxis verticalAxis = new LinearAxis();


chartView.VerticalAxis = verticalAxis;

ViewGroup rootView = (ViewGroup)FindViewById(Resource.Id.container);


rootView.AddView(chartView);
 

This example assumes that your root container has id container


 
Here's the result:

1891
Telerik UI for Xamarin

Customization
LineSeries extend CategoricalStrokedSeries which provide the following way to change their style:

 StrokeColor: changes the color used to draw lines.


 StrokeThickness: changes the width of the lines.

You can also customize the appearance of LineSeries by using Palettes.

1892
Telerik UI for Xamarin

ChartView for Xamarin.Android: SplineSeries


RadCartesianChartView visualizes each data item from the SplineSeries and connects them with
curved line segments. The SplineSeries extend LineSeries, so they are also CategoricalSeries and
require one CategoricalAxis and one LinearAxis.

Example
You can read from the Getting Started page how to define the MonthResult type and declare the
initData() method.

After you create the method for initialization of sample data, you can create a
RadCartesianChartView with SplineSeries by adding the following code to the onCreate() method of
your Activity.

C#
InitData();

RadCartesianChartView chartView = new RadCartesianChartView(this);

SplineSeries splineSeries = new SplineSeries();


splineSeries.CategoryBinding = new MonthResultDataBinding ("Month");
splineSeries.ValueBinding = new MonthResultDataBinding ("Result");
splineSeries.Data = (Java.Lang.IIterable)this.monthResults;
chartView.Series.Add(splineSeries);

CategoricalAxis horizontalAxis = new CategoricalAxis();


chartView.HorizontalAxis = horizontalAxis;

LinearAxis verticalAxis = new LinearAxis();


chartView.VerticalAxis = verticalAxis;

ViewGroup rootView = (ViewGroup)FindViewById(Resource.Id.container);


rootView.AddView(chartView);
 

This example assumes that your root container has id container


 
Here's the result:

1893
Telerik UI for Xamarin

Customization
SplineSeries extend LineSeries, so they provide the same way to change their style — by using the
following properties:

 StrokeColor: changes the color used to draw lines.


 StrokeThickness: changes the width of the lines.

You can also customize the appearance of SplineSeries by using Palettes.

1894
Telerik UI for Xamarin

ChartView for Xamarin.Android: AreaSeries


RadCartesianChartView visualizes AreaSeries as an area on the chart that is enclosed by the
coordinate axes and straight line segments that connect the data points represented by these series.
The AreaSeries extend CategoricalStrokedSeries, so they are also CategoricalSeries and require
one CategoricalAxis and one LinearAxis.

Example
You can read from the Getting Started page how to define the MonthResult type and declare the
initData() method.

After you create the method for initialization of sample data, you can create a
RadCartesianChartView with AreaSeries by adding the following code to the onCreate() method of
your Activity.

C#
InitData();

RadCartesianChartView chartView = new RadCartesianChartView(this);

AreaSeries areaSeries = new AreaSeries();


areaSeries.CategoryBinding = new MonthResultDataBinding ("Month");
areaSeries.ValueBinding = new MonthResultDataBinding ("Result");
areaSeries.Data = (Java.Lang.IIterable)this.monthResults;
chartView.Series.Add(areaSeries);

CategoricalAxis horizontalAxis = new CategoricalAxis();


chartView.HorizontalAxis = horizontalAxis;

LinearAxis verticalAxis = new LinearAxis();


chartView.VerticalAxis = verticalAxis;

ViewGroup rootView = (ViewGroup)FindViewById(Resource.Id.container);


rootView.AddView(chartView);
 

Here's the result:

1895
Telerik UI for Xamarin

Customization
AreaSeries extend CategoricalStrokedSeries which provides the following way to change their style:

 StrokeColor: changes the color used to draw lines.


 StrokeThickness: changes the width of the lines.

Additionally, AreaSeries can change the color of their fill with the FillColor property.

You can also customize the appearance of AreaSeries by using Palettes.

1896
Telerik UI for Xamarin

ChartView for Xamarin.Android: SplineAreaSeries


RadCartesianChartView visualizes SplineAreaSeries as an area on the chart that is enclosed by the
coordinate axes and curved line segments that connect the data points represented by these series.
The SplineAreaSeries extend AreaSeries, so they are also CategoricalSeries and require one
CategoricalAxis and one LinearAxis.

Example
You can read from the Getting Started page how to define the MonthResult type and declare the
initData() method.

After you create the method for initialization of sample data, you can create a
RadCartesianChartView with SplineAreaSeries by adding the following code to the onCreate()
method of your Activity.

C#
InitData();

RadCartesianChartView chartView = new RadCartesianChartView(this);

SplineAreaSeries splineAreaSeries = new SplineAreaSeries();


splineAreaSeries.CategoryBinding = new MonthResultDataBinding ("Month");
splineAreaSeries.ValueBinding = new MonthResultDataBinding ("Result");
splineAreaSeries.Data = (Java.Lang.IIterable)this.monthResults;
chartView.Series.Add(splineAreaSeries);

CategoricalAxis horizontalAxis = new CategoricalAxis();


chartView.HorizontalAxis = horizontalAxis;

LinearAxis verticalAxis = new LinearAxis();


chartView.VerticalAxis = verticalAxis;

ViewGroup rootView = (ViewGroup)FindViewById(Resource.Id.container);


rootView.AddView(chartView);
 

This example assumes that your root container has id container


 
Here's the result:

1897
Telerik UI for Xamarin

Customization
SplineAreaSeries extend AreaSeries, so they provide the same way to change their style — by using
the following properties:

 StrokeColor: changes the color used to draw lines.


 StrokeThickness: changes the width of the lines.
 FillColor: changes the color used to fill the area shapes.

You can also customize the appearance of AreaSeries by using Palettes.

1898
Telerik UI for Xamarin

ChartView for Xamarin.Android: BarSeries


RadCartesianChartView visualizes each data point from the BarSeries as a rectangle. These
rectangles (or bars) can be displayed either horizontally, or vertically, depending on whether the
CategoricalAxis is the vertical axis or the horizontal. When the horizontal axis is categorical, the
rectangles are displayed vertically. This means that they have equal width while their height
represents the numerical value of each of the data points. On the other hand, when the vertical axis
is categorical, the rectangles have equal height, while their width represents the value of the data
point. The BarSeries extend CategoricalSeries and require one CategoricalAxis and one LinearAxis.

Example
You can read from the Getting Started page how to define the MonthResult type and declare the
initData() method.

After you create the method for initialization of sample data, you can create a
RadCartesianChartView with BarSeries by adding the following code to the onCreate() method of
your Activity.

C#
InitData();

RadCartesianChartView chartView = new RadCartesianChartView(this);

BarSeries barSeries = new BarSeries();


barSeries.CategoryBinding = new MonthResultDataBinding ("Month");
barSeries.ValueBinding = new MonthResultDataBinding ("Result");
barSeries.Data = (Java.Lang.IIterable)this.monthResults;
chartView.Series.Add(barSeries);

CategoricalAxis horizontalAxis = new CategoricalAxis();


chartView.HorizontalAxis = horizontalAxis;

LinearAxis verticalAxis = new LinearAxis();


chartView.VerticalAxis = verticalAxis;

ViewGroup rootView = (ViewGroup)FindViewById(Resource.Id.container);


rootView.AddView(chartView);
 

Here's the result:

1899
Telerik UI for Xamarin

Properties and customization


Rounded edges
The bars that are used to represent the data points in BarSeries can have their corners rounded.
This can be achieved by using the AreBarsRounded property. When the value that is set is true,
the corners are rounded. The rounding radius can be checked and modified by using the
RoundBarsRadius. If you try to set a negative value, an IllegalArgumentException will be
thrown. Here's an example of BarSeries when their round bar radius is set to 10:

C#

1900
Telerik UI for Xamarin

barSeries.AreBarsRounded = true;
barSeries.RoundBarsRadius = 10;
 

And here's the result:

Customization
BarSeries provide the following way to change their style:

 StrokeColor: changes the color used to draw lines around the bars.

1901
Telerik UI for Xamarin

 StrokeWidth: changes the width of the lines around the bars.


 FillColor: changes the color used to fill the bar shapes.

You can also customize the appearance of BarSeries by using Palettes.

1902
Telerik UI for Xamarin

ChartView for Xamarin.Android: RangeBarSeries


RadCartesianChartView visualizes each data point from the RangeBarSeries as a rectangle. These
rectangles (or bars) can be displayed either horizontally, or vertically, depending on whether the
CategoricalAxis is the vertical axis or the horizontal. When the horizontal axis is categorical, the
rectangles are displayed vertically. This means that they have equal width while their height
represents the difference between the numerical values of each of the data points. The low value is
the rectangle's start point, while the high value is the end point. On the other hand, when the vertical
axis is categorical, the rectangles have equal height, while their width represents the difference
between the values of the data point. The RangeBarSeries extend RangeSeriesBase and are also
require one CategoricalAxis and one LinearAxis.

Example
You can read from the Getting Started page how to define the MonthResult type and declare the
initData() method.

After you create the method for initialization of sample data, you can create a
RadCartesianChartView with RangeBarSeries by adding the following code to the onCreate()
method of your Activity. For the purposes of the example, we are going to use the Result property of
our data object for both low value and high value. In order to actually have different values so that
bars that are visible, we will multiply the original value by a constant and the product will be our high
value.

C#
InitData();

RadCartesianChartView chartView = new RadCartesianChartView(this);

RangeBarSeries rangeBarSeries = new RangeBarSeries();


rangeBarSeries.CategoryBinding = new MonthResultDataBinding ("Month");
rangeBarSeries.LowBinding = new MonthResultDataBinding ("Result");
rangeBarSeries.HighBinding = new MonthResultHighBinding ("Result");
rangeBarSeries.Data = (Java.Lang.IIterable)this.monthResults;
chartView.Series.Add(rangeBarSeries);

CategoricalAxis horizontalAxis = new CategoricalAxis();


chartView.HorizontalAxis = horizontalAxis;

LinearAxis verticalAxis = new LinearAxis();


chartView.VerticalAxis = verticalAxis;

ViewGroup rootView = (ViewGroup)FindViewById(Resource.Id.container);


rootView.AddView(chartView);

...

// Usually RangeBarSeries will be used with data, where each data item contains
// 2 values - one low and one high. However, since in this example we are using
// data items which have only one value, in order to display range bars, we can

1903
Telerik UI for Xamarin

// create another binding which will retrieve a value which is higher than the
// original.
class MonthResultHighBinding : MonthResultDataBinding {
public MonthResultHighBinding(string propertyName)
:base(propertyName) {
}
public override Java.Lang.Object GetValue (Java.Lang.Object p0)
{
return (double)base.GetValue (p0) * 4;
}
}
 

This example assumes that your root container has id container


 
Here's the result:

1904
Telerik UI for Xamarin

Properties and customization


Rounded edges
The bars that are used to represent the data points in RangeBarSeries can have their corners
rounded. This can be achieved by using the AreBarsRounded property. When the value that is set is
true, the corners are rounded. The rounding radius can be checked and modified by using the
RoundBarsRadius property. If you try to set a negative value, an IllegalArgumentException will
be thrown.

Here's how the RangeBarSeries look when their round bar radius is set to 10:

1905
Telerik UI for Xamarin

C#
rangeBarSeries.AreBarsRounded = true;
rangeBarSeries.RoundBarsRadius = 10;
 

And here's the result:

Customization
Similarly to BarSeries, RangeBarSeries provide the following way to change their style:

1906
Telerik UI for Xamarin

 StrokeColor: changes the color used to draw lines around the bars.
 StrokeWidth: changes the width of the lines around the bars.
 FillColor: changes the color used to fill the bar shapes.

You can also customize the appearance of RangeBarSeries by using Palettes.

1907
Telerik UI for Xamarin

ChartView for Xamarin.Android: PieSeries


RadPieChartView visualizes the PieSeries in the shape of a pie. Each data item is visually
represented by a pie slice. The ratio between the space consumed by each slice and the space
consumed by the whole chart is the same as the ratio between the value of the data point that it
represents and the total value of all data points in the series.

Example
You can read from the Getting Started page how to define the MonthResult type and declare the
initData() method.

After you create the method for initialization of sample data, you can create a RadPieChartView with
PieSeries by adding the following code to the onCreate() method of your Activity.

C#
InitData();

RadPieChartView chartView = new RadPieChartView(this);

PieSeries pieSeries = new PieSeries();

pieSeries.ValueBinding = new MonthResultDataBinding ("Result");


// The name binding is used in the legend to show what the given pie slice value
means.
pieSeries.NameBinding = new MonthResultDataBinding ("Name");
pieSeries.Data = (Java.Lang.IIterable)this.monthResults;
chartView.Series.Add(pieSeries);

ViewGroup rootView = (ViewGroup)FindViewById(Resource.Id.container);


rootView.AddView(chartView);
 

Here's the result:

1908
Telerik UI for Xamarin

Properties and customization


Radius Factor
Before the RadPieChartView instance is drawn, its radius needs to be calculated. By default the
radius is set to value so that the whole chart will fill the whole available space. Then the radius factor
is applied. The default value for the radius factor is 1.0. This means that the radius will remain to a
value significant to fill the entire space that is available for RadPieChartView. You can use the
RadiusFactor property in order to change it. For example, here's how to modify the radius factor, so
that the pie consumes only half of the available space:

C#
pieSeries.RadiusFactor = 0.5;
 

Angle Range
The default value of the angle range used to visualize the data from PieSeries is the range [0,
360]. If you want to change this, you can use the AngleRange property and specify a new range.
For example, here's how you can set a new range so that the data is presented in a semicircle:

C#
pieSeries.AngleRange = new AngleRange(0,180);
 

And this is the result:

1909
Telerik UI for Xamarin

Styles
The default colors used for PieSeries come from the default palette, you can change the palette as
described in this article or use the styles as demonstrated here

Slice Styles
The SliceStyle class allow you to create a set of stroke and fill colors which you can easily apply to
the slices in a pie chart. Here's one simple SliceStyle:

C#
SliceStyle style1 = new SliceStyle();
style1.FillColor = Color.Argb(255, 51, 181, 229);
style1.StrokeColor = Color.Argb(255, 0, 130, 173);
style1.StrokeWidth = 2;
style1.ArcColor = Color.White;
style1.ArcWidth = 2;
 

As you can see, you can modify the color of the fill of the segments, their stroke color and width and
additionally you can add an arc that is drawn between the stroke and the fill. Please note, that the
arc is drawn not around the whole segment but only on its arc. Once you have create a few styles,
you can add them in a List<SliceStyle> and set it to your PieSeries instance:

C#
List<SliceStyle> styles = new List<SliceStyle>();
styles.Add(style1);
pieSeries.SliceStyles = styles;
 

Here's the result when we add a collection of four styles similar to the one in the example:

1910
Telerik UI for Xamarin

Slice Offset
As you may have noticed, there is a thin line between the segments. You can change its width
through the SliceOffset property. If you set it to 0, the line will be removed:

C#
pieSeries.SliceOffset = 0;
 

1911
Telerik UI for Xamarin

ChartView for Xamarin.Android: DoughnutSeries


The DoughnutSeries class inherit from PieSeries and are also used to visualize series of data in a
RadPieChartView. The difference between adding DoughnutSeries compared to adding PieSeries is
that there will be a blank portion in center.

Example
You can read from the Getting Started page how to define the MonthResult type and declare the
initData() method.

After you create the method for initialization of sample data, you can create a RadPieChartView with
DoughnutSeries by adding the following code to the onCreate() method of your Activity.

C#
InitData();

RadPieChartView chartView = new RadPieChartView(this);

DoughnutSeries doughnutSeries = new DoughnutSeries();

doughnutSeries.ValueBinding = new MonthResultDataBinding ("Result");


doughnutSeries.Data = (Java.Lang.IIterable)this.monthResults;
chartView.Series.Add(doughnutSeries);

ViewGroup rootView = (ViewGroup)FindViewById(Resource.Id.container);


rootView.AddView(chartView);
 

Here's the result:

1912
Telerik UI for Xamarin

Properties and customization


The DoughnutSeries class inherit from PieSeries, so you can use the same customization options.
Additionally in DoughnutSeries, you can change the inner radius factor through InnerRadiusFactor
property. The default value that you will get initially is 0.5. This means that the radius of the blank
segment in the center will be half as long as the radius of the RadPieChartView instance.

The possible values for the inner radius factor are the values in the (0,1) interval.
 
Here's an example of how to enlarge the blank portion:

C#

1913
Telerik UI for Xamarin

doughnutSeries.InnerRadiusFactor = 0.85f;
 

And the result is:

Styles
The default colors used for DoughnutSeries come from the default palette, you can change the
palette as described in this article or use the styles as demonstrated here

Slice Styles
The SliceStyle class allow you to create a set of stroke and fill colors which you can easily apply to
the slices in a pie chart. Here's one simple SliceStyle:

1914
Telerik UI for Xamarin

C#
SliceStyle style1 = new SliceStyle();
style1.FillColor = Color.Argb(255, 51, 181, 229);
style1.StrokeColor = Color.Argb(255, 0, 130, 173);
style1.StrokeWidth = 2;
style1.ArcColor = Color.White;
style1.ArcWidth = 2;
 

As you can see, you can modify the color of the fill of the segments, their stroke color and width and
additionally you can add an arc that is drawn between the stroke and the fill. Please note, that the
arc is drawn not around the whole segment but only on its arc. Once you have create a few styles,
you can add them in a List<SliceStyle> and set it to your DoughnutSeries instance:

C#
List<SliceStyle> styles = new List<SliceStyle>();
styles.Add(style1);
doughnutSeries.SliceStyles = styles;
 

Here's the result when we add a collection of four styles similar to the one in the example:

1915
Telerik UI for Xamarin

Slice Offset
As you may have noticed, there is a thin line between the segments. You can change its width
through the SliceOffset property. If you set it to 0, the line will be removed:

C#
doughnutSeries.SliceOffset = 0;
 

1916
Telerik UI for Xamarin

ChartView for Xamarin.Android: Financial Series


The financial series are represented by the OhlcSeries and CandlestickSeries classes. They must be
added to RadCartesianChartView and the chart must be configured with a CategoricalAxis and a
NumericalAxis. Both financial series use OhlcDataPoint for data points internally and they only differ
in the way they visualize the data point. OHLC stands for Open, High, Low and Close.

A more detailed explanation of an OHLC and a Candlestick chart can be found here and here
respectively. To populate a financial series with data developers need to set five bindings in
contrastwith only two for a BarSeries for example. Like any categorical series both financial series
need a category binding. In addition they need bindings for the financial components. These are an
open binding, a high binding, a low binding and a close binding.

Example
To initialize a sample financial chart the following code can be used:

C#
RadCartesianChartView chartView = new RadCartesianChartView(this);

CandlestickSeries series = new CandlestickSeries();


series.CategoryBinding = new OhlcDataBinding("category");
series.OpenBinding = new OhlcDataBinding("open");
series.HighBinding = new OhlcDataBinding("high");
series.LowBinding = new OhlcDataBinding("low");
series.CloseBinding = new OhlcDataBinding("close");

series.Data = (Java.Lang.IIterable)this.GenerateOhlcData();
chartView.Series.Add(series);

CategoricalAxis horizontalAxis = new CategoricalAxis();


chartView.HorizontalAxis = horizontalAxis;

LinearAxis verticalAxis = new LinearAxis();


chartView.VerticalAxis = verticalAxis;

ViewGroup rootView = (ViewGroup)this.FindViewById(Resource.Id.container);


rootView.AddView(chartView);
 

Here are also the OhlcData class and the GenerateOhlcData() method:

C#
public class OhlcData : Java.Lang.Object {
public String category;
public int open;
public int high;
public int low;
public int close;

1917
Telerik UI for Xamarin

private Java.Util.ArrayList GenerateOhlcData() {


Random r = new Random();
Java.Util.ArrayList data = new Java.Util.ArrayList();
int size = 10;

for (int i = 1; i <= size; ++i) {


OhlcData ohlc = new OhlcData();
ohlc.category = i.ToString();
ohlc.high = r.Next(100);
if (ohlc.high < 2) {
ohlc.high = 2;
}

ohlc.low = r.Next(ohlc.high - 1);


ohlc.open = ohlc.low + r.Next(ohlc.high - ohlc.low);
ohlc.close = ohlc.low + r.Next(ohlc.high - ohlc.low);

data.Add(ohlc);
}

return data;
}

class OhlcDataBinding : DataPointBinding {

private string propertyName;

public OhlcDataBinding(string propertyName)


{
this.propertyName = propertyName;
}

public override Java.Lang.Object GetValue (Java.Lang.Object p0)


{
switch (propertyName) {
case "category":
return ((OhlcData)(p0)).category;
case "open":
return ((OhlcData)(p0)).open;
case "high":
return ((OhlcData)(p0)).high;
case "low":
return ((OhlcData)(p0)).low;
case "close":
return ((OhlcData)(p0)).close;
}
return null;
}
}
 

1918
Telerik UI for Xamarin

Finally, here's the result:

The OhlcSeries class is identical in terms of usage and initialization.


 

Customization
You can also customize the appearance of the financial series by using palettes.

1919
Telerik UI for Xamarin

ChartView for Xamarin.Android: Financial Indicators


RadCartesianChartView visualizes each data item from the Indicator Series using a LineRenderer.
The Indicator Series extend CartesianSeries and they require one CategoricalAxis and one
LinearAxis.

Overview
The financial, or also called stock indicators, are mainly used for keeping track of stock prices and
patterns of price changes over time. You can find further information about what indicators are and
what they are being used for by following this link: Short information about financial indicators.

In terms of using the indicators in the RadCartesianChartView you will need to add them as you
would add any other Cartesian series. Every indicator has a related formula by which it calculates
the expected result. All you need to do is provide the needed data.

There are two types of indicators in terms of setting their properties and getting them ready for
displaying your stock data:

1. Indicators that have a category and a value(usually the close) bindings as well as one or
more periods.
2. Indicators that have a category and high/low/close value bindings as well as none, one, or
more periods.

There are some special cases which will be reviewed separately.

Examples
The following examples will cover the common settings for every type as well as state the specific
differences that some indicators require.

All the examples expect you to provide your own ohlc data. The class used in the examples is as
follows:

C#
public class FinancialDataClass : Java.Lang.Object {

public float open;


public float high;
public float low;
public float close;
public float volume;

public Java.Util.Calendar date;

public FinancialDataClass(
Java.Util.Calendar date,
float open, float high, float low, float close,

1920
Telerik UI for Xamarin

float volume) {

this.open = open;
this.high = high;
this.low = low;
this.close = close;
this.date = date;
this.volume = volume;
}
}
 

First type
Indicators from the first type are: ExponentialMovingAverageIndicator,
ModifiedExponentialMovingAverageIndicator, ModifiedMovingAverageIndicator, MomentumIndicator,
MovingAverageIndicator, RateOfChangeIndicator, RelativeStrengthIndexIndicator, TrixIndicator,
WeightedMovingAverageIndicator, AdaptiveMovingAverageKaufmanIndicator,
BollingerBandsIndicator, RelativeMomentumIndexIndicator, MacdIndicator, OscillatorIndicator,
RaviIndicator

Initializing any of these is the same, so the next example shows the process with only one of them:

C#
MovingAverageIndicator indicator = new MovingAverageIndicator();
indicator.Period = 5;
indicator.CategoryBinding = new OhlcDataBinding("category");
indicator.ValueBinding = new OhlcDataBinding("close");
indicator.Data = (Java.Lang.IIterable)this.GenerateOhlcData();
chartView.Series.Add(indicator);
 

The rest of the indicators from this category will need the same settings, but will behave accordingly
to their own algorithms.

Exceptions in this category are in the following indicators:

1. AdaptiveMovingAverageKaufmanIndicator needs to have setSlowPeriod(int); and


setFastPeriod(int);.
2. BollingerBandsIndicator needs setStandardDeviations(int).
3. RelativeMomentumIndexIndicator needs setMomentumPeriod(int);.
4. MacdIndicator needs setLongPeriod(int);, setShortPeriod(int); and setSignalPeriod(int);
5. OscillatorIndicator needs setLongPeriod(int); and setShortPeriod(int);
6. RaviIndicator needs setLongPeriod(int); and setShortPeriod(int);

Second type
Indicators of the second type are: AverageTrueRangeIndicator, CommodityChannelIndexIndicator,
StochasticFastIndicator, StochasticSlowIndicator, TrueRangeIndicator, UltimateOscillatorIndicator

All indicators from the second type are binded to multiple values, instead of just one value(close).

1921
Telerik UI for Xamarin

Some of them have multiple periods, some use one and some use no periods. The initialization for
all of them includes setting the proper bindings:

C#
TrueRangeIndicator indicator = new TrueRangeIndicator();
indicator.CategoryBinding = new OhlcDataBinding("category");
indicator.CloseBinding = new OhlcDataBinding("close");
indicator.HighBinding = new OhlcDataBinding("high");
indicator.LowBinding = new OhlcDataBinding("low");
chartView.Series.Add(indicator);
 

This will be enough for setting a TrueRangeIndicator, since it doesn't use a period. Every other
indicator from this category will need some additional period settings as follows:

1. StochasticFastIndicator needs setMainPeriod(int); and setSignalPeriod(int);


2. StochasticSlowIndicator needs setMainPeriod(int);, setSignalPeriod(int); and
setSlowPeriod(int);
3. AverageTrueRangeIndicator needs setPeriod(int);
4. CommodityChannelIndexIndicator needs setPeriod(int);
5. UltimateOscillatorIndicator needs setPeriod(int);, setPeriod2(int); and setPeriod3(int);

Full example code


Here are two indicators in action:

And here is the code for the example:

1922
Telerik UI for Xamarin

C#
RadCartesianChartView chart = new RadCartesianChartView(this);

// This example assumes that your root container has id `container`


ViewGroup rootView = (ViewGroup)this.FindViewById(Resource.Id.container);
rootView.AddView(chart);

DateTimeCategoricalAxis horizontalAxis = new DateTimeCategoricalAxis();


horizontalAxis.DateTimeFormat = new SimpleDateFormat("MM/dd");
horizontalAxis.DateTimeComponent = DateTimeComponent.Date;
horizontalAxis.LabelFitMode = AxisLabelFitMode.Rotate;

LinearAxis verticalAxis = new LinearAxis();

DataPointBinding categoryBinding = new OhlcDataBinding("date");


DataPointBinding openBinding = new OhlcDataBinding("open");
DataPointBinding highBinding = new OhlcDataBinding("high");
DataPointBinding lowBinding = new OhlcDataBinding("low");
DataPointBinding closeBinding = new OhlcDataBinding("close");

Java.Lang.IIterable data = (Java.Lang.IIterable)this.GenerateOhlcData ();

CandlestickSeries series = new CandlestickSeries();


series.CategoryBinding = categoryBinding;
series.OpenBinding = openBinding;
series.HighBinding = highBinding;
series.LowBinding = lowBinding;
series.CloseBinding = closeBinding;
series.Data = data;

BollingerBandsIndicator bollingerBands = new BollingerBandsIndicator();


bollingerBands.CategoryBinding = categoryBinding;
bollingerBands.ValueBinding = closeBinding;
bollingerBands.Period = 5;
bollingerBands.StandardDeviations = 2;
bollingerBands.Data = data;

MovingAverageIndicator movingAverage = new MovingAverageIndicator();


movingAverage.CategoryBinding = categoryBinding;
movingAverage.ValueBinding = closeBinding;
movingAverage.Period = 5;
movingAverage.Data = data;

chart.VerticalAxis = verticalAxis;
chart.HorizontalAxis = horizontalAxis;
chart.Series.Add(series);
chart.Series.Add(bollingerBands);
chart.Series.Add(movingAverage);

...

private Java.Util.ArrayList GenerateOhlcData() {


Random r = new Random();

1923
Telerik UI for Xamarin

Java.Util.ArrayList data = new Java.Util.ArrayList();


int size = 10;

for (int i = 1; i <= size; ++i) {


OhlcData ohlc = new OhlcData();
ohlc.category = i.ToString();
ohlc.high = r.Next(100);
if (ohlc.high < 2) {
ohlc.high = 2;
}

ohlc.date = new Java.Util.GregorianCalendar (2014, 9, i);


ohlc.low = r.Next(ohlc.high - 1);
ohlc.open = ohlc.low + r.Next(ohlc.high - ohlc.low);
ohlc.close = ohlc.low + r.Next(ohlc.high - ohlc.low);

data.Add(ohlc);
}

return data;
}

class OhlcDataBinding : DataPointBinding {

private string propertyName;

public OhlcDataBinding(string propertyName)


{
this.propertyName = propertyName;
}

public override Java.Lang.Object GetValue (Java.Lang.Object p0)


{
switch (propertyName) {
case "category":
return ((OhlcData)(p0)).category;
case "open":
return ((OhlcData)(p0)).open;
case "high":
return ((OhlcData)(p0)).high;
case "low":
return ((OhlcData)(p0)).low;
case "close":
return ((OhlcData)(p0)).close;
case "date":
return ((OhlcData)(p0)).date;
}
return null;
}
}
 

Customization

1924
Telerik UI for Xamarin

Financial Indicators are using a LineRenderer which makes them LineSeries, that simply have a
different algorithm when it comes to handling data points. They can be styled the same way you
would style a LineSeries. The default palette styles are still being applied if not overridden by the
user.

You can also customize the appearance of Financial Series by using Palettes.

1925
Telerik UI for Xamarin

ChartView for Xamarin.Android: ScatterPointSeries


RadCartesianChartView visualizes each data item from the ScatterPointSeries as individual points
on the plot area. ScatterPointSeries like all other scatter series require two numerical axes to
function properly.

All scatter series are incompatible with all categorical axes.

Example
To create a chart with scatter series you need to create a chart object, add horizontal and vertical
axes and add a scatter series object populated with data. It must be noted that the chart must have a
LinearAxis set for both the horizontal and vertical axes.

Immediately below is the implementation of the initScatterData() method which is used to populate
the scatter series with data along with the ScatterPoint class which serves as the actual chart data.

C#
public class ScatterPoint : Java.Lang.Object
{
public ScatterPoint(int x, int y)
{
this.X = x;
this.Y = y;
}

public int X { get; set; }

public int Y { get; set; }


}

public Java.Lang.IIterable InitScatterData()


{
Java.Util.ArrayList data = new Java.Util.ArrayList ();
Random random = new Random();
for(int i = 0; i < 20; ++i)
{
data.Add(new ScatterPoint(random.Next(50), random.Next(50)));
}

return data;
}
 

After you create the method for initialization of sample data, you can create a
RadCartesianChartView with ScatterPointSeries by adding the following code to the onCreate()
method of your Activity.

C#

1926
Telerik UI for Xamarin

RadCartesianChartView chartView = new RadCartesianChartView(this);

ScatterPointSeries scatterSeries = new ScatterPointSeries();


scatterSeries.XValueBinding = new MonthResultDataBinding("X");
scatterSeries.YValueBinding = new MonthResultDataBinding("Y");
scatterSeries.Data = InitScatterData();
chartView.Series.Add(scatterSeries);

LinearAxis horizontalAxis = new LinearAxis();


chartView.HorizontalAxis = horizontalAxis;

LinearAxis verticalAxis = new LinearAxis();


chartView.VerticalAxis = verticalAxis;

ViewGroup rootView = (ViewGroup)FindViewById(Resource.Id.container);


rootView.AddView(chartView);
 

Here's the result:

1927
Telerik UI for Xamarin

Customization
ScatterPointSeries provide the following API to change their style:

 StrokePaint (of type Paint): changes the color used to draw points' stroke.
 FillPaint (of type Paint): changes the fill of the scatter points.

You can also customize the appearance of ScatterPointSeries by using Palettes.

1928
Telerik UI for Xamarin

ChartView for Xamarin.Android: ScatterBubbleSeries


RadCartesianChartView visualizes each data item from the ScatterBubbleSeries as individual
bubbles on the plot area where each bubble has an individual size. The size is measured in pixels
and represents the area of the bubble. ScatterBubbleSeries like all other scatter series require two
numerical axes to function properly. All scatter series are incompatible with all categorical axes.

ScatterBubbleSeries are initialized much like ScatterPointSeries with only one addition: a bubble
size binding that will tell the series how big each point should be. The number provided by the data
source should be the area of the bubble in pixels. More often than not the data will not have this
exact property so you will need to use a GenericDataPointBinding object in order to translate the
incoming data to the bubble size.For more details on the base ScatterPointSeries configuration see
ScatterPointSeries topic.

Example
C#
public class ScatterBubblePoint : ScatterPoint
{
public ScatterBubblePoint(int x, int y, int area) : base(x, y)
{
this.Area = area;
}

public int Area { get; set; }


}

public IIterable InitScatterBubbleData() {


ArrayList data = new ArrayList();
Random random = new Random();
for(int i = 0; i < 20; ++i) {
data.Add(new ScatterBubblePoint(random.Next(50), random.Next(50),
random.Next(5000)));
}

return data;

public class BubbleDataPointBinding : DataPointBinding


{
public override Java.Lang.Object GetValue(Java.Lang.Object dataItem)
{
return ((ScatterBubblePoint)dataItem).Area;
}
}
 

Now with the bubble data initialization in place we can create our chart.

1929
Telerik UI for Xamarin

C#
RadCartesianChartView chartView = new RadCartesianChartView(this);

ScatterBubbleSeries scatterSeries = new ScatterBubbleSeries();


scatterSeries.XValueBinding = new MonthResultDataBinding("X");
scatterSeries.YValueBinding = new MonthResultDataBinding("Y");

// If the incoming data does not contain information about the bubble area, the lambda
expression is a good place to calculate it.
scatterSeries.BubbleSizeBinding = new BubbleDataPointBinding();
scatterSeries.Data = InitScatterBubbleData();
chartView.Series.Add(scatterSeries);

LinearAxis horizontalAxis = new LinearAxis();


chartView.HorizontalAxis = horizontalAxis;

LinearAxis verticalAxis = new LinearAxis();


chartView.VerticalAxis = verticalAxis;

ViewGroup rootView = (ViewGroup)FindViewById(Resource.Id.container);


rootView.AddView(chartView);
 

Here's the result:

1930
Telerik UI for Xamarin

Customization
The ScatterBubbleSeries class exposes only one property and it is called BubbleScale. You can use
BubbleScale to set a multiplier with which the radius of the bubble will be multiplied immediately
before rendering.

C#
scatterBubbleSeries.BubbleScale = 1000;
 

You can also customize the appearance of ScatterBubbleSeries by using Palettes.

1931
Telerik UI for Xamarin

ChartView for Xamarin.Android: RadCartesianChartView


RadCartesianChartView is one of the RadChartView types. This chart visualizes its data points using
the Cartesian coordinate system. The X and Y axes define how the coordinates of each point in the
plot area are calculated and the series type define the way these data points will be visualized.

Supported Series
RadCartesianChartView can visualize the following types of series:

 LineSeries: Visualizes a collection of data points using a Line.


 SplineSeries: Visualizes a collection of data points using a Curve.
 AreaSeries: Represents a chart series that are visualized like an area figure in the Cartesian
space.
 SplineAreaSeries: Represents series which define an area with smooth curves among points.
 BarSeries: Represents a chart series that plot their points using rectangular shapes, named
"Bars". RadCartesianChartView can display BarSeries both horizontally and vertically. If the
series are more than one, they can be stacked.
 RangeBarSeries: Represents a chart range bar series. Both BarSeries and RangeBarSeries
display its data points as bars. However the bars in BarSeries represent just a single value
and the bars in RangeBarSeries represent low value and high value.

Supported Axes
RadCartesianChartView needs to have two axes which will be used to calculate correctly the

1932
Telerik UI for Xamarin

position of each data point. Usually one of the axes will be used to display the category of each data
point and the other will represent its value. Here are the supported axes:

 Category Axes
 CategoricalAxis: Arranges the plotted data points in categories where the key of each
category is the point's value (if available) for that axis or its index within the points
collection. The point's coordinate, specified by this axis is discrete and is calculated
depending on the size of the category slot where the point resides.
 DateTimeCategoricalAxis: This is a special categorical axis that expects each data point
to provide a java.util.Calendar structure as its value for this axis. The points are
grouped by a user-defined date-time component (Year, Month, Day, etc.) and then the
groups are sorted chronologically.
 DateTimeContinuousAxis: This is a special axis that expects each data point to provide a
java.util.Calendar structure as its value for this axis. You can think of
DateTimeContinuousAxis as a timeline where the coordinate of each data point is
calculated depending on the position of its associated DateTime on the timeline. The
base unit (or the timeline step) of the axis is calculated depending on the smallest
difference between any two dates.
 Value Axes
 LinearAxis: Calculates the coordinate of each data point, depending on the actual
numerical value this point provides for the axis. A LinearAxis exposes Minimum and
Maximum properties to allow for explicit definition of the range of values visible on this
axis. If these properties are not specified, the axis will automatically calculate the range,
depending on the minimum and maximum data point values.
 LogarithmicAxis: Special linear axis that will transform each data point value using the
logarithm function. Using LogarithmicAxis allows your app to show numerical data with
huge delta between the minimum and the maximum to be visualized in a readable way.

Create RadCartesianChartView from scratch


In order to create a new instance of RadCartesianChartView you can follow the instructions from the
Getting Started page of RadChartView.

1933
Telerik UI for Xamarin

ChartView for Xamarin.Android: RadPieChartView


RadPieChartView is one of the RadChartView types. This chart visualizes its data points using radial
coordinate system. Each data point is represented as a slice from a pie. The ratio between the space
consumed by each slice and the space consumed by the whole chart is the same as the ratio
between the value of the data point that it represents and the total value of all data points in the
series.

Supported Series
RadPieChartView can visualize the following types of series:

 PieSeries: The PieSeries are used to visualize a single series of data in a pie chart. The
sweep of a pie's slices is directly proportional to the magnitude of the data points' values.
 DoughnutSeries: The DoughnutSeries extend PieSeries. When the RadPieChartView
visualizes the data from DoughnutSeries, it leaves a blank segment in the center.

Create RadPieChartView from scratch


Creating a new pie chart is very similar to creating a new Cartesian chart. Again we will need to
initialize the data that we will use to visualize:

C#
private Java.Util.ArrayList monthResults;

private void InitData() {


monthResults = new Java.Util.ArrayList();
monthResults.Add(new MonthResult("Jan", 12));

1934
Telerik UI for Xamarin

monthResults.Add(new MonthResult("Feb", 5));


monthResults.Add(new MonthResult("Mar", 10));
monthResults.Add(new MonthResult("Apr", 7));
}

public class MonthResult : Java.Lang.Object {

public double Result { get; set; }


public String Month { get; set; }

public MonthResult(String month, double result) {


this.Month = month;
this.Result = result;
}
}

class MonthResultDataBinding : DataPointBinding {

private string propertyName;

public MonthResultDataBinding(string propertyName)


{
this.propertyName = propertyName;
}

public override Java.Lang.Object GetValue (Java.Lang.Object p0)


{
if(propertyName == "Month")
{
return ((MonthResult)(p0)).Month;
}
return ((MonthResult)(p0)).Result;
}
}
 

And inside the activity that will visualize the chart, we need to find a container and create a new chart
instance. RadPieChartView doesn't have any axes, so you need to simply add series:

C#
InitData();

RadPieChartView chartView = new RadPieChartView(this);

PieSeries pieSeries = new PieSeries();

pieSeries.ValueBinding = new MonthResultDataBinding ("Result");


pieSeries.Data = (Java.Lang.IIterable)this.monthResults;
chartView.Series.Add(pieSeries);

ViewGroup rootView = (ViewGroup)FindViewById(Resource.Id.container);


rootView.AddView(chartView);
 

1935
Telerik UI for Xamarin

ChartView for Xamarin.Android: Labels


In this article, you will learn to use the labels in RadChartView for Android: how to use the labels for
the series and for the axes and how to customize them.

Series Labels
All series have their default labels. In order to display them, you simply need to set show labels of
the series to true:

C#
series.ShowLabels = true;
 

Axes Labels
All axes have their default labels. They are visible by default. In order to hide them, you simply need
to set show labels of the axis to false:

C#
axis.ShowLabels = false;
 

Customization
All axes and series have properties which provide various customization options for the labels:

 LabelTextColor(Android.Graphics.Color): specifies the color of the label text;


 LabelFillColor(Android.Graphics.Color): sets the background color of the labels;
 LabelStrokeColor(Android.Graphics.Color): sets the border color of the labels;
 LabelSize(float): sets the size of the labels;
 LabelMargin(float): specifies the margins of the labels;
 LabelFont(Android.Graphics.Typeface): determines the font of the labels;
 LabelFormat: specifies the format string of the labels.

Additionally, you can provide a custom label render in order to completely change the way the labels
are rendered. In order to set the renderer you need to use the LabelRenderer of type
BaseLabelRenderer property.

Here's an excerpt from a custom label renderer:

C#
class CustomLabelRenderer : BaseLabelRenderer {

private String labelFormat = "{0}";


private TextPaint paint = new TextPaint();

1936
Telerik UI for Xamarin

private Paint strokePaint = new Paint();


private Paint fillPaint = new Paint();
private float labelMargin = 10.0f;
private float labelPadding = 20.0f;

public CustomLabelRenderer(ChartSeries owner)


:base(owner) {

this.strokePaint.SetStyle(Paint.Style.Stroke);
this.strokePaint.Color = Color.White;
this.strokePaint.StrokeWidth = 2;

this.fillPaint.Color = Color.ParseColor("#F5413F");
this.paint.TextSize = 35.0f;
this.paint.Color = Color.White;
}

public override void RenderLabel (Canvas canvas,


Com.Telerik.Widget.Chart.Engine.ElementTree.ChartNode relatedLabelNode) {

CategoricalDataPoint dataPoint =
relatedLabelNode.JavaCast<CategoricalDataPoint>();

RadRect dataPointSlot = dataPoint.LayoutSlot;


Double val = dataPoint.Value;
String labelText = String.Format(this.labelFormat, (int)val);

StaticLayout textInfo = this.CreateTextInfo(labelText, dataPoint);


this.RenderLabel(canvas, dataPointSlot, labelText, textInfo);
}

private StaticLayout CreateTextInfo(String labelText,


CategoricalDataPoint dataPoint) {

return new StaticLayout(labelText,


0,
labelText.Length,
this.paint,
(int)Math.Round((float) dataPoint.LayoutSlot.Width),
Layout.Alignment.AlignCenter,
1.0f,
1.0f,
false);
}

private void RenderLabel(Canvas canvas, RadRect dataPointSlot,


String labelText, StaticLayout textBounds) {

RectF labelBounds = new RectF();


float height = textBounds.Height + this.labelPadding * 2;
float top = (float) dataPointSlot.GetY() - this.labelMargin - height;

labelBounds.Set(
(float) dataPointSlot.GetX(),

1937
Telerik UI for Xamarin

top,
(float) dataPointSlot.Right,
top + height);

canvas.DrawRect(
labelBounds.Left,
labelBounds.Top,
labelBounds.Right,
labelBounds.Bottom,
this.fillPaint);

canvas.DrawRect(
labelBounds.Left,
labelBounds.Top,
labelBounds.Right,
labelBounds.Bottom,
this.strokePaint);

canvas.DrawText(
labelText,
(float) dataPointSlot.GetX() + (float) (dataPointSlot.Width / 2.0) -
textBounds.GetLineWidth(0) / 2.0f,
labelBounds.CenterY() + textBounds.GetLineBottom(0) -
textBounds.GetLineBaseline(0),
paint);
}
}
 

And the result:

1938
Telerik UI for Xamarin

1939
Telerik UI for Xamarin

ChartView for Xamarin.Android: Legend


In this article, you will learn to use the built-in legend in RadChartView for Android.

Overview
You can start from the BarSeries example and add a second instance of the BarSeries with stack
combine mode. Then you need to set their legend title and create a new instance of
RadLegendView. RadLegendView needs a legend provider which will provide the data. You can use
RadCartesianChartView as a LegendProvider:

C#
barSeries1.CombineMode = ChartSeriesCombineMode.Stack;
barSeries2.CombineMode = ChartSeriesCombineMode.Stack;

barSeries1.LegendTitle = "first";
barSeries2.LegendTitle = "second";

RadLegendView legendView = new RadLegendView (this);


legendView.LegendProvider = chartView;

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(460,100);


layoutParams.SetMargins(10,10,10,10);
legendView.LayoutParameters = layoutParams;

LinearLayout linearLayout = new LinearLayout(this);


linearLayout.Orientation = Android.Widget.Orientation.Vertical;

linearLayout.AddView(legendView);
linearLayout.AddView(chartView);

ViewGroup rootView = (ViewGroup)FindViewById(Resource.Id.container);


rootView.AddView(linearLayout);
 

Here's the result:

1940
Telerik UI for Xamarin

The legend for the pie chart is a little bit different. The pie series does not have a legend title
because each point in the series means something different, the title is taken from the data points
with a name binding. For example:

C#
PieSeries series = new PieSeries();

// This assumes that the data models have a property with the signature public string
Name { get; }.
series.NameBinding = new PropertyNameDataPointBinding("Name");
 

Orientation

1941
Telerik UI for Xamarin

The default behavior of the RadLegendView is to show the legend items vertically. However you can
change the orientation of the items to horizontal with LegendOrientation property:

C#
legendView.LegendOrientation = OrientationHelper.Horizontal;
 

The possible values for the orientation are:

 OrientationHelper.Horizontal
 OrientationHelper.Vertical

Scrolling
By default the scroll of the legend items is disabled. In order to enable the horizontal and vertical
scroll you can use:

C#
legendView.SetCanScrollHorizontally(true);
legendView.SetCanScrollVertically(true);
 

Selection
RadLegendView supports selection by setting the AllowSelection property to true.

C#
legendView.AllowSelection = true;
 

The LegendItemSelected event can be used to determine the selected LegendItem.

C#
private void LegendViewOnLegendItemSelected(object sender, LegendSelectionEventArgs e)
{
var title = (e.P0 as LegendItem)?.Title;
}
 

1942
Telerik UI for Xamarin

DataForm for Xamarin.Android: Overview


RadDataForm for Xamarin.Android is an editing component that allows editing of any object at
run-time. The component automatically generates editors for the different public properties exposed
by the object being edited.

1943
Telerik UI for Xamarin

DataForm for Xamarin.Android: Getting Started


To use RadDataForm you will need to add the following Telerik references:

 Telerik.Xamarin.Android.Input
 Telerik.Xamarin.Android.Common

Then it's just a matter of creating a new RadDataForm instance, adding it to the Android UI tree and
providing an object to edit. For example:

C#
RadDataForm form = new RadDataForm(context);
form.SetEntity(new Person());

layout.AddView(form);
 

Here's the Person class:

C#
public class Person : Java.Lang.Object
{
[DataFormProperty(Label = "Age", Index = 1)]
public int Age
{
get;
set;
}

[DataFormProperty(Label = "Employee Type", Index = 4)]


public EmployeeType EmployeeType
{
get;
set;
}

[DataFormProperty(Label = "Name", Index = 0)]


public string Name
{
get;
set;
}

[DataFormProperty(Label = "E-mail", Index = 2)]


public string Mail
{
get;
set;
}

1944
Telerik UI for Xamarin

[DataFormProperty(Label = "Employed", Index = 3)]


public bool IsEmployed
{
get;
set;
}
}
public enum EmployeeType
{
PROGRAMMER,
MANAGER,
SUPPORT,
MARKETING
}
 

Now the data form should be ready to edit the fields of the person object:

To learn more about the @DataFormProperty annotation see the page about property metadata.

Editing JSON Objects


You can also use RadDataForm to edit Json Objects. For example, if you have the Person details in
a json file with the following content:

{
"name": "John Doe",
"age": 21,
"email": "john.doe@example.com"

1945
Telerik UI for Xamarin

}
 

You can edit it through RadDataForm like this:

C#
// The file Person.json is in the Assets folder of the project
String json = LoadJSONFromAsset ("Person.json");
try {
JSONObject jsonObject = new JSONObject (json);
dataForm.SetEntity(jsonObject);
} catch(JSONException e) {
Log.Error ("json", "error parsing json", e);
}
 

The loadJSONFromAsset simply returns the content of file with given name. Here's one sample
implementation:

C#
private String LoadJSONFromAsset(String fileName)
{
String json = null;
try
{
using (StreamReader sr = new StreamReader (Activity.Assets.Open (fileName)))
{
json = sr.ReadToEnd ();
}
}
catch (IOException ex)
{
Log.Error("error", ex.StackTrace);
}
return json;
}
 

1946
Telerik UI for Xamarin

DataForm for Xamarin.Android: Features


Editors
RadDataForm is used for editing the properties of an object. For example if a Person class has a
field that stores the age of the person, it should have a public getter and setter with the following
signature:

C#
public int Age {
get;
set;
}
 

If the property only has a getter, the property will be read-only and a property viewer will be created
instead of a property editor. If a field only has a setter it will be ignored by RadDataForm.

RadDataForm supports the basic data types for editing out of the box - these include text, date and
time, booleans, enums and numbers. For custom types RadDataForm provides means for creating a
custom editor. Also, the basic editors can be replaced by custom editors whenever necessary.

RadDataForm has a priority list when it decides which editor to show for a given property or type:

1. If the developer has defined an editor with the [property


metadata](/devtools/xamarin/nativecontrols/android/dataform/dataform-metadata "Read
more about the data form metadata.") for their object it will be used first.
2. If the metadata does not define an editor, a special callback (editor provider) will be
attempted next. The callback is a function that accepts an EntityProperty and returns an
EntityPropertyEditor. For example:

C#
dataForm.Adapter.SetEditorProvider(new EditorProviderImpl(dataForm));

public class EditorProviderImpl : Java.Lang.Object, IFunction {


RadDataForm dataForm;
public EditorProviderImpl(RadDataForm dataForm) {
this.dataForm = dataForm;
}

public Java.Lang.Object Apply(Java.Lang.Object argument) {


XamarinEntityProperty property = (XamarinEntityProperty)argument;
if(property.OriginalType == typeof(System.Boolean)) {
return new DataFormSwitchEditor(dataForm, property);
}

return null;
}
}

1947
Telerik UI for Xamarin

The sample callback above replaces the default checkbox editor for booleans with the switch
editor. For other types and properties it returns null. When the data form adapter gets null
from this callback it proceeds with the remaining options for editor resolution.

3. The next option is the **editor registry**. The registry contains pre-defined editors for
properties and types. First it looks if it has an editor for the specific property provided. If it
doesn't it finally tries to map the property type to a default editor. If an editor is not found at
all, the property is not displayed for editing. Developers can modify the registry as required.
For example the default types can be mapped to custom editors and the editors for custom
types can also be defined:

C#
dataForm.Adapter.EditorRegistry.AddEditorForProperty(
Java.Lang.Class.FromType(typeof(DataFormSwitchEditor)), "MyProperty");
 

Similarly to set a single editor for multiple types developers have to edit the registry like this:

C#
dataForm.Adapter.EditorRegistry.AddEditorForTypes(Java.Lang.Class.FromType(
typeof(MyCustomEditor)), new Java.Lang.Class[] {CustomType1.Type,
CustomType2.Type});
 

When in read-only mode RadDataForm creates property viewers instead of property editors.
Developers can use the exact same mechanism for viewer resolution: metadata, viewer provider
callback and viewer registry modification.

The editor registry of the data form adapter has corresponding methods for registering viewers, just
like the editors. For example:

C#
dataForm.Adapter.EditorRegistry.AddViewerForTypes(Java.Lang.Class.FromType(
typeof(MyCustomViewer)), new Java.Lang.Class[] {CustomType1.Type,
CustomType2.Type});
 

For more information on how to create a custom editor or viewer see the Custom Editors page.

Validation
Every editor in RadDataForm can validate the entered data before it is committed to the object being
edited. There are two ways to set a validator for a property:

The first way is to specify it when defining the property metadata, for more details on this check
Metadata topic.

The second way is to get the editor for the required property during run-time and set a validator on

1948
Telerik UI for Xamarin

the editor. For example:

C#
MailValidator validator = new MailValidator();
dataForm.GetExistingEditorForProperty ("EMail").Property ().Validator = validator;
 

Any validator should implements the PropertyValidator interface. For example here is how
MailValidator is implemented:

C#
public class MailValidator : Com.Telerik.Widget.Dataform.Engine.PropertyValidatorBase
{
protected override bool ValidateCore(Java.Lang.Object input, String propertyName)
{
String mail = (String)input;
return Android.Util.Patterns.EmailAddress.Matcher(mail).Matches();
}
}
 

When an editor tries to commit its value, if the validation fails or succeeds, the validation view of the
editor will be notified with the validation info produced in the process. The validation view must be
present inside the editor and will visually update itself to reflect the validation info that is passed to it.

For example if the user enters a value for the mail field that is not an e-mail, a validation error will be
displayed like this:

1949
Telerik UI for Xamarin

Property Value Converters


RadDataForm can associate property value converters with the properties of the edited object. For
example the developer decides to use a text editor to display an integer, they will have to specify a
way to convert that integer to and from a string. For example:

C#
dataForm.GetExistingEditorForProperty("Age").Property().Converter =
new IntegerToStringConverter();

public class IntegerToStringConverter : Java.Lang.Object,


Com.Telerik.Widget.Dataform.Engine.IPropertyConverter {

public Java.Lang.Object ConvertTo(Java.Lang.Object source) {


return source.ToString();
}

public Java.Lang.Object ConvertFrom(Java.Lang.Object source) {


return Java.Lang.Integer.ParseInt(source.ToString());
}
}
 

Editor Relations
Some data entry forms contain editors that depend on each other. For example if there is an editor
that displays a spinner with predefined items, the items might need to change if the value of another
editor changes.

A practical case is when the user selects the country in which they live, then another editor can be
enabled so that they can choose a city from the selected country and so on.

An editor relation is just a callback method that is called when an editor value changes:

C#
dataForm.AddEditorDependency("City", new Procedure2Impl());

public class Procedure2Impl : Java.Lang.Object, IProcedure2 {


public void Apply(Java.Lang.Object form, Java.Lang.Object editor) {
RadDataForm dataForm = (RadDataForm)form;
EntityPropertyEditor cityEditor = (EntityPropertyEditor)editor;

Spinner citiesSpinner = (Spinner)cityEditor.EditorView;


String selectedCountry =
(String)(dataForm.GetExistingEditorForProperty("Country").
JavaCast<EntityPropertyEditor>()).Value();
citiesSpinner.Adapter = CreateAdapterForCountry(selectedCountry);
}
}
 

1950
Telerik UI for Xamarin

In this example the editor for the City property depends on the value of the editor for the Country
property. When the country changes, the callback gets invoked and the city spinner is populated with
the cities from the selected country.

Property Metadata
When defining custom classes for RadDataForm to edit, developers have the option to annotate the
properties of their classes with the @DataFormProperty annotation. It contains several attributes than
can be used to customize the functionality of the editor corresponding to the property.

Commit Modes
RadDataForm supports three commit modes - Immediate, OnLostFocus and Manual. Immediate
mode validates and commits the property value of an editor immediately after the editor value
changes. OnLostFocus works only for editors that can be focused, like a text field for example.
Editors that can't be focused can work only in immediate or manual mode. Finally manual mode
allows the developer to dictate when to validate and commit all or some the edited properties by
calling the dataForm.CommitChanges() method.

To commit a single property the EntityProperty object for the property must be obtained and then its
Commit() method must be called:

C#
dataForm.GetExistingEditorForProperty("Age").Property().Commit();
 

It is important to note that committing in this way will not validate the currently set value. To validate
manually first call ValueCandidate to the EntityProperty object and then call commit if no validation
errors occur.To listen for validation errors call AddValidationCompletedListener() on the
EntityProperty object.
 

Customizing the editors layout


Supporting multiple screen sizes on Android is a necessity so RadDataForm allows developers to
specify a Layout Manager that will be used to arrange the editors. The default layout manager
arranges the editors in a table layout.

Read-Only mode
RadDataForm can simply display information about an object in read-only mode. To make
RadDataForm read-only, simply set IsReadOnly property to "True".When in read-only mode,
RadDataForm will disregard the property setters and will create non-interactive viewers for each
property.

Creating custom editors and viewers

1951
Telerik UI for Xamarin

RadDataForm can be extended by creating custom editors or by modifying the existing ones.

Label Position
RadDataForm has two options for layout of the labels and the editors. The default label position is on
top of the editor, but with the LabelPosition property you can change it, so that the labels and the
editors are on the same row. Here’s how:

C#
dataForm.LabelPosition = LabelPosition.Left;
 

And here’s the result:

Image Labels
RadDataForm allows you to use images as labels of your editor. You can supply the image resource
through the @DataFormProperty annotation. Here's an example:

C#
[DataFormProperty(Label = "", Hint = "name", Index = 0,
ImageResource = Resource.Drawable.ic_dataform_guest)]
public string Name
{
get;
set;
}
 

1952
Telerik UI for Xamarin

Here's the result:

1953
Telerik UI for Xamarin

DataForm for Xamarin.Android: Built-in Editors


RadDataForm contains many built-in property editors that are either automatically resolved
depending on the property's type or by the associated annotation @DataFormProperty editor.
RadDataForm currently ships with the following built-in editors:

 DataFormTextEditor
 DataFormEmailEditor
 DataFormPasswordEditor
 DataFormPhoneEditor
 DataFormIntegerEditor
 DataFormDecimalEditor
 DataFormSwitchEditor
 DataFormNumberPickerEditor
 DataFormSeekBarEditor
 DataFormSegmentedEditor
 DataFormDateEditor
 DataFormTimeEditor
 DataFormSpinnerEditor
 DataFormListViewEditor
 DataFormRadioGroupEditor
 DataFormCheckBoxEditor
 DataFormRadAutoCompleteEditor

Using @DataFormProperty
RadDataForm 'Editor annotation' can be used to easily assign an editor to a property of the source
object. The next example demonstrates how to set the editor of a property via the described
annotations:

C#
[DataFormProperty(Label = "Phone Number", Hint = "phone",
Editor = typeof(DataFormPhoneEditor)]
public string Phone
{
get;
set;
}
 

Using the DataFormRadAutoCompleteEditor


DataFormRadAutoCompleteEditor is a bit more advanced editor which provides quick search
functionality. This editor uses the RadAutoCompleteTextView standalone control and all its
functionality like DisplayMode is available to the RadDataForm editor.

Setting the suggestions 'source'

1954
Telerik UI for Xamarin

Because of the nature of the RadAutoCompleteTextView the editor which exposes its functionality
requires some additional data to be passed to it which will be used as the 'suggestions' when a user
starts typing in its textbox.

In order to pass this data, you would need to create AutoCompleteAdapter and set it to the
RadAutoComplete via its Adapter property. RadAutoComplete control can be accessed through the
EditorView of the DataFormRadAutoCompleteEditor.

To illustrate the approach better, the example below will use the following class as a Source of the
DataForm:

C#
public class Booking : NotifyPropertyChangedBase
{
private string from;
private string to;

[DataFormProperty(Label = "From", Index =0, Editor =


typeof(DataFormRadAutoCompleteEditor))]
public string From
{
get
{
return this.from;
}
set
{
this.from = value;
NotifyListeners("From", value);
}
}

[DataFormProperty(Label = "To", Index = 1, Editor =


typeof(DataFormRadAutoCompleteEditor))]
public string To
{
get
{
return this.to;
}
set
{
this.to = value;
NotifyListeners("To", value);
}
}
}
 

Here is the DataForm definition with the AutoCompleteAdapter applied:

C#

1955
Telerik UI for Xamarin

public class MainActivity : AppCompatActivity


{
private List<string> destinations = new List<string>()
{
"Atlanta", "Beijing", "Los Angeles", "Dubai", "Tokyo", "Chicago", "London",
"Shanghai", "Paris",
"Dallas", "Amsterdam", "Hong Kong", "Frankfurt", "Delhi", "Madrid", "Toronto",
"Sydney"
};

protected override void OnCreate(Bundle savedInstanceState)


{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);

RadDataForm dataForm = new RadDataForm(Application.Context);

dataForm.SetEntity(new Booking());
var adapter = new AutoCompleteAdapter(Application.Context,
this.GetTokenObjects(),
Java.Lang.Integer.ValueOf(Resource.Layout.suggestion_item_layout));
adapter.CompletionMode = CompletionMode.StartsWith;

DataFormRadAutoCompleteEditor fromEditor =
(DataFormRadAutoCompleteEditor)dataForm.GetExistingEditorForProperty("From");
RadAutoCompleteTextView fromAutocomplete =
(RadAutoCompleteTextView)fromEditor.EditorView;
fromAutocomplete.Adapter = adapter;
SetContentView(dataForm);
}

private List<TokenModel> GetTokenObjects()


{
List<TokenModel> feedData = new List<TokenModel>();
for (int i = 0; i < this.destinations.Count; i++)
{
TokenModel token = new TokenModel(this.destinations[i], null);
feedData.Add(token);
}

return feedData;
}
}
 

Setting the DisplayMode


If you are familiar with the RadAutoCompleteTextView element you know that is supports out of the
box two different selected items display modes:

 Token - the selected item from the 'suggestion box' is displayed as a box with a remove 'X'
button
 Plain - the selected item's text is appended and autocompleted after an item from the

1956
Telerik UI for Xamarin

'suggestion box' is selected

When using the DataFormRadAutoCompleteEditor you too have the option to change the editor's
DisplayMode:

C#
DataFormRadAutoCompleteEditor fromEditor =
(DataFormRadAutoCompleteEditor)dataForm.GetExistingEditorForProperty("From");
RadAutoCompleteTextView fromAutocomplete =
(RadAutoCompleteTextView)fromEditor.EditorView;
fromAutocomplete.DisplayMode = DisplayMode.Tokens;
 

When the DisplayMode is set to Tokens if the bound to that editor property of your EntityProperty is
of type String[] and each of its elements is present in the "suggestion source" those items from
the array will be rendered as separate tokens.

1957
Telerik UI for Xamarin

DataForm for Xamarin.Android: Custom Editors


Creating a custom editor for RadDataForm consists of two things: creating an editor and creating a
viewer, when in read-only mode.

To create a custom editor developers need to create a class that inherits from EntityPropertyEditor
and provide a constructor that accepts a Context asits first argument and an EntityProperty object as
its second argument. For example:

C#
public class CustomEditor : EntityPropertyEditor {
public CustomEditor(RadDataForm form, IEntityProperty property) : base(form,
Resource.Layout.custom_editor_layout,
Resource.Layout.custom_editor_header_layout,
Resource.Id.custom_editor_header,
Resource.Layout.custom_editor_core,
Resource.Id.custom_editor,
Resource.Layout.custom_editor_validation_layout,
property)
{

}
public CustomEditor(RadDataForm dataForm, int layoutId, int headerLayoutId,
int headerViewId, int editorLayoutId, int editorViewId,
int validationLayoutId, IEntityProperty property) :

base(dataForm, layoutId, headerLayoutId, headerViewId, editorLayoutId,


editorViewId, validationLayoutId, property)
{
}

public override Java.Lang.Object Value() {


return ((EditText)EditorView).Text;
}

protected override void ApplyEntityValueToEditor(Java.Lang.Object entityValue) {


((EditText)EditorView).Text = entityValue.ToString();
}
}
 

This basic custom editor is designed to edit String properties. Notice how the constructor calls the
super constructor with a specific layout and the ids of the necessary parts that define the editor.
These are the editor itself, the header view and the validation view. The editor can be a button, an
edit text widget, a spinner or anything else that allows the user to edit the associated property. The
layout can be completely arbitrary and the only requirement is that the editor, header and validation
view be specified. One minor restriction is that the validation view must inherit from
DataFormValidationView.

1958
Telerik UI for Xamarin

DataForm for Xamarin.Android: Metadata


When defining a class that will be edited by RadDataForm it is useful to annotate it with the
@DataFormProperty annotation. This annotation contains several attributes that help the data form
editors to be rendered with precision. The available attributes are label, index, column index, group,
required, readOnly, skip, viewer, editor, converter and validator.

Label
The label attribute is used for the header of the editor. If the label is not specified the header will be
set to the property name without the get/set prefix.

Index
The index is used by the layout manager to sort the editors by index.

Column Index
The column index is used by the default layout which is a TableLayout and specifies in which column
a given editor will be positioned.

Column Span
The column span is used by the default layout which is a TableLayout and specifies how many
columns a given editor will occupy.

Group
The group attribute is used to group editors. A group of editors will be visually distinct and packed
together when RadDataForm is rendered.

ImageResource
The imageResource attribute is used by the editors to display an image inside the editor that can be
used instead of a label if it will be descriptive enough for the users.

Required
The required attribute is used by the editors to display a small notification to the end-user that certain
fields can not be omitted.

ReadOnly

1959
Telerik UI for Xamarin

When the readOnly attribute is set to true the setter for the associated property will be ignored and a
viewer will be created instead of an editor.

Skip
When skip is set to true the associated property will be ignored by RadDataForm and will not be
available for editing or viewing.

Viewer
A custom viewer can be specified by setting a custom viewer type.

Editor
A custom editor can be specified by setting a custom editor type.

EditorParams
Custom parameters used to properly set up the editor.

Converter
Specifies a property value converter for the associated property.

Validator
Specifies a custom validator for the associated property.

ValidatorParams
Custom parameters used to properly set up the validator.

Example
To annotate a class with @DataFormProperty, only the getters of the properties should be
annotated. Any annotations on the setters will be ignored:

C#
public class Person : Java.Lang.Object
{
[DataFormProperty(Label = "Age", Index = 1, Validator = typeof(RangeValidator))]
[DataFormValidatorParams(Min = 18, Max = 70)]
public int Age
{

1960
Telerik UI for Xamarin

get;
set;
}

[DataFormProperty(Label = "Employee Type", Index = 4)]


public EmployeeType EmployeeType
{
get;
set;
}

[DataFormProperty(Label = "Name", Index = 0)]


public string Name
{
get;
set;
}

[DataFormProperty(Label = "E-mail", Index = 2,


Validator = typeof(MailValidator))]
public string Mail
{
get;
set;
}

[DataFormProperty(Label = "Employed", Index = 3, Required = true)]


public bool IsEmployed
{
get;
set;
}

[DataFormProperty(Label = "Birth Date", Index = 5,


Editor = typeof(DataFormTimeEditor), ReadOnly = true)]
public long BirthDate
{
get;
set;
}
}
 

1961
Telerik UI for Xamarin

DataForm for Xamarin.Android: Schema


You can set up how each property will be edited through the Property Metadata. Another way to
achieve the same is through a json schema that provides the same information. This can be useful
for example when editing json objects that can't be annotated with the DataFormProperty annotation.

The schema can be used not only as a replacement for the annotations for defining the metadata for
each property - label, index, columnIndex, group, required, readOnly, skip, editor, editorParams,
converter, validator, validatorParams - but also for data form properties like IsReadOnly,
CommitMode and ValidationMode.

Here's one schema example:

{
"commitMode": "immediate",
"validationMode": "immediate",
"properties":
[
{
"name": "name",
"displayName": "Your Name"
},
{
"name": "age",
"displayName": "Your Age",
"editor": "stepper",
"editorParams":
{
"minimum": 18,
"maximum": 70
}
},
{
"name": "gender",
"displayName": "Your Gender",
"editor": "picker",
"valuesProvider": ["male", "female"]
},
{
"name": "email",
"editor": "email",
"validator": "MailValidator",
"displayName": "Your Email"
},
{
"name": "city",
"editor": "segmentededitor",
"valuesProvider": ["New York", "Las Vegas", "Los Angeles"]
}
]
}

1962
Telerik UI for Xamarin

This schema can be used to edit the following object:

{
"name": "John Doe",
"age": 21,
"gender": "Male",
"email": "john.doe@example.com",
"city": "New York"
}
 

The result would be that the name property will have a header "Your name", the age property will be
edited with NumberPicker(Stepper), with available range from 18 to 70. The gender will be edited
with a Picker(Spinner) with male and female as possible values, etc.

Here's how to apply the schema to the DataForm:

C#
// The files PersonExtended.json and PersonSchema.json are
// in the Assets folder of the project
String json = LoadJSONFromAsset ("PersonExtended.json");

try {
JSONObject jsonObject = new JSONObject (json);
dataForm.SetEntity(jsonObject);

String schema = LoadJSONFromAsset("PersonSchema.json");


JSONObject jsonSchema = new JSONObject(schema);
DataFormMetadata metadata = new DataFormMetadata(jsonSchema);
dataForm.SetMetadata(metadata);
} catch(JSONException e) {
Log.Error ("json", "error parsing json", e);
}
 

The LoadJSONFromAsset simply returns the content of file with given name. One sample
implementation is provided in the Getting Started article.

1963
Telerik UI for Xamarin

DataForm for Xamarin.Android: Customizing


RadDataForm's Editors
Each editor in RadDataForm consists of the following elements:

 Header
 Core editor
 Validation message
 Validation icon

Each of these elements can be customized individually for each editor. They (except core editor) can
also be specified once to be used for every editor in the DataForm

Custom layouts
Specifying individual parts for a specific editor is done via the @DataFormProperty annotation. For
example:

C#
[DataFormProperty(
EditorLayout = Resource.Layout.editor_main_layout,
CoreEditorLayout = Resource.Layout.core_editor,
HeaderLayout = Resource.Layout.editor_header_layout,
ValidationLayout = Resource.Layout.editor_validation_layout)]
public string Name {
get {
return name;
}
set {
name = value;
}
}
 

Notice one additional attribute of the annotation, the EditorLayout. This is the main layout of the
editor which contains each of the sub-elements described above. This can be used if the app design
requires the header to be on the right of the editor or if the validation message should be on top of
the core editor for example. The main layout's purpose is to allow custom positioning of the sub
elements of each editor.

Finally along with the fine grained options above, one main layout can be specified and reused for
every editor. For example:

C#
// Set the same main layout for every editor.
dataForm.EditorsMainLayout = Resource.Layout.editors_main_layout;

// Set the same header layout for every editor.

1964
Telerik UI for Xamarin

dataForm.EditorsHeaderLayout = Resource.Layout.editors_header_layout;

// Set the same validation layout for every editor.


dataForm.EditorsValidationLayout = Resource.Layout.editors_validation_layout;
 

To illustrate the main layout and its sub elements consider this image:

Here "Date" is the header. The red highlighted text field is the core editor which is a date picker in
this case and finally the red message below is the validation message. When there is a validation
icon specified it will be displayed to the right of the core editor.

Editor customizations
Another way to customize the editors is with DataForm's EditorCustomization property. It allows you
to define a procedure that will be applied for each editor and you will get a chance to alter the
appearance for the editors that meet a certain requirement.

Here is an example:

C#
dataForm.EditorCustomizations = new EditorCustomizationsExample();
// ...
class EditorCustomizationsExample : Java.Lang.Object, IProcedure {
public void Apply (Java.Lang.Object p0)
{
EntityPropertyViewer entityPropertyViewer = (EntityPropertyViewer)p0;
switch (entityPropertyViewer.Property().Name()) {
case "Name":
TextView headerView = (TextView)entityPropertyViewer.HeaderView;
headerView.SetTextColor (Color.Blue);
EditText editorView = (EditText)entityPropertyViewer.EditorView;
editorView.SetTextColor (Color.Blue);
break;
case "Age":
entityPropertyViewer.RootLayout().SetBackgroundColor(Color.Cyan);
break;
case "BirthDate":
entityPropertyViewer.HeaderView.
SetBackgroundColor(Color.Red);
entityPropertyViewer.EditorView.
SetBackgroundColor(Color.ParseColor("#AAFF4444"));
break;
}

1965
Telerik UI for Xamarin

}
}
 

And here's the result:

1966
Telerik UI for Xamarin

DataForm for Xamarin.Android: Customizing Validation


Every editor in RadDataForm has a default validation behavior. This behavior is represented by the
DataFormValidationViewBehavior class. It shows only negative feedback which looks like this:

The negative feedback consists of displaying a message somewhere around the editor, showing an
error icon if available and setting the background of the core editor parent to some red color.

Another indication for negative validation that you can use is, to show red color as a background of
the core editor. You can use this behavior with validation behavior's setChangeBackground method
and set it to true, if you want the color modification to be applied not to the line below the editor, but
to its background.

The error message and indications can also be animated. RadDataForm provides another class
called ValidationAnimationBehavior which animates an invalid editor by shaking it. It can easily be
extended to blink, fade or any other appropriate animation.

To customize the validation behavior the DataFormValidationViewBehavior class can be tweaked


with the following properties:

 InvalidBackgroundDrawable: The error background.


 InvalidDrawable: The error icon.

There is also a third behavior out of the box that inherits from DataFormValidationViewBehavior and
it is called DataFormPositiveValidationViewBehavior. The positive behavior can display negative as
well as positive feedback. For example:

The positive behavior adds two more properties:

 ValidBackgroundDrawable
 ValidDrawable

To use any of the described behaviors developers have to do this:

C#
EntityPropertyEditor editor =

1967
Telerik UI for Xamarin

Android.Runtime.Extensions.JavaCast<EntityPropertyEditor>(
dataForm.GetExistingEditorForProperty("Name"));
editor.ValidationViewBehavior = new DataFormValidationViewBehavior(context);
 

1968
Telerik UI for Xamarin

DataForm for Xamarin.Android: Group Layout


To separate the DataForm editors into groups, developers must use
DataFormGroupLayoutManager.

C#
// The context argument is the app context/activity.
dataForm.LayoutManager = new DataFormGroupLayoutManager (context);
 

Each editor will be put in the group specified in the @DataFormProperty annotation of the associated
property.

For example if we have a Reservation class with a ReservationDate property:

C#
public class Reservation
{
[DataFormProperty(Group = "Reservation Date")]
public long ReservationDate
{
get;
set;
}
}
 

We can annotate the getReservation() method with the @DataFormProperty annotation and specify
the group for the editor.With this information, DataFormGroupLayoutManager creates an
EditorGroup object for each group. EditorGroup represents a layoutwhich contains a group header
and a container for the editors for the group. Each EditorGroup can have a specific layout manager
thatwill be used to arrange its editors. By default EditorGroup uses DataFormLinearLayoutManager.

Specifying a layout manager for each group


Developers can specify a custom layout manager with the setLayaoutManager() method just like
setLayoutManager() on RadDataForm:

C#
editorGroup.LayoutManager = new DataFormPlaceholderLayoutManager();
 

Creating special groups or modifying the default ones


To get a reference to the required EditorGroup object, developers can supply a callback that creates
groups for every group name. For example:

1969
Telerik UI for Xamarin

C#
groupLayoutManager.CreateGroup = new CreateGroupImpl();

public class CreateGroupImpl : Java.Lang.Object, IFunction2 {


public Java.Lang.Object Apply(Java.Lang.Object context,
Java.Lang.Object groupName) {

if(groupName.Equals("Reservation Date")) {
EditorGroup group = new EditorGroup(
(Context)context, groupName.ToString());
group.LayoutManager =
new DataFormPlaceholderLayoutManager(
(Context)context, R.layout.placeholder_layout);
return group;
}

// Returning null will invoke the default group creation logic.


return null;
}
}
 

If a property does not a have group set to it, it will be added to the default group which has a name
of "", also known as the empty group.

When creating an EditorGroup developers can use another constructor that accepts a layout as its
third argument. This allows custom group headersand custom positioning of the group header
compared to the editors container. For example:

C#
EditorGroup group =
new EditorGroup(context, groupName, Resource.Layout.custom_editor_group);
 

And the layout can look like this:

XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<TextView android:visibility="gone"
android:id="@+id/data_form_group_header"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

<FrameLayout
android:id="@+id/data_form_editor_group_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>

1970
Telerik UI for Xamarin

Here the TextView with id data_form_group_header and the ViewGroup with id


data_form_editor_group_container are mandatory.

Sorting the editor groups


The editor groups in DataFormGroupLayoutManager can be sorted by providing a simple callback by
calling setSortGroups(). For example:

C#
groupLayoutManager.SortGroups = new SortGroupsImpl();

public class SortGroupsImpl : Java.Lang.Object, IFunction, Java.Util.IComparator {


public Java.Lang.Object Apply(Java.Lang.Object arg) {
Java.Util.IList groups = (Java.Util.IList)arg;
List<EditorGroup> groupsList =
new List<EditorGroup> (groups.ToEnumerable<EditorGroup> ());
Java.Util.Collections.Sort (groupsList, this);

return Java.Util.ArrayList.FromArray (groupsList.ToArray ());


}

public int Compare(Java.Lang.Object lhs, Java.Lang.Object rhs) {


EditorGroup left = (EditorGroup)lhs;
EditorGroup right = (EditorGroup)rhs;
return right.Name ().CompareTo (left.Name());
}
}
 

Using ExpandableEditorGroup
Finally, developers can make use of another group which is called ExpandableEditorGroup.The
ExpandableEditorGroup class has one property - IsExpanded.ExpandableEditorGroup can also be
created with a flag that indicates that it can be expanded onlyonce. After it is expanded, the collapse
button disappears.

C#
// The third argument indicates whether the group can be expanded only once.
ExpandableEditorGroup expandableGroup =
new ExpandableEditorGroup (Context, "Reservation Date", true);
expandableGroup.IsExpanded = false;
 

1971
Telerik UI for Xamarin

DataForm for Xamarin.Android: Linear Layout


RadDataForm can easily arrange its editors in a linear layout instead of the default table layout. This
can be done with the DataFormLinearLayoutManager class.

C#
// The context argument of the manager is the app context/activity.
dataForm.LayoutManager = new DataFormLinearLayoutManager(context);
 

The linear manager can also change its orientation:

C#
linearLayoutManager.Orientation = (int)Android.Widget.Orientation.Horizontal;
 

Finally, DataFormLinearLayoutManager can be initialized with a special linear layout inflated from
XML.

Assuming the app project contains a layout called R.layout.data_form_custom_linear_layout, the


manager can be initialized like this:

C#
// Note that the orientation of the linear layout specified in the XML
// will be overwritten by the orientation of the manager itself.
// Another important detail is that the XML must have the LinearLayout
// object as the root element.
DataFormLinearLayoutManager manager =
new DataFormLinearLayoutManager(context,
Resource.Layout.data_form_custom_linear_layout);
 

1972
Telerik UI for Xamarin

DataForm for Xamarin.Android: Placeholder Layout


To use the placeholder layout developers must create an instance of the
DataFormPlaceholderLayoutManager class.

C#
// The second argument must have a ViewGroup as the root element in the XML.
// This can be any view group.
dataForm.LayoutManager =
new DataFormPlaceholderLayoutManager(context, Resource.Layout.placeholder_layout);
 

The placeholder_layout root element must contain ViewGroup objects where each child has a
tagthat is set to the name of the property which will be edited there. For example consider this simple
XML:

XML
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<FrameLayout
android:layout_gravity="start|top"
android:tag="Name"
android:layout_width="150dp"
android:layout_height="wrap_content"/>
</FrameLayout>
 

Here the only child element has a tag set to "Name". This tag will be compared to the properties of
the edited object and the editor responsiblefor editing the Name property will be inserted in the
Name placeholder. The placeholder is positioned in thetop left corner of the root layout. Similarly, all
other editors can be placed at arbitrary positions or even in a hierarchy of view groups allowingvery
complex layouts.

Finally, it is important to note that a placeholder for every editor must be provided. Also you may
need to call dataForm.setFillViewport(true) in order to consume the whole space from the view port.

1973
Telerik UI for Xamarin

DataSource for Xamarin.Android: Overview


RadDataSource is a class that can easily filter, sort and group data in a collection or array. The data
source exposes three collections for filtering, sorting and grouping allowing developers to define an
arbitrary data view. Furthermore RadDataSource provides automatic change notifications and is fully
integrated with the standard Android ListView as well as RadListView.

To use RadDataSource developers must add dependencies to the Common and Data libraries of the
Telerik UI for Xamarin.Android suite.

1974
Telerik UI for Xamarin

DataSource for Xamarin.Android: Getting Started


To use RadDataSource developers first need raw data in a collection of some sort. Then
RadDataSource can be constructed like this:

C#
// This method gets the raw data from somewhere. (web service, file etc.)
Java.Util.ArrayList rawData = GetData();
RadDataSource dataSource = new RadDataSource(rawData);
 

Once the data source is constructed the data can be filtered, sorted and grouped:

C#
public class Person : Java.Lang.Object
{
public int age;
public string name;
public string nationality;
}

public class AgeFilterDescriptor : Java.Lang.Object, IFunction


{
public Java.Lang.Object Apply(Java.Lang.Object argument)
{
Person person = (Person)argument;
return person.age < 18;
}
}

public class NameSortDescriptor : Java.Lang.Object, IFunction2


{
public Java.Lang.Object Apply(Java.Lang.Object arg1, Java.Lang.Object arg2)
{
Person person1 = (Person)arg1;
Person person2 = (Person)arg2;

return person1.name.CompareTo(person2.name);
}
}

public class NationalityGroupDescriptor : Java.Lang.Object, IFunction


{
public Java.Lang.Object Apply(Java.Lang.Object argument)
{
Person person = (Person)argument;
return person.nationality;
}
}
 

1975
Telerik UI for Xamarin

The order in which the descriptors are added does not matter. RadDataSource always filters first,
sorts second and groups last.
 
Finally when the data is processed it can be consumed in two ways. One is the View() method,
which returns the data in full hierarchy (if grouped multiple times). The other is the FlatView() method
which, as the method name says, returns the hierarchical data flattened to a single level. Both
methods return lists of DataItem. The DataItem class wraps the native data so that the data source
can represent groups and actual data items. A DataItem is a group if it does not have an entity
associated, that is if its Entity() method returns null. A group can also be recognized if it has a
non-null GroupKey() value.

C#
foreach (Java.Lang.Object data in dataSource.FlatView())
{
DataItem dataItem = data.JavaCast<DataItem>();

if (dataItem.Entity () == null) {
Console.WriteLine (dataItem.GroupKey().ToString());
} else {
Console.WriteLine (dataItem.Entity().ToString());
}
}
 

RadDataSource never modifies the raw data provided.


 
To see how to use RadDataSource with RadListView have a look at this article.

1976
Telerik UI for Xamarin

ListView for Xamarin.Android: Overview


RadListView for Android is a virtualizing list component that provides the most popular features
associated with scenarios where a list of items is used. All these features are embedded in one
control with the idea to save developer time and provide better experience.

The control's features include item animations, different layouts and orientations, smart defaults for
many gestures - select on long press, execution of special action on swipe, reorder of items on long
press and drag, refreshing the list on swipe or loading more items only when need. The control can
also be used to easily visualize your items in groups, sorted and filtered in accordance with your
criteria.

On Getting Started article you can see how to get started using the control.

Behaviors
RadListView control provides various behaviors. Each of them is configurable to perform a specific
action when a user gesture occurs.

You are free to add one or more behaviors to your list view instance according to your requirements
and preferences. You can also extend an existing behavior to tweak it in order to suit your needs or
start from scratch and write a completely new behavior.

This is the list of the currently available behaviors:

1977
Telerik UI for Xamarin

 Overview: This is the overview page for the list view behaviors which explains their common
features.
 Selection: The selection behavior provides single and multiple selection modes for your list
and allows you to easily show your custom action bar while the selection is active.
 Item Reorder: The item reorder behavior allows the end user to change the initial order of the
items by performing a long press on an item and then drag freely to the desired destination
position.
 Load on Demand: The load on demand behavior allows you to load a few items at the start
and when (and only if) the user scrolls down to a certain position or presses a dedicated
button at the bottom, you can load more items.
 Swipe to Refresh: The Swipe to refresh behavior allows the end user to request a refresh of
the list for scenarios where the items in the list can change after the initial load.
 Swipe to Execute: The Swipe to execute behavior can be used to allow the end users to
dismiss an item with swipe gesture or to reveal a custom functionality button hidden behind
an item.
 Sticky Headers: The Sticky header behavior can be used when grouping is enabled to force
the header of the first item to remain visible after it is scrolled away.
 Collapsible Groups: The Collapsible Groups behavior can be used when grouping is enabled
to allow the users to collapse or expand the groups by tapping on their header.

Layouts
RadListView extends the native RecyclerView control, so you can use the same layout modes for
your list: Linear, Grid and Staggered Grid. We have also provided three additional layouts: Deck of
Cards, Slide and Wrap. More information is available in the Layouts topic.

1978
Telerik UI for Xamarin

Group, Sort, Filter


RadListView is integrated with RadDataSource which brings you the power to provide rules for
filtering, sorting or grouping with a single line of code. You can combine an indefinite number of rules
of all three types to receive the desired manipulation on the original list.

Group, Sort and Filter topic provides more information about these operations and the type of the
rules that are used to define each of them.

1979
Telerik UI for Xamarin

Item Animations
You can define your own item animations that will play when performing add/remove operations on
the list or use the item animators that we have provided. The types of animations that are currently
available are fade, slide and scale. Go to Item Animations topic to find out more information about the
animations: how to add them and how to set up their properties.

Other Features
RadListView also supports the concept of header and footer — custom view which are visualized in
the start and the end of the list. You can also add item click listeners to get notified when an item is
tapped. Another feature is to scroll to certain position of the list or to its start or end. More information
on these features is available on Other Features topic.

1980
Telerik UI for Xamarin

ListView for Xamarin.Android: Getting Started


In this article, you will learn how to get started with ListView for Xamarin.Android: how to initialize the
list, how to create the adapter that populates it and extend it in accordance with your layout.

By the end of the article we will have a list that looks like this:

Project Setup
For RadListView you will need the following Telerik references:

 Telerik.Xamarin.Android.Common
 Telerik.Xamarin.Android.Data
 Telerik.Xamarin.Android.List

And add references to the following AndroidX packages:

1981
Telerik UI for Xamarin

 Xamarin.AndroidX.AppCompat
 Xamarin.AndroidX.RecyclerView

Adding the list view instance


Now that the project is setup, you can easily add RadListView in the layout file for the main activity of
your project:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<com.telerik.widget.list.RadListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

</RelativeLayout>
 

You can access the control from the activity in order to be able to apply further modifications:

C#
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);

RadListView listView = FindViewById<RadListView> (Resource.Id.listView);


}
 

Adapter
RadListView extends RecyclerView and requires a similar adapter, which will be responsible for
providing a proper view for each data item. The items are represented by ViewHolders which are
recycled for better performance.

For example if we have a list of 20 items, but only 7 are visible on the screen at one point, then 7
view holders should be enough to represent all the data. Later when the user scrolls the same view
holders will be reused to show the new data.

The default adapter that is used by RadListView is called ListViewAdapter. In order to create a new
instance, you simply need to pass a list of items to the constructor of the adapter.

Let's create a simple class that we will use later to populate the list:

C#

1982
Telerik UI for Xamarin

public class City : Java.Lang.Object


{
public String Name { get; set; }
public String Country { get; set; }

public City(String name, String country)


{
this.Name = name;
this.Country = country;
}

public override string ToString ()


{
return string.Format ("{0} ({1})", Name, Country);
}
}
 

Now, let's create a method that will create a list of items that we can use for our list view adapter:

C#
private List<City> GetListOfCities()
{
List<City> cities = new List<City> ();
cities.Add (new City ("London", "United Kingdom"));
cities.Add (new City ("Berlin", "Germany"));
cities.Add (new City ("Madrid", "Spain"));
cities.Add (new City ("Rome", "Italy"));
cities.Add (new City ("Paris", "France"));
cities.Add (new City ("Hamburg", "Germany"));
cities.Add (new City ("Barcelona", "Spain"));
cities.Add (new City ("Munich", "Germany"));
cities.Add (new City ("Milan", "Italy"));
cities.Add (new City ("Cologne", "Germany"));
return cities;
}
 

We are now ready to create a new adapter from the list and pass it to the list view instance:

C#
ListViewAdapter listViewAdapter = new ListViewAdapter (GetListOfCities ());
listView.SetAdapter (listViewAdapter);
 

More often than not, you will want your list view items to include a bit more complex layout. In order
to achieve this you will need to extend the ListViewAdapter class and override its
onCreateViewHolder and onBindViewHolder methods. The first one is responsible for creating a new
view holder that will be later reused to visualize different data items. The second is responsible for
the binding of a view holder with information about a specific item from the list.

Here's one way to extend the default adapter:

1983
Telerik UI for Xamarin

C#
public class CityAdapter : Com.Telerik.Widget.List.ListViewAdapter
{
public CityAdapter(IList items) : base(items)
{
}

public override AndroidX.RecyclerView.Widget.RecyclerView.ViewHolder


OnCreateViewHolder (ViewGroup parent, int viewType)
{
LayoutInflater inflater = LayoutInflater.From(parent.Context);
View view = inflater.Inflate(Resource.Layout.city_list_item, parent, false);
return new CityViewHolder(view);
}

public override void OnBindListViewHolder (Com.Telerik.Widget.List.ListViewHolder


holder, int position)
{
CityViewHolder viewHolder = (CityViewHolder)holder;
City city = (City)Items[position];
viewHolder.nameView.Text = city.Name;
viewHolder.countryView.Text = city.Country;
}

public class CityViewHolder : Com.Telerik.Widget.List.ListViewHolder


{
public TextView nameView;
public TextView countryView;

public CityViewHolder(View itemView) : base(itemView)


{

nameView = (TextView)itemView.FindViewById(Resource.Id.nameView);
countryView = (TextView)itemView.FindViewById(Resource.Id.countryView);
}
}
}
 

The resource city_list_item that is used in the adapter is a new layout resource added in the layout
directory of your project and its content is as follows:

xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/pressable_item_background"
android:padding="16dp">

<TextView
android:id="@+id/nameView"
android:layout_width="match_parent"

1984
Telerik UI for Xamarin

android:layout_height="wrap_content"
android:textSize="16sp"
android:textColor="#FF33B5E5" />

<TextView
android:id="@+id/countryView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="14sp"
android:textColor="#8A000000" />

</LinearLayout>
 

When you set an instance of your new adapter to the list view, it will look as the one in image from
the beginning of the article:

C#
CityAdapter cityAdapter = new CityAdapter (GetListOfCities ());
listView.SetAdapter (cityAdapter);
 

1985
Telerik UI for Xamarin

ListView for Xamarin.Android: Layouts


As RadListView extends RecyclerView, it provides the same layout mechanism. Namely — you can
use the setLayoutManager(LayoutManager) method to change the layout that is used.There are
three implemented layouts and you can also create your own by extending LayoutManager.

Getting Started
By default RadListView will use LinearLayoutManager but you can easily change that with the
setLayoutManager(LayoutManager). The layouts that are implemented are:

 Linear: The default layout which orders the item in a simple list.
 Grid: A LayoutManager implementation that lays out items in a grid.
 Staggered Grid: A LayoutManager that lays out children in a staggered grid formation.
 Deck of Cards: A LayoutManager that lays out children stacked in a way similar to a deck of
cards, where one item is fully visible and others are shown in perspective.
 Slide: A LayoutManager that lays out children in a gallery-like way where one item is in the
center and users can easily swipe to adjacent items.
 Wrap: A LayoutManager that lays out children consecutively on one line until it can and when
there is not enough space on the current line, it creates a new line and continues the layout
process there.

Each of these layouts can layout the items either horizontally or vertically. More information about
the first three layouts is available in their own documentation. The others are demonstrated below.
Here's one example of setting grid layout with two columns and horizontal layout:

C#
GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2,
LinearLayoutManager.Horizontal, false);
listView.SetLayoutManager(gridLayoutManager);
 

Deck of Cards
The DeckOfCardsLayoutManager is a layout manager which lays out the items in way similar to a
deck of cards where one item is fully visible and other are shown behind it in a perspective and when
you scroll down, the next itemmoves forward:

1986
Telerik UI for Xamarin

Getting Started
Just like the other layout managers, all you need to do, is to create a new instance of the layout and
add it through RadListView's setLayoutManager method:

C#
DeckOfCardsLayoutManager deckOfCardsLayoutManager =
new DeckOfCardsLayoutManager (this);
listView.SetLayoutManager (deckOfCardsLayoutManager);
 

Similarly to LinearLayoutManager, DeckOfCardsLayoutManager provides additional constructor,


which allows you to change the orientation to Horizontal and/or reverse the layout, so that the
perspective items are shownon a different side of front item. For example:

C#
DeckOfCardsLayoutManager deckOfCardsLayoutManager =

1987
Telerik UI for Xamarin

new DeckOfCardsLayoutManager (this,


OrientationHelper.Horizontal, true);
listView.SetLayoutManager (deckOfCardsLayoutManager);
 

This way the perspective items will be laid out to the right of the front item and the scrolling forward
will be made by swiping to the left.

Items Count
Speaking of perspective items, by default you will see 2 items behind the front view,which can be
changed through setPerspectiveItemsCount(int). The current value is accessible with
getPerspectiveItemsCount().

C#
deckOfCardsLayoutManager.PerspectiveItemsCount = 5;
 

Scrolling
By default you are able to scroll to the next or previous item by swiping bottom or top. However, you
can also do that programmatically through the scrollToNext() and scrollToPrevious() methods and
also to a certain position through scrollToPosition(int). For example this can be used to move the
items with one button for forward scroll and one button for backward scroll.In that case you can also
disable the scrolling through swipe with setScrollEnabled(false).

Current item
If you need to determine which item is the one that is fully visible, you can get its position through
getCurrentPosition(). Alternatively you can change it with setCurrentPosition(int). You can also track
any changesby creating a CurrentPositionChangeListener:

C#
public class MyItemChangeListener : Java.Lang.Object,
Com.Telerik.Widget.List.ICurrentPositionChangeListener
{
private Context context;

public MyItemChangeListener(Context context)


{
this.context = context;
}

public void OnCurrentPositionChanged (int oldPosition, int newPosition)


{
Toast.MakeText (context,
"Position changed from " + oldPosition + " to " + newPosition,
ToastLength.Short).Show ();
}
}

1988
Telerik UI for Xamarin

Then you need to set it to your deck of cards layout:

C#
MyItemChangeListener listener = new MyItemChangeListener (this);
deckOfCardsLayoutManager.AddListener (listener);
 

Customization
The deck of cards layout provides a transformation object which allows you to tweak the
transformation that are applied to the perspective items. That object is available as perspective() and
you can use it to changethe way the perspective items are visible behind the front view item. For
example, if you would like to have a bigger visible part and change the way the perspective is
oriented, here's what you can do:

C#
deckOfCardsLayoutManager.Perspective ().TranslateStart = -50;
deckOfCardsLayoutManager.Perspective ().TranslateTop = -50;
deckOfCardsLayoutManager.Perspective ().TranslateEnd = -50;
 

The result is:

1989
Telerik UI for Xamarin

The idea here is that each item in the perspective will be translated from the one in front of it with the
specified pixels, in that case by 50 pixels, and since the values are negative, the translation is to the
left and to the top.Another change in the default behavior can be made with the deck of cards'
setAutoDissolveFrontView(boolean). When it is set to true the front item will dissolve as you slide it
out in order to scroll to next item andwill gently appear while you scroll to the previous item.

Behaviors
You can add the following behaviors to your list view when the DeckOfCardsLayoutManager is used:
SelectionBehavior, LoadOnDemandBehavior and SwipeExecuteBehavior. They will provide the same
functionality they do for the rest of the layout managers.

Slide
The SlideLayoutManager is a layout manager which lays out the items in a gallery-like way where
one item is in the center and users can easily swipe to adjacent items:

1990
Telerik UI for Xamarin

Getting Started
Just like the other layout managers, all you need to do, is to create a new instance of the layout and
add it through RadListView's setLayoutManager method:

C#
SlideLayoutManager slideLayoutManager =
new SlideLayoutManager (this);
listView.SetLayoutManager (slideLayoutManager);
 

SlideLayoutManager provides additional constructor, which allows you to change its orientation to
Vertical:

C#
SlideLayoutManager slideLayoutManager =
new SlideLayoutManager (this,
OrientationHelper.Vertical);
listView.SetLayoutManager (slideLayoutManager);
 

This way the adjacent items will be laid out to the top and to the bottom of the front item and the
scrolling will be made by swiping to the top or to the bottom.

Item Spacing

1991
Telerik UI for Xamarin

In the example from the screen shot, we have added margin to the item layout and this is why there
is visible space between the items. Another option to have space between items, which will not
consume place on the screen is the item spacing feature. In other words you can have an item
stretched to fill the screen and still have space between the adjacent items. Here's how to add a
spacing of 20 pixels:

C#
slideLayoutManager.ItemSpacing = 20;
 

Of course, you can get the current value with getItemSpacing(). The default is 0.

Item Preview
If you don't want to occupy the whole space with only one item, you can show its adjacent items on
the left and/or on the right. Here's an example:

C#
slideLayoutManager.PreviousItemPreview = 100;
slideLayoutManager.NextItemPreview = 100;
 

Now you will be able to see 100 pixels from each of the adjacent items (if there are any). You can
use only one of the methods or both of them together depending on your requirements. The default
value for both is 0, which you can check with getPreviousItemPreview() and getNextItemPreview()
respectively. By default, when users tap on one of the adjacent items, that item will move to the front.
If this behavior is not desired,you can turn it off through setScrollOnTap(false).

Transitions
The default transition mode in SlideLayoutManager is called SLIDE_AWAY. This means that when the
user swipes, the current item slides away in the direction of the swipe and another appears from the
opposite side. The modecan be changed to SLIDE_OVER which means that the items will appear
stacked in a way that one item slides over the one that is current. This mode resembles the behavior
in the default Android Photos app. Here's how you can change it:

C#
slideLayoutManager.TransitionMode =
SlideLayoutManager.Transition.SlideOver;
 

Please note that from visual perspective the Item Preview and Item Spacing make sense only with
the default transition mode.
 

Scrolling
By default you are able to scroll to the next or previous item by swiping left or right. However, you
can also do that programmatically through the scrollToNext() and scrollToPrevious() methods and

1992
Telerik UI for Xamarin

also to a certain position through scrollToPosition(int). For example this can be used to navigate
through items with two buttons - one for each direction.In that case you can also disable the scrolling
through swipe with setScrollEnabled(false).

Current item
If you need to determine which item is the one that is currently in front, you can get its position
through getCurrentPosition(). Alternatively you can change it with setCurrentPosition(int). You can
also track any changesby creating a CurrentPositionChangeListener:

C#
public class MyItemChangeListener : Java.Lang.Object,
Com.Telerik.Widget.List.ICurrentPositionChangeListener
{
private Context context;

public MyItemChangeListener(Context context)


{
this.context = context;
}

public void OnCurrentPositionChanged (int oldPosition, int newPosition)


{
Toast.MakeText (context,
"Position changed from " + oldPosition + " to " + newPosition,
ToastLength.Short).Show ();
}
}
 

Then you need to set it to your slide layout:

C#
MyItemChangeListener listener = new MyItemChangeListener (this);
slideLayoutManager.AddListener (listener);
 

Wrap
The WrapLayoutManager is a layout manager that starts to layout its items consecutively on one line
until it can. When there is not enough space on the current line to accommodate the next item, it
creates a new line and continues the layout process there. This repeats until all items that are
currently visible are laid out.

Getting Started
Just like the other layout managers, all you need to do, is to create a new instance of the layout and
add it through RadListView's setLayoutManager method:

C#

1993
Telerik UI for Xamarin

WrapLayoutManager wrapLayoutManager =
new WrapLayoutManager (this);
listView.SetLayoutManager (wrapLayoutManager);
 

WrapLayoutManager provides additional constructor, which allows you to change its orientation to
Horizontal:

C#
WrapLayoutManager wrapLayoutManager =
new WrapLayoutManager (this,
OrientationHelper.Horizontal);
listView.SetLayoutManager (wrapLayoutManager);
 

This way the layout process will start by creating one column and will place items there until there is
no place for a next item. Then a new column will be created for the next items.

Minimum Item Spacing


If you want, you can easily add spacing between the items on each line (that is row in vertical
orientation and column in horizontal orientation). This happens with the setMinimumItemSpacing(int).
You can get the current valuewith getMinimumItemSpacing(), the default value is 0.

Line Spacing
The spacing between the lines (again - between rows in vertical orientation and between columns in
horizontal orientation) is controlled by the line spacing. It's default value is also 0, which you can
checkwith getLineSpacing(). If you want to add spacing, use setLineSpacing(int).

Gravity
By default, the layout process starts from the top-left point and layout items one after other. Consider
the following layout scenario:

1994
Telerik UI for Xamarin

As you can see when items have different sizes, there can be empty spaces. What's common for the
items in the layout produced in the image is that the items on each line share common top border.
Also all lines share a common leftborder. However, different items in a line may have a different
bottom position and also, different lines have a different ending right position. Here's when the
gravity may come handy. You can combine one value for horizontal gravityand one for vertical
gravity at the same time.

Let's start with the horizontal values, they can be: LEFT (START), RIGHT (END),
CENTER_HORIZONTAL, FILL_HORIZONTAL. As you can see from the image the items in a single
line arealigned to the left. You can align them to the right, which will result in moving the empty
space (currently on the right) to the left. Your other option is to center them, which will result in the
even distribution of the empty space between left and right. The last option is fill, this will result in
having the items aligned both to the left and to the right with the remaining empty space equally
distributed between the items on that line.This is why the item spacing is minimum - because when
the gravity is set to fill, the item spacing may increase.

The vertical meaningful values are: TOP, BOTTOM, CENTER_VERTICAL. Depending on this value
the items in each line are aligned to the top edge of the line, to the bottom edge, or to the center.

When the orientation is horizontal, the logic is reverted - the horizontal values are applied for
alignment to the edge of the lines and the vertical values reflect the distribution of the empty space
on each line.This also means that you can use FILL_VERTICAL to distribute the empty space
between items in a column and that FILL_HORIZONTAL will not make sense for this orientation.
Here's an example for changing the gravity:

C#
wrapLayoutManager.Gravity = (int)(GravityFlags.CenterHorizontal |
GravityFlags.Bottom);
 

You can read more about Gravity here.

1995
Telerik UI for Xamarin

ListView for Xamarin.Android: Group, Sort, Filter


RadListView has an integration with RadDataSource to provide its group, sort and filter features. In
this article, you will learn to add descriptors to your adapter in order to reshape the way your original
list of items is presented.

Getting Started
For this example, we are going to use again the City type that we created in the Getting Started page.
The methods that can be usedto add the rules for grouping, sorting and filtering are part of the
ListViewDataSourceAdapter. This adapter extends the ListViewAdapter so you can use it in the
same way with all other list view features.

C#
ListViewDataSourceAdapter listViewDataSourceAdapter =
new ListViewDataSourceAdapter (GetListOfCities());
listView.SetAdapter (listViewDataSourceAdapter);
 

At this point you will not notice any difference in the way the items are visualized as opposed to if
you were using ListViewAdapter. In order to use the layout file that we created in the getting started
page,we will extend the ListViewDataSourceAdapter class and create a new adapter. We will name
it CityDataSourceAdapter:

C#
public class CityDataSourceAdapter : ListViewDataSourceAdapter
{
public CityDataSourceAdapter(IList items)
:base(items) {
}

public override ListViewHolder OnCreateItemViewHolder (ViewGroup parent, int


viewType)
{
LayoutInflater inflater = LayoutInflater.From(parent.Context);
View view = inflater.Inflate(Resource.Layout.city_list_item, parent, false);
return new CityViewHolder(view);
}

public override void OnBindItemViewHolder (ListViewHolder holder, Java.Lang.Object


entity)
{
CityViewHolder viewHolder = (CityViewHolder)holder;
City city = (City)entity;
viewHolder.nameView.Text = city.Name;
viewHolder.countryView.Text = city.Country;
}

public class CityViewHolder : ListViewHolder {

1996
Telerik UI for Xamarin

public TextView nameView;


public TextView countryView;

public CityViewHolder(View itemView)


:base(itemView){

nameView = (TextView)itemView.FindViewById(Resource.Id.nameView);
countryView = (TextView)itemView.FindViewById(Resource.Id.countryView);
}
}
}
 

You can see that the implementation is very identical to the implementation of our CityAdapter. The
difference that has to be pointed out is that instead of overriding onCreateViewHolder and
onBindViewHolder, themethods here are onCreateItemViewHolder and onBindItemViewHolder.
When we add a group descriptor we will see why this is necessary. Now let's just set an instance of
our new adapter to the list view:

C#
CityDataSourceAdapter cityDataSourceAdapter = new CityDataSourceAdapter
(GetListOfCities());
listView.SetAdapter (cityDataSourceAdapter);
 

The ListViewDataSourceAdapter provides add, remove and clear methods for each type of
descriptor that you can use, for example the methods for group descriptors are:
addGroupDescriptor(), removeGroupDescriptor()and clearGroupDescriptors(). Now let's see an
example of each descriptor type.

Group
The ListViewDataSourceAdapter allows you to easily define rules for showing your list of items in
groups. Let's create a simple group descriptor that will group our items by their country:

C#
public class CountryGroupDescriptor : Java.Lang.Object, IFunction {
public Java.Lang.Object Apply (Java.Lang.Object item)
{
return ((City)item).Country;
}
}
 

And now let's add it to our adapter:

C#
CountryGroupDescriptor countryGroupDescriptor = new CountryGroupDescriptor ();
cityDataSourceAdapter.AddGroupDescriptor (countryGroupDescriptor);
 

1997
Telerik UI for Xamarin

Now if we run the application we will see that the items are shown in groups. If we want to change
the layout of our headers, we can do so by overriding the following methods in our
CityDataSourceAdapter: onCreateGroupViewHolder() and onBindGroupViewHolder(). Here's one
simple implementation:

C#
public override ListViewHolder OnCreateGroupViewHolder (ViewGroup parent, int
viewType)
{
LayoutInflater inflater = LayoutInflater.From(parent.Context);
View view = inflater.Inflate(Resource.Layout.city_group_item, parent, false);
return new ListViewTextHolder(view, Resource.Id.headerTextView);
}

public override void OnBindGroupViewHolder (ListViewHolder holder, Java.Lang.Object


groupKey)
{
((ListViewTextHolder)holder).TextView.Text = groupKey.ToString ();
}
 

Here we are using a sample layout file named city_group_item for our header items that we have
added to the layout directory of our project:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="wrap_content">
<TextView
android:id="@+id/headerTextView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textStyle="bold"
android:textColor="#FFFFFF"
android:background="#FF0099CC"
android:textSize="14sp"
android:padding="16dp" />
</RelativeLayout>
 

Here's how it looks now:

1998
Telerik UI for Xamarin

As you have probably noticed the methods for creating and binding of the view holders that we had
in ListViewAdapter and now divided in two for ListViewDataSourceAdapter — one method for the
group headers and one method for the actual items. If you need to use more than one layout by
defining different view types, you can override adapter's getItemViewType(int). Note that negative
values for item view type will be treatedas group headers and item view types which have a value of
0 or more will be treated like list items.

Sort
The descriptors for sorting are used in a way similar to the way the grouping descriptors are used.
Here's one simple implementation:

C#
public class CountrySortDescriptor : Java.Lang.Object, IFunction2 {
public Java.Lang.Object Apply (Java.Lang.Object item1, Java.Lang.Object item2)
{
return ((City)item1).Country.CompareTo (((City)item2).Country);
}
}
 

1999
Telerik UI for Xamarin

And now let's add it to our adapter:

C#
CountrySortDescriptor countrySortDescriptor = new CountrySortDescriptor ();
cityDataSourceAdapter.AddSortDescriptor (countrySortDescriptor);
 

Now the items in the list will be sorted alphabetically by their country name. This means that if we
keep the group descriptor that we created earlier, we will have the items sorted by their group
headers.

Filter
The descriptors for filtering are definitions of rules that determine whether an item should be
displayed or not. Here's one example:

C#
public class CityFilterDescriptor : Java.Lang.Object, IFunction {
public Java.Lang.Object Apply (Java.Lang.Object item)
{
return ((City)item).Name.Length <= 5;
}
}
 

And now let's add it to our adapter:

C#
CityFilterDescriptor cityFilterDescriptor = new CityFilterDescriptor ();
cityDataSourceAdapter.AddFilterDescriptor (cityFilterDescriptor);
 

The result will be that the visible items will be only those that have a name written with 5 letters or
less.

2000
Telerik UI for Xamarin

ListView for Xamarin.Android: Item Animations


As RadListView extends RecyclerView it provides the same item animation mechanism. Namely —
you can use the setItemAnimator(ItemAnimator) method to change the animator that is used.The
item animations are played each time an item is added to the list or when it is removed.You can
extend the ItemAnimator class and implement you own animator or use one of those that we have
implemented: Fade, Slide and Scale.

Getting Started
You can easily change that DefaultItemAnimator by the setItemAnimator(ItemAnimator). The
animators that are implemented are:

 FadeItemAnimator: This animator provides fading of the items that are added or removed.
 SlideItemAnimator: With this animator the items that are added or removed will slide in and
out from the edges of the list view.
 ScaleItemAnimator: With this animator the items that are added or removed will gradually
change their scale.

Note that this animations will be played when items are added or removed (for example by calling
adapter's add or remove methods) and not when the items are loaded to populate the initial list.

Fade
Here's how we can add a FadeItemAnimator to a list view instance:

C#
FadeItemAnimator fadeItemAnimator = new FadeItemAnimator ();
listView.SetItemAnimator (fadeItemAnimator);
 

In order to see the effect, you can add a button somewhere and use it to add another item to the list
by adapter's add() method.

By default the items will fade from 0 when they appear and fade to 0 when they disappear. You can
change this by using FadeItemAnimator's setAlpha(float) method. The alpha value can be between 0
and 1, where 0 means full transparency and 1 means no transparency.

Slide
Here's how we can add a SlideItemAnimator to a list view instance:

C#
SlideItemAnimator slideItemAnimator = new SlideItemAnimator ();
listView.SetItemAnimator (slideItemAnimator);
 

2001
Telerik UI for Xamarin

In order to see the effect, you can add a button somewhere and use it to add another item to the list
by adapter's add() method.

By default the items will slide from and to the right. You can change this by using
SlideItemAnimator's setAnimateInDirection(int) and setAnimateOutDirection(int). Here are the
constants that you can use:SlideItemAnimator.DIRECTION_LEFT,
SlideItemAnimator.DIRECTION_TOP, SlideItemAnimator.DIRECTION_RIGHT,
SlideItemAnimator.DIRECTION_BOTTOM.

Scale
Here's how we can add a SlideItemAnimator to a list view instance:

C#
ScaleItemAnimator scaleItemAnimator = new ScaleItemAnimator ();
listView.SetItemAnimator (scaleItemAnimator);
 

In order to see the effect, you can add a button somewhere and use it to add another item to the list
by adapter's add() method.

By default the items will scale from 0.3f when you add them and to 0.3 when you remove them.
The scale will be applied to both dimensions of the item (height and width). You can change these
values by using ScaleItemAnimator's setScaleX(float) and setScaleY(float) methods. It you set one
of the scales to 1.0f, this means that the item will not scale at all in this dimension.

Sets
You can use the ItemAnimatorSet class to combine the animators. Additionally the animators have a
setType method that allows you to define whether an animator will be used for animation when an
item is added or removed or both. Here's how to include use scale animator when an item is added
and slide animator when an item is removed.

C#
ScaleItemAnimator scaleItemAnimator = new ScaleItemAnimator();
scaleItemAnimator.Type = ListViewItemAnimator.Add;

SlideItemAnimator slideItemAnimator = new SlideItemAnimator();


slideItemAnimator.Type = ListViewItemAnimator.Remove;

ItemAnimatorSet itemAnimatorSet = new ItemAnimatorSet();


itemAnimatorSet.AddAnimator(scaleItemAnimator);
itemAnimatorSet.AddAnimator(slideItemAnimator);

listView.SetItemAnimator(itemAnimatorSet);
 

2002
Telerik UI for Xamarin

ListView for Xamarin.Android: Other Features


This article demonstrates some of the other features of RadListView: how to show empty content
when the list is empty, how to add header and footer, how to listen to item clicks and how to scroll to
a specific position in the list.

Empty Content
You can easily provide an indication that your list currently has no items. This can be due to the lack
of adapter or if the adapter has no items.

Custom Layout as Empty Content


This can be done through the setEmptyContent(View) method. You can combine multiple items -
images, texts, etc. in a layout of your choice and use it as a parameter for this method. Here's one
example where we have create a dedicated layout resource file to define our empty content:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_gravity="center"
android:layout_width="100dp"
android:layout_height="100dp">
<ImageView
android:src="@mipmap/ic_launcher"
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:text="nothing here"
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</FrameLayout>
 

This sample demonstrates how to show the currently default launcher icon. Make sure you are
referencing an existing image file from its proper location (mipmap, drawable, etc.) and with its exact
name (ic_launcher, Icon, etc.).
 
Then we need to inflate this layout and set the resulted view as empty content:

C#
LayoutInflater inflater = LayoutInflater.From (this);
View emptyContentView = inflater.Inflate (Resource.Layout.empty_content, listView,
false);

2003
Telerik UI for Xamarin

listView.EmptyContent = emptyContentView;
 

Now if our list view doesn't contain an adapter or if it has no items, it would look in a way similar to
this:

Simple Text as Empty Content


If all you need to display is a simple TextView, you can take advantage of our default empty content.
Here's how:

C#
listView.EmptyContentEnabled = true;
 

2004
Telerik UI for Xamarin

This will automatically create a TextView with a default text that will be set as your empty content
view. You can access if you need to change its appearance, text and or gravity through the
getEmptyContent() method, of courseafter you have enabled it as just shown
(setEmptyContentEnabled(true)).

Header and Footer


RadListView allows you to add a custom view as a header or as a footer to your list. The header will
be displayed on top of the list and the footer will be at the bottom. Here's how to add a header:

C#
TextView headerView = new TextView(this);
headerView.Text = "CITIES";

listView.HeaderView = headerView;
 

The footer can be added in a similar way with the setFooterView(View) method. You can get the
current header any time by the getHeaderView() method and getFooterView() will give you the footer
so that you canmodify it if necessary.

Item Clicks
Often you will need to listen for item clicks in order to provide more information for the clicked item,
for example for a master-detail scenario. Here's one simple example that demonstrates how to adda
toast with the content of the clicked item:

C#
public class CityClickListener : Java.Lang.Object, RadListView.IItemClickListener {
private Context context;
private ListViewAdapter listViewAdapter;
public CityClickListener(Context context, ListViewAdapter adapter) {
this.context = context;
this.listViewAdapter = adapter;
}
public void OnItemClick (int postion, MotionEvent motionEvent)
{
Toast.MakeText (context, listViewAdapter.GetItem (postion).ToString(),
ToastLength.Short).Show ();
}
public void OnItemLongClick (int postion, MotionEvent motionEvent)
{
}
}
 

And now let's add it to our list view:

C#
CityClickListener cityClickListener = new CityClickListener (this, cityAdapter);

2005
Telerik UI for Xamarin

listView.AddItemClickListener (cityClickListener);
 

You can use the same listener in a similar way to get notified for long clicks by using the listener's
onItemLongClick().You can remove the listener by calling
removeItemClickListener(ItemClickListener) on the list view.

Scroll
If you need to scroll the list to a specific position or to the start of the list or to its end, you can use
RadListView's scrollToPosition(int), scrollToStart() or scrollToEnd() methods.

2006
Telerik UI for Xamarin

ListView for Xamarin.Android: Behaviors


If you have already read the Getting Started page, you know how to add RadListView instance to
your project and populate it with data.This section will demonstrate how to add different behaviors to
the list view instance that we have created.

Getting Started
The list view behaviors can be used for efficient handling of gestures by RadListView. Each behavior
handles different gestures in order to provide intuitive response. For example, when the long press
gesture is detected, SelectionBehavior will select the item that was long pressed. A behavior can be
added to a list view instance through the addBehavior(ListViewBehavior) method and removed
through removeBehavior(ListViewBehavior). Additionally you can remove allcurrently added
behaviors with clearBehaviors(). Here's an example of adding the LoadOnDemandBehavior to a list
view instance:

C#
LoadOnDemandBehavior loadOnDemandBehavior = new LoadOnDemandBehavior ();
listView.AddBehavior (loadOnDemandBehavior);
 

For now, what this will do, is to add a button at the end of the list that can be used by the end user to
request loading of more items. You can have a look at thededicated page for the
LoadOnDemandBehavior to see how to actually load more items when the button is clicked.Here's the
list of the behaviors that are currently available:

 Selection: This behavior allows the end users to select items in the list.
 Item Reorder: This behavior allows the end users to change the order of the items in the list.
 Load on Demand: This behavior allows you to load a few items at first and load more only if
necessary.
 Swipe to Refresh: This behavior allows the end users to reload the items in the list to see if
the information is updated.
 Swipe to Execute: This behavior allows the end users to swipe an item and remove it from the
list or execute another predefined command.
 Sticky Headers: This behavior can be used when grouping is enabled to force the header of
the first item to remain visible after it is scrolled away.
 Collapsible Groups: This behavior can be used when grouping is enabled to allow the users
to collapse or expand the groups by tapping on their header.

2007
Telerik UI for Xamarin

ListView for Xamarin.Android: SelectionBehavior


The SelectionBehavior is responsible for selecting, deselecting and reporting the selection of items
in RadListView. It supports single and multiple selection and can provide a notificationwhen the
selection state of an item is changed. Here's how the default settings work: when long press gesture
occurs, the list view starts selection mode and the item that was pressed gets selected. Once in
selection mode,a simple tap is enough to change the selection state of each item. The list view exits
the selection mode when all items are de-selected or when the back button is pressed.

Getting Started
If you have read the Getting Started page, you already have a project with RadListView which is
populated with items of type City. Inthe Behaviors Overview we introduced the behaviors and now we
will go into more details about the SelectionBehavior.If we were using an instance of the default
ListViewAdapter, adding the SelectionBehavior to the list view instance would have been enough to
enable the selection:

C#
SelectionBehavior selectionBehavior = new SelectionBehavior ();

2008
Telerik UI for Xamarin

listView.AddBehavior (selectionBehavior);
 

However, we have already extended the default list view adapter to CityAdapter and now in order to
be able to highlight an item when selected we will need to add a StateListDrawable to our layout that
will handle the selected state. If you are not familiar with state list drawables you can read more here
. You can also use the one that is part of the list view resources and is called
selectable_item_background. You simply need to set it as background of the list item layout (in
our example that is city_list_item). In order to target all supported platforms, you need toset this
resource as a background of the root element of the layout. Since API Level 11 the state list
drawable doesn't need to be set on the root element. You can add a new layout that will be used
when running on a device with API 11 or higher(or change the default layout if you don't plan to
support versions prior API 11). This can be used to add an overlay view that will contain the
selection state layer. The difference will be more visible if your layout contains an image. Then you
may notice that if the selection layer was set as background, the image would look the same way no
matter if the item is selected or not.Even though our layout does not include images, we are going to
add a new View for the selection layer for demonstration purposes. Here's the new content of the
city_list_item:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#FFFFFFFF"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/pressable_item_background"
android:padding="16dp">
<TextView
android:id="@+id/nameView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textColor="#FF33B5E5" />
<TextView
android:id="@+id/countryView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="14sp"
android:textColor="#8A000000" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/selectable_item_background"/>
</FrameLayout>
 

Now if you long press an item, it will change its state to show the selection layer.

Single selection

2009
Telerik UI for Xamarin

The SelectionBehavior can be also used for selection of a single item at a time. This can be done by
the setSelectionMode(SelectionBehavior.SelectionMode) method. To see the current mode you can
use getSelectionMode(). The default value is MULTIPLE. Let's change the mode to SINGLE:

C#
selectionBehavior.SetSelectionMode (SelectionBehavior.SelectionMode.Single);
 

Still, long press is required to start the selection mode. The difference is that now when you select
another item, the previous selection is cleared. In some scenarios, you may need to select an item
instantly on tap, without the explicitneed to start a selection by a long press gesture first. Here's
when the setSelectionOnTouch(SelectionBehavior.SelectionOnTouch) comes in handy. It allows you
to change the way the tap gesture is treated. The options are: NEVER, ALWAYS, AFTER_START. In
order to achieve the above mentioned instant selection on tap, you need to set the mode to ALWAYS.
The default value is AFTER_START which means that you need to start the selection first (by long
press) before the behaviors starts listening for tap gestures. If the value is NEVER, the only way to
select an item will be by long press no matter if there are selected items or not. The method
getSelectionOnTouch() returns the current value.

Selection with code


Sometimes it may be useful to have a certain item(s) preselected. Then you will need to select them
manually through code. This can be achieved through the changeIsSelected(int position, boolean
value) and changeIsSelected(int position) methods. The first will allow you to define whether the item
at the specified position is selected or not and the second allows you to simply change the selection
state of theitem at the specified position. In other words, if it was not selected, it will become
selected, and if it was selected already, it will be deselected. Here's an example of how to manually
select the first itemfrom your list:

C#
selectionBehavior.ChangeIsSelected (0);
 

Using the other overload with true as a second parameter will have the same result in this case.

SelectionChangedListener
Usually you will need to monitor the items that the user selects. You can do this by adding a
SelectionChangedListener to your SelectionBehavior. Let's remove the previously added line that set
the mode to single selection,so we can get back to the default selection mode. Now we are going to
add a new android.support.v7.view.ActionMode.Callback instance that we will use in a
SelectionChangedListener in order to properly reflect the current selection.Here's the callback that
we will use:

C#
public class SelectionCallback : Java.Lang.Object, ActionMode.ICallback {
private SelectionBehavior selectionBehavior;
public SelectionCallback(SelectionBehavior behavior) {
selectionBehavior = behavior;

2010
Telerik UI for Xamarin

public bool OnCreateActionMode (ActionMode mode, IMenu menu)


{
MenuInflater inflater = mode.MenuInflater;
inflater.Inflate (Resource.Menu.menu_main, menu);
return true;
}

public bool OnPrepareActionMode (ActionMode mode, IMenu menu)


{
return false;
}

public bool OnActionItemClicked (ActionMode mode, IMenuItem item)


{
return false;
}

public void OnDestroyActionMode (ActionMode mode)


{
selectionBehavior.EndSelection ();
}
}
 

Note that depending on the action bar that your current activity has (if it has), you may need to use
different types of callback, but the methods are similar as well as the general idea.
 
If you are using Android Studio, it should have generated the menu resource automatically, but if it
hasn't or if you are using another IDE, you will need to add a menu folder to your resources and add
a layout file named menu_main with the following (or similar) content:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity">
<item android:id="@+id/action_settings" android:title="Settings"
android:orderInCategory="100" app:showAsAction="never" />
</menu>
 

Here's the SelectionChangedListener that we will use:

C#
public class SelectionListener : Java.Lang.Object,
SelectionBehavior.ISelectionChangedListener {

private ActionMode actionMode;


private ActionMode.ICallback callback;
private Activity activity;
private SelectionBehavior selectionBehavior;

2011
Telerik UI for Xamarin

public SelectionListener(Activity activity, SelectionBehavior selectionBehavior) {


this.callback = new SelectionCallback(selectionBehavior);
this.activity = activity;
this.selectionBehavior = selectionBehavior;
}

public void OnSelectionStarted ()


{
actionMode = activity.StartActionMode (callback);
}
public void OnItemIsSelectedChanged (int position, bool newValue)
{
int selectionCount = selectionBehavior.SelectedItems ().Count;
actionMode.Title = selectionCount.ToString ();
}
public void OnSelectionEnded ()
{
actionMode.Finish ();
}
}
 

Now that we have the callback and the listener, all that's left is to add the listener to our
SelectionBehavior:

C#
SelectionListener selectionListener = new SelectionListener (this, selectionBehavior);
selectionBehavior.AddListener (selectionListener);
 

You can see the result in the image from the beginning of the article. That is when we start the
selection mode, the default action bar will be replaced with a contextual action bar that will display
the number of currently selected items.

2012
Telerik UI for Xamarin

ListView for Xamarin.Android: ItemReorderBehavior and


ReorderWithHandlesBehavior
The ItemReorderBehavior can be used to allow the end user to reorder an item by long-pressing and
dragging it. When a long-press gesture is detected, the item that lies beneath is highlighted.Any
forthcoming move gestures cause the item to be dragged around the screen and if at some point
another item lies beneath the dragged item's position is changed to the position of the new item.

The ReorderWithHandlesBehavior can be used to allow the end user to reorder an item by simply
dragging it. This behavior requires specifying a View which must be part of the item. It will work as a
reorder handle. Dragging the item by this handle will initiate the reorder operation. The constructor of
the ReorderWithHandlesBehavior accepts the ID of that view.

The following screenshot and code snippet demonstrate a custom reorder handle within an item:

In that particular case the ReorderWithHandlesBehavior is instantiated with the id of the element
within the item view that represents the reorder handle:

Java
this.reorderBehavior = new ReorderWithHandlesBehavior(R.id.imgReorder);
 

C#
this.reorderBehavior = new ReorderWithHandlesBehavior(R.id.imgReorder);
 

Getting Started
If you have read the Getting Started page, you already have a project with RadListView which is
populated with items of type City. In the Behaviors Overview we introduced the behaviors and now
we will go into more details about the ItemReorderBehavior.All you need to do, in order to enable the
reorder is to add an instance of the ItemReorderBehavior to your list view instance:

C#
ItemReorderBehavior itemReorderBehavior = new ItemReorderBehavior ();
listView.AddBehavior (itemReorderBehavior);
 

ItemReorderListener
If you need to monitor the changes in the order of the items, you can use the
addListener(ItemReorderBehavior.ItemReorderListener) method to add a new listener or

2013
Telerik UI for Xamarin

removeListener(ItemReorderBehavior.ItemReorderListener)to remove an existing one. The listener


will be notified on the following events: onReorderStarted(int position), onReorderItem(int
positionFrom, int positionTo) and onReorderFinished().

Additional features
Disabling reorder for specific items
The ListViewAdapter class allows you to have more control on the reorder process if necessary. It
has two methods which are related to the reordering functionality: canReorder(int position) and
reorderItem(int oldPosition, int newPosition). The first can be used to disable reordering of an item
with a specific position and the second can be used for disabling specific reorder operations. Here's
an example ofhow we can override these methods in our custom adapter implementation:

C#
public override bool CanReorder (int position)
{
if(position == 0) {
return false;
}
return true;
}

public override bool ReorderItem (int oldPosition, int newPosition)


{
if(newPosition == 0) {
return false;
}
return base.ReorderItem (oldPosition, newPosition);
}
 

With the first method we are telling the reorder behavior that the first item on the list (the one on
position 0) can't be reordered. This means that if the user applies long press on the first item it would
not be highlighted for reorder. With the second method we allow the reordering to continue only it the
newPosition is not 0. This means that if we have started reordering an item from the list and go
above the first item, the reordering item will note move to the first position. Instead, it will remain at
the position of its last successful reorder operation.

2014
Telerik UI for Xamarin

ListView for Xamarin.Android: LoadOnDemandBehavior


If your list contains a lot of items, it may not be necessary to load of them at the start. Here the
LoadOnDemandBehavior can be useful to allow the end user to request the loading of more items if
needed.There are two modes for this behavior: manual and automatic. The manual is represented
by a button at the end of the list that can be clicked to load more items. The automatic mode, as the
name suggests,automatically requests the loading of more items when the list is scrolled to a
position close to the end of the currently loaded items.

Getting Started
If you have read the Getting Started page, you already have a project with RadListView which is
populated with items of type City. In the Behaviors Overview we introduced the behaviors and now
we will go into more details about the LoadOnDemandBehavior.Here's how to add the
LoadOnDemandBehavior to your list view instance:

C#
LoadOnDemandBehavior loadOnDemandBehavior = new LoadOnDemandBehavior ();
listView.AddBehavior (loadOnDemandBehavior);
 

This will only show a button at the end of the list, but in order to actually load items, you need to add
a LoadOnDemandListener.

LoadOnDemandListener
The LoadOnDemandListener should be used to get notification that loading is requested. Here's one
simple implementation:

C#
public class LoadListener : Java.Lang.Object,
LoadOnDemandBehavior.ILoadOnDemandListener {
private ListViewAdapter listViewAdapter;
public LoadListener(ListViewAdapter adapter) {
listViewAdapter = adapter;
}
public void OnLoadStarted ()
{
City city = new City("Naples", "Italy");
listViewAdapter.Add(city);
listViewAdapter.NotifyLoadingFinished ();
}
public void OnLoadFinished ()
{
}
}
 

2015
Telerik UI for Xamarin

That will result in addition of a new city at the end of the list every time the load more button is
pressed. Note that you need to manually notify that you have finished the loading process. This can
be done with eitherListViewAdapter's notifyLoadingFinished() method or with
LoadOnDemandBehavior's endLoad(). The result is the same, so you can use the one that is more
suitable for you. Now what's left to do is to add the listener to the behavior:

C#
LoadListener loadListner = new LoadListener (cityAdapter);
loadOnDemandBehavior.AddListener (loadListner);
 

Automatic mode
The LoadOnDemandBehavior also provides an automatic mode that allow loading of items in a way
in which the end user may not even realize that all items were not loaded at the start. Here's how we
can switch the mode to automatic:

C#
loadOnDemandBehavior.Mode = LoadOnDemandBehavior.LoadOnDemandMode.Automatic;
 

What happens now is that whenever the user is near the end of the list new items are requested.
What exactly is 'near the end' is defined by the max remaining items. You can get the current value
with getMaxRemainingItems()and set a new value with setMaxRemainingItems(int). The default
value is 10. What it means for the behavior is that when the remaining items (the items that are not
yet visible to the user) become less than the value specified by that number, new items will be
requested. Let's add some numbers to make things more clear. Let's say the max remaining items
are set to 3 and the items loaded at the beginning are 10. When the user scrolls the list and reaches
the position of the 7th item(which means that there are 3 more items for him to see from the currently
loaded list) the request is issued and more items are loaded. In this mode, again, you are expected
to notify either the adapter or the behavior that you have finished with the loading so that the
indicator's state can be correctly updated.

Customization
The LoadOnDemandBehavior has one more constructor that allows you to use your own custom
Views that will be used for indicators in both modes: LoadOnDemandBehavior(View
manualDemandView, automaticDemandView). If you add your custom views, you will need to handle
manually the changes in their state (for example you can disable the button while the loading
process is in progress). In that case you will need to use the startLoad() method to initiate the load
(for example when the button is clicked).

2016
Telerik UI for Xamarin

ListView for Xamarin.Android: SwipeRefreshBehavior


If your list contains items, which may change after the initial list has been loaded, it may be good
idea to allow the users to refresh the list. That is easy with the SwipeRefreshBehavior. Simply add
an instance of this behaviorto your list view and you will get a nice indicator that will be shown when
the user swipes the list from its top.

Getting Started
If you have read the Getting Started page, you already have a project with RadListView which is
populated with items of type City. In the Behaviors Overview we introduced the behaviors and now
we will go into more details about the SwipeRefreshBehavior.Here's how to add the
SwipeRefreshBehavior to your list view instance:

C#
SwipeRefreshBehavior swipeRefreshBehavior = new SwipeRefreshBehavior ();
listView.AddBehavior (swipeRefreshBehavior);
 

This will show a loading indicator when the user swipes from the top of the list, but in order to
actually refresh the list you will need to add a SwipeRefreshListener.

SwipeRefreshListener
The SwipeRefreshListener should be used to get notification that refresh is requested. Here's one
simple implementation:

C#
public class SwipeListener : Java.Lang.Object,
SwipeRefreshBehavior.ISwipeRefreshListener {
private CityAdapter cityAdapter;
public SwipeListener(CityAdapter adapter) {
cityAdapter = adapter;
}
public void OnRefreshRequested ()
{
cityAdapter.RefreshList ();
cityAdapter.NotifyRefreshFinished ();
}
}
 

You will also need to create the refreshList() method in your adapter in order to actually refresh the
list. That method's implementation will depend on the way you load your data, but for this example
we can leave its body empty with the presumption that our initial list will not change over the time.
Pay attention to the call of the notifyRefreshFinished() which is one of the options to notify the
behavior that the refresh operation is complete. The other option isto call SwipeRefreshBehavior's
endRefresh() method and the effect will be the same — the loading indicator will hide.

2017
Telerik UI for Xamarin

Now we can add the listener to our behavior:

C#
SwipeListener swipeRefreshListener = new SwipeListener ();
swipeRefreshBehavior.AddListener(swipeRefreshListener)
 

The indicator that this behavior uses is actually the SwipeRefreshLayout from the support library. You
can get the instance of this layout withthe swipeRefresh() method in case you need to apply any
customizations to this layout, for example, change the indicator's color.

2018
Telerik UI for Xamarin

ListView for Xamarin.Android: SwipeExecuteBehavior


A popular pattern when you have a list of items is to allow the user to remove an item by swiping it to
the right (or to the left). The SwipeExecuteBehavior allows you to achieve this fairly easy. You can
also use it to reveal additional swipe content behind the item. For example a button with some
dedicated action.

Getting Started
If you have read the Getting Started page, you already have a project with RadListView which is
populated with items of type City. In the Behaviors Overview we introduced the behaviors and now
we will go into more details about the SwipeExecuteBehavior.Here's how to add the
SwipeExecuteBehavior to your list view instance:

C#
SwipeExecuteBehavior swipeExecuteBehavior = new SwipeExecuteBehavior ();
listView.AddBehavior (swipeExecuteBehavior);

2019
Telerik UI for Xamarin

This will allow you to swipe items to the direction that is opposite of the layout of your items. If we
presume that you are using the default layout, which is vertical, you can swipe items to the left and to
the right.

SwipeExecuteListener
The SwipeExecuteListener should be used to get notification that an item is swiped, so you can
perform the desired action on that item, for example to delete it. Here's one simple implementation:

C#
public class SwipeExecuteListener: Java.Lang.Object,
SwipeExecuteBehavior.ISwipeExecuteListener {

private ListViewAdapter listViewAdapter;


public SwipeExecuteListener(ListViewAdapter adapter) {
listViewAdapter = adapter;
}
public void OnSwipeStarted (int position) {
}
public void OnSwipeProgressChanged (int position, int offset, View swipeContent) {
}
public void OnSwipeEnded (int position, int offset) {
int absOffset = Math.Abs(offset);
if (absOffset > 300) {
listViewAdapter.Remove(position);
}
listViewAdapter.NotifySwipeExecuteFinished ();
}
public void OnExecuteFinished (int position) {
}
}
 

This listener will be notified when a swipe gesture starts (with onSwipeStarted(int)), when it's in
progress (with onSwipeProgressChanged(int, int, View))) and when it ends (with onSwipeEnded(int,
int)). Additionally if there is a special content that is revealed you will be notified when it is dismissed
(with onExecuteFinished(int)). We will see later how to add such content. The sample
implementation that we have just made simply checks if the item that is swipedhas travelled at least
300 pixels in any supported direction (left or right) and if it has, it is removed. Let's add this listener
to our behavior and see it in action:

C#
SwipeExecuteListener swipeExecuteListener = new SwipeExecuteListener ();
swipeExecuteBehavior.AddListener(swipeExecuteListener)
 

You can see the result in the image from the beginning of the article.

2020
Telerik UI for Xamarin

Revealing Additional Swipe Content


Now let's see the other scenario, where we need to add buttons that will be revealed, when an item
is swiped to the left or to the right. In order to achieve this we will need to override the
ListViewAdapter's onBindSwipeContentHolder(ListViewHolder holder, int position). This method is
very similar to the onBindViewHolder method that we used to populate our items. What you get as a
parameter is a view holder that will contain the swipe content and the position of the swiped item.
Here's one simple implementation of this method:

C#
public override void OnBindSwipeContentHolder (ListViewHolder holder, int position)
{
RelativeLayout mainLayout = (RelativeLayout)holder.ItemView;
LinearLayout leftLayout = (LinearLayout)mainLayout.GetChildAt(0);
LinearLayout rightLayout = (LinearLayout)mainLayout.GetChildAt(1);

Button leftButton = new Button(mainLayout.Context);


leftButton.Text = "edit";

Button rightButton = new Button(mainLayout.Context);


rightButton.Text = "delete";

leftLayout.RemoveAllViews();
leftLayout.AddView(leftButton);

rightLayout.RemoveAllViews();
rightLayout.AddView(rightButton);
}
 

This implementation heavily relies on the knowledge about the nature of the default view holder for
the swipe content, namely — that it is a RelativeLayout, which contains two child views — each of
themof type LinearLayout. In most cases that implementation is enough to display different content
on each side of the swiped item, however if you need something else you can override
onCreateSwipeContentHolder()and create a view holder that will suit your needs. If you keep the
default implementation, you will get one more benefit. When the swipe gesture ends, the item will
automatically snap to the size of the content that you have added (in our example that is the default
width of a button). If you need to snap the swiped item to another offset (or if you don't use the
default implementation), you can use the setSwipeOffset(int) method and set your preferred final
offset. Another thing that is worth mentioning is that the item will fade as you drag it towards the
edge.This is useful to hint the user that a swiped item will be removed but since this is not the case,
you can disable the fading through the behavior's setAutoDissolve(boolean) method. The default
value is true, which means that the item will fade as you swipe it.

Swipe Limits
By default, an item can be swiped away from the screen. If you need to set a limit so that it can be
swiped only 50 pixels in each direction, here's how to do it:

C#

2021
Telerik UI for Xamarin

swipeExecuteBehavior.SwipeLimitStart = -50;
swipeExecuteBehavior.SwipeLimitEnd = 50;
 

2022
Telerik UI for Xamarin

ListView for Xamarin.Android: SwipeActionsBehavior


RadListView's SwipeActionsBehavior is an upgraded version of the SwipeExecuteBehavior
addressing animation glitches and introducing new capabilities. With SwipeExecuteBehavior the
dragged item was basically a screenshot of the actual View which prevented the end-user from
interacting with the content in it. With SwipeActionsBehavior this is no longer the case, as the
end-user drags the actual View. The way SwipeActionsBehavior is used is very similar to the
approach with SwipeExecuteBehavior so you will be familiar with most of the APIs.

SwipeActionsBehavior: Getting Started


To get started using the SwipeActionsBehavior you need to create an instance of it, provide a
listener for the swipe events and add it to the RadListView instance. Additionally, you need to
override the onCreateSwipeContentHolder and onBindSwipeContentHolder methods in your
adapter and provide a View that will represent the swipe actions.

Callbacks
The following code snippet demonstrates how to instantiate the SwipeAcitonsBehavior and
provide a listener for its callbacks:

C#
public class ListViewSwipeActionsGettingStartedFragment : Fragment, ExampleFragment,
SwipeActionsBehavior.ISwipeActionsListener
{
private RadListView listView;
private SwipeActionsBehavior sap;

public override View OnCreateView(LayoutInflater inflater, ViewGroup container,


Bundle savedInstanceState)
{
View rootView = inflater.Inflate(Resource.Layout.fragment_list_view_example,
container, false);

this.listView =
(RadListView)rootView.FindViewById(Resource.Id.listView).JavaCast<RadListView>();

ArrayList dataSource = new ArrayList();

EmailMessage message = new EmailMessage();


message.title = "Tech news";
message.content = "Here is your daily LinkedIn feed with news about .NET, Java,
iOS and more...";
dataSource.Add(message);

message = new EmailMessage();


message.title = "Awaiting Payment";
message.content = "Monthly bills summary: water supply, electricity, earth
gas...";

2023
Telerik UI for Xamarin

dataSource.Add(message);

message = new EmailMessage();


message.title = "Greetings from Hawai";
message.content = "Hey Betty, we've just arrived! What a flight!...";
dataSource.Add(message);

this.listView.SetAdapter(new ListViewSwipeActionsAdapter(dataSource));

sap = new SwipeActionsBehavior();

sap.AddListener(this);

this.listView.AddBehavior(sap);

return rootView;
}

public void OnExecuteFinished(SwipeActionsBehavior.SwipeActionEvent p0)


{
}

public void OnSwipeEnded(SwipeActionsBehavior.SwipeActionEvent p0)


{

public void OnSwipeProgressChanged(SwipeActionsBehavior.SwipeActionEvent p0)


{

public void OnSwipeStarted(SwipeActionsBehavior.SwipeActionEvent p0)


{

public void OnSwipeStateChanged(SwipeActionsBehavior.SwipeActionsState p0,


SwipeActionsBehavior.SwipeActionsState p1)
{

public string Title()


{
return "Swipe Actions Getting Started";
}
}
 

There are four callbacks exposed by the SwipeActionsListener that are called depending on the
state of the SwipeActionsBehavior:

 onSwipeStarted - called when the user starts swiping an item

2024
Telerik UI for Xamarin

 onSwipeProgressChanged - continuously called while the user swipes the item


 onSwipeEnded - called when the user stops swiping the item
 onExecuteFinished - called when the swiped item is returned back to its original position
 onSwipeStateChanged - called when the state of the SwipeActionsBehavior instance
changes as a result of a user action

All of these callbacks provide a reference to an instance of the SwipeActionEvent class which
exposes the following getters:

 swipePositionWhenReleased() - returns the swiped item's offset at the moment the user
released it
 swipedItemPosition() - returns the index of the corresponding data item being swiped in
the data source assigned to the RadListView instance
 swipeView() - returns the View that is shown below the main content that is swiped. This
view comes from the onCreateSwipeContentHolder() override. This view gives you
access to the elements that represent the swipe actions.
 mainView() - returns the View that represents the main content of the item being swiped
 currentOffset() - returns the current offset of the item being swiped
 isThresholdPassed() - returns a boolean value determining whether the threshold
specified on the SwipeActionsBehavior instance has been passed

All of these getters are helpful when implementing various Swipe Actions scenarios.

Adapter overrides
Besides implementing the SwipeActionsListener interface you will also need to extend the
adapter assigned to RadListView by overriding the onBindSwipeContentHolder and
onCreateSwipeContentHolder methods:

C#
class ListViewSwipeActionsAdapter : ListViewAdapter
{

public ListViewSwipeActionsAdapter(IList items) : base(items)


{
}

public override Android.Support.V7.Widget.RecyclerView.ViewHolder


OnCreateViewHolder(ViewGroup p0, int p1)
{
LayoutInflater inflater = LayoutInflater.From(p0.Context);
View itemView =
inflater.Inflate(Resource.Layout.example_list_view_item_swipe_layout, p0, false);
SwipeToExecuteCustomViewHolder customHolder = new
SwipeToExecuteCustomViewHolder(itemView);
return customHolder;
}

public override void OnBindListViewHolder(ListViewHolder p0, int p1)

2025
Telerik UI for Xamarin

{
SwipeToExecuteCustomViewHolder customVH = (SwipeToExecuteCustomViewHolder)p0;
EmailMessage message = (EmailMessage)this.GetItem(p1);
customVH.txtTitle.Text = message.title;
customVH.txtContent.Text = message.content;
}

public override ListViewHolder OnCreateSwipeContentHolder(ViewGroup viewGroup)


{
LayoutInflater inflater = LayoutInflater.From(viewGroup.Context);
View swipeContentView =
inflater.Inflate(Resource.Layout.example_list_swipe_actions_static, viewGroup, false);
ListViewHolder vh = new ListViewHolder(swipeContentView);
return vh;
}

public override void OnBindSwipeContentHolder(ListViewHolder viewHolder, int


position)
{
View swipeContent = viewHolder.ItemView;

EmailMessage currentDataItem = (EmailMessage)this.GetItem(position);

}
}
 

What these overrides do is return a container for the swipe actions and bind it to the corresponding
data item.

Thresholds and limits


The SwipeActionsBehavior exposes the following properties via getters and setters:

 swipeThresholdStart - defines the threshold at the start of the item beyond which the
item, when released, will stick open
 swipeThresholdEnd - defines the threshold at the end of the item beyond which the item,
when released, will stick open.
 swipeLimitStart - defines the limit from the start (near end of the item) beyond which the
item cannot be swiped
 swipeLimitEnd - defines the limit from the start (far end of the item) beyond which the item
cannot be swiped.

States
While performing a swipe action the SwipeActionsBehavior switches between different swipe
states. The current swipe state is accessible vie the getSwipeState() method. The
getSwipeState() method returns an instance of the SwipeActionsState enum. The following
swipe states are defined:

2026
Telerik UI for Xamarin

 IDLE - this state is active when the user is not interacting with the list and there is no a
pending swiping procedure
 SWIPING - this state is active when the user is swiping and item
 RESETTING - this state is active when the user has released the item being swiped and it is
animated to its final position
 ACTIVE - this state is active when the swiped item has been released and animated to its
sticky position, i.e. the swipe actions are visible but there's no user interaction

Terminating the swipe procedure


The SwipeActionsBehavior exposes the endExecute() method which, when called, returns the
item being swiped to its original position and resets the swipe state.

Dock mode
The Swipe Dock Mode is used to determine where the swiped item will be docked once released.
There are two possible options:

 DockAtLimit - the default option. The swiped item is animated so that it docks at the swipe
limit, if defined.
 DockAtThreshold - the swiped item is animated so that it docks at the swipe threshold
position, if defined.

SwipeActionsBehavior: Advanced
scenarios
Using the SwipeActionsBehavior API you can implement various Swipe Actions scenarios found
in many modern mobile applications including but not limited to:

 trigger a specific action when the user swipes left or right beyond a given threshold
 display a set of actions when the user swipes beyond a given threshold
 delete an item from the list when the user swipes an item out of the view port
 indicate that a given action will happen while the user swipes the item
 animate the contents of the main view or the swipe view while the user swipes the item

Some of the scenarios are demonstrated in the SDK examples of UI for Android available on GitHub
here: https://github.com/telerik/Android-samples/tree/master/Samples-Java.

Sticky swipe actions


Using the SwipeActionsListener you can implement the popular scenario in which the swipe
actions displayed below the item's main content are animated while swiping. Here's a basic example:

C#
public void OnExecuteFinished(SwipeActionsBehavior.SwipeActionEvent p0)

2027
Telerik UI for Xamarin

{
// Fired when the swipe-execute procedure has ended, i.e. the item being swiped is
at
// its original position.
this.leftWidth = -1;
this.rightWidth = -1;
}

public void OnSwipeEnded(SwipeActionsBehavior.SwipeActionEvent p0)


{

public void OnSwipeStateChanged(SwipeActionsBehavior.SwipeActionsState oldState,


SwipeActionsBehavior.SwipeActionsState newState)
{
}

public void OnSwipeProgressChanged(SwipeActionsBehavior.SwipeActionEvent


swipeActionEvent)
{
if (swipeActionEvent.CurrentOffset() > this.leftWidth)
{
ViewGroup.LayoutParams lp = this.leftActionView.LayoutParameters;
lp.Width = swipeActionEvent.CurrentOffset();
this.leftActionView.LayoutParameters = lp;
}

if (swipeActionEvent.CurrentOffset() < -rightWidth)


{
ViewGroup.LayoutParams lp = this.rightActionView.LayoutParameters;
lp.Width = -swipeActionEvent.CurrentOffset();
this.rightActionView.LayoutParameters = lp;
}
}

public void OnSwipeStarted(SwipeActionsBehavior.SwipeActionEvent swipeActionEvent)


{
ViewGroup swipeView = (ViewGroup)swipeActionEvent.SwipeView();
this.leftActionView = swipeView.GetChildAt(0);
this.rightActionView = swipeView.GetChildAt(1);

if (leftWidth == -1)
{
leftWidth = this.leftActionView.Width;
}

if (rightWidth == -1)
{
rightWidth = this.rightActionView.Width;
}
}
 

2028
Telerik UI for Xamarin

In short, the onSwipeStarted callback is used to acquire the two View instances that represent the
left and right swipe actions. Their initial size is also stored to be able to reset it at the end of the
swipe procedure. Then, using the onSwipeProgressChanged callback we track the swipe offset
and once it goes beyond one of the swipe actions' default size we start resizing the corresponding
View.

Swipe thresholds
By using the swipeThresholdStart and swipeThresholdEnd properties we can implement a
behavior in which the item being swiped sticks open revealing an action or set of actions. Similar to
popular Mail apps, we can implement a scenario which allows the end user to archive or delete an
item from the list by using the thresholds. Take a look at the source below:

C#
public void OnExecuteFinished(SwipeActionsBehavior.SwipeActionEvent p0)
{
}

public void OnSwipeEnded(SwipeActionsBehavior.SwipeActionEvent p0)


{

public void OnSwipeProgressChanged(SwipeActionsBehavior.SwipeActionEvent


swipeActionEvent)
{
}

public void OnSwipeStateChanged(SwipeActionsBehavior.SwipeActionsState oldState,


SwipeActionsBehavior.SwipeActionsState newState)
{
}

public void OnSwipeStarted(SwipeActionsBehavior.SwipeActionEvent swipeActionEvent)


{
View swipeView = swipeActionEvent.SwipeView();
if (this.leftContentSize == -1 || rightContentSize == -1)
{
sap.SetSwipeThresholdStart((((ViewGroup)swipeView).GetChildAt(0)).Width);
sap.SetSwipeThresholdEnd((((ViewGroup)swipeView).GetChildAt(1)).Width);
}
}
 

## Action animationsA popular scenario with Swipe Actions is to animate the swipe content once the
user reaches beyond a given threshold. The purpose of this behavior is to inform the users of the
app that the corresponding swipe action will be executed. This behavior can be implemented by
using the `onSwipeProgressChanged` callback. Take a look at the following snippet:
C#
public void OnExecuteFinished(SwipeActionsBehavior.SwipeActionEvent p0)
{
// Fired when the swipe-execute procedure has ended, i.e. the item being swiped is

2029
Telerik UI for Xamarin

at
// its original position.
this.leftWidth = -1;
this.rightWidth = -1;
this.animationApplied = false;
}

public void OnSwipeEnded(SwipeActionsBehavior.SwipeActionEvent p0)


{

public void OnSwipeStateChanged(SwipeActionsBehavior.SwipeActionsState oldState,


SwipeActionsBehavior.SwipeActionsState newState)
{
}

public void OnSwipeProgressChanged(SwipeActionsBehavior.SwipeActionEvent


swipeActionEvent)
{
if (swipeActionEvent.CurrentOffset() > leftWidth)
{
ViewGroup.LayoutParams lp = this.leftActionView.LayoutParameters;
lp.Width = swipeActionEvent.CurrentOffset();
this.leftActionView.LayoutParameters = lp;
}

if (swipeActionEvent.CurrentOffset() < -rightWidth)


{
ViewGroup.LayoutParams lp = this.rightActionView.LayoutParameters;
lp.Width = -swipeActionEvent.CurrentOffset();
this.rightActionView.LayoutParameters = lp;
}

if (!this.animationApplied)
{
if (Math.Abs(swipeActionEvent.CurrentOffset()) > Math.Abs(leftWidth) * 1.5f)
{
if (swipeActionEvent.CurrentOffset() < 0)
{
this.rightActionView.GetChildAt(0).ClearAnimation();
RotateAnimation ra = new RotateAnimation(0, 360, 0.5f, 0.5f);
ra.Interpolator = new AccelerateDecelerateInterpolator();
ra.Duration = 200;
this.rightActionView.GetChildAt(0).StartAnimation(ra);
}
else if (swipeActionEvent.CurrentOffset() > 0)
{
this.leftActionView.GetChildAt(0).ClearAnimation();
RotateAnimation ra = new RotateAnimation(0, 360, 0.5f, 0.5f);
ra.Interpolator = new AccelerateDecelerateInterpolator();
ra.Duration = 200;
this.leftActionView.GetChildAt(0).StartAnimation(ra);
}

2030
Telerik UI for Xamarin

this.animationApplied = true;
}
}
}

public void OnSwipeStarted(SwipeActionsBehavior.SwipeActionEvent swipeActionEvent)


{
this.animationApplied = false;
this.swipeView = (ViewGroup)swipeActionEvent.SwipeView();
this.leftActionView = (ViewGroup)this.swipeView.GetChildAt(0);
this.rightActionView = (ViewGroup)this.swipeView.GetChildAt(1);

if (leftWidth == -1)
{
leftWidth = this.leftActionView.Width;
}

if (rightWidth == -1)
{
rightWidth = this.rightActionView.Width;
}
}
 

In this case, besides resizing the swipe action's container, we track the swiped offset and animate
the action's label once the offset passes a certain threshold.

2031
Telerik UI for Xamarin

ListView for Xamarin.Android: StickyHeaderBehavior


If your list contains group headers as demonstrated in Group, Sort and Filter topic, you can use the
StickyHeaderBehavior which will 'freeze' the group header of the top item:

This means the GroupHeader will remain sticked to the top corner of the ListView while scrolling
through the items until the whole group is scrolled away. As you scroll through the next group, the
currently sticked group header will be pushed by the next group header.

Here's the code for this to work - just create an instance of StickyHeaderBehavior class and
assign it to the ListView through AddBehavior method:

C#
StickyHeaderBehavior stickyHeaderBehavior = new StickyHeaderBehavior();
listView.AddBehavior(stickyHeaderBehavior);
 

2032
Telerik UI for Xamarin

ListView for Xamarin.Android: CollapsibleGroupsBehavior


If your list contains group headers as demonstrated in this article, you can use the
CollapsibleGroupsBehavior which will allow users to collapse and expandgroups by tapping on their
headers.

Getting Started
The ListViewDataSourceAdapter's default header template contains an image that shows whether a
group is expanded or collapsed. Since our example uses its own adapter - CityDataSourceAdapter,
we will need toadd an image element that will hold an indication arrow. Change the
city_group_item.xml added in the article for grouping to include an image:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

2033
Telerik UI for Xamarin

android:orientation="horizontal"
android:background="#FF0099CC"
android:padding="8dp"
android:layout_width="match_parent" android:layout_height="match_parent">
<ImageView
android:id="@+id/groupHeaderCollapseImage"
android:layout_gravity="center_vertical"
android:src="@drawable/ic_collapse"
android:visibility="gone"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
<TextView
android:id="@+id/headerTextView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textStyle="bold"
android:textColor="#FFFFFF"
android:textSize="14sp"
android:padding="8dp" />
</LinearLayout>
 

Now we can create a new instance of the collapsible groups behavior and add it to the list view:

C#
CollapsibleGroupsBehavior collapsibleGroupsBehavior = new CollapsibleGroupsBehavior
();
listView.AddBehavior (collapsibleGroupsBehavior);
 

Customization
If you need to change the image that is used for indication of whether the group is collapsed you can
use the setCollapseImageResource(int) method. The image will be automatically rotated when the
group is collapsed. You can alsoprovide a different image of the collapsed state by using
setExpandImageResource(int). The default value is -1 indicating that instead of another resource
the upside down version of the collapse image will be used.

Collapse Group Listener


The CollapseGroupListener can be used to get notification that a group is collapsed or expanded.
Here's one simple implementation:

C#
public class CollapseListener : Java.Lang.Object,
CollapsibleGroupsBehavior.ICollapseGroupListener {

Context context;

2034
Telerik UI for Xamarin

public CollapseListener(Context context) {


this.context = context;
}

public void OnGroupCollapsed (Java.Lang.Object p0)


{
Toast.MakeText (context, String.Format (
"Group {0} was collapsed", p0.ToString ()), ToastLength.Short).Show ();
}

public void OnGroupExpanded (Java.Lang.Object p0)


{
Toast.MakeText (context, String.Format (
"Group {0} was expanded", p0.ToString ()), ToastLength.Short).Show ();
}
}
 

Now we can add the listener to our behavior:

C#
CollapseListener listener = new CollapseListener (Context);
collapsibleGroupsBehavior.AddListener (listener);
 

Manual collapse/expand
With CollapsibleGroupsBehavior you can also manually change whether a group is expanded or
collapsed with changeIsGroupCollapsed(Object group).To determine the current state of a group you
can use isGroupCollapsed(Object group).You can also expand all groups or collapse them by using
expandAll() or collapseAll().

2035
Telerik UI for Xamarin

NumberPicker for Xamarin.Android:


Overview
RadNumberPicker for Xamarin.Android is a customizable input control for numeric data. It allows the
user to set or edit a number using the decrease and increase buttons or directly enter it in the input
field.

You have control over the allowed minimum and maximum values, the increase/decrease step when
clicking the buttons as well as the format of the value.

2036
Telerik UI for Xamarin

NumberPicker for Xamarin.Android: Getting Started


To use RadNumberPicker a dependency to the Telerik.Xamarin.Android.Input.dll library must be
added.

Creating RadNumberPicker is like creating any other widget:

C#
RadNumberPicker picker = new RadNumberPicker(context);
 

RadNumberPicker can be customized with the following properties:

 Value - Setting the value outside the [minimum, maximum] range will result in the value
being clamped to that range.
 Step - Defines the step by which the value will increase when the plus and minus buttons are
pressed. If the [min, max] range is not divisible by the step the number pickerwill not be able
to reach the maximum or minimum value.
 Minimum - Defines the max value of the number picker. The Value can never become more
than max.
 Maximum - Defines the min value of the number picker. The Value can never become less
than min.
 FormatString - The format string can be used to specify specific text for RadNumberPicker.
The format string functionality is actually composed of three sub properties. These are
SingleFormatString, PluralFormatString and ZeroFormatString. When RadNumberPicker's
value is equal to 1 SingleFormatString will be used, ZeroFormatString for 0 and forthe rest of
the values PluralFormatString will be used.

Finally RadNumberPicker has AddPropertyChangeListener() and


RemovePropertyChangedListener() methods that can be used to listen for changes in the number
picker. For example to listen for value changes the following code is in order:

C#
picker.AddPropertyChangedListener(new MyPropertyChangedListener());

public class MyPropertyChangedListener : Java.Lang.Object, IPropertyChangedListener {


public void OnPropertyChanged (string propertyName, Java.Lang.Object value)
{
if(propertyName.Equals("Value")) {
double newValue = (Double)value;
// do something with the new value.
}
}
}
 

2037
Telerik UI for Xamarin

SpreadStreamProcessing for
Xamarin.Android: Overview
This article briefly explains the specifics of RadSpreadStreamProcessing - what is spread streaming,
how it works compared to other libraries and when to use it.

RadSpreadStreamProcessing is part of the Telerik Document Processing libraries. The full


documentation for this component is available at
http://docs.telerik.com/devtools/document-processing/libraries/radspreadstreamsprocessing.
 

What is Spread Streaming?


Spread streaming is a document processing paradigm that allows you to create big spreadsheet
documents with great performance and minimal memory footprint.

The key for the memory efficiency is that the spread streaming library writes the spreadsheet content
directly to a stream without creating and preserving the spreadsheet document model in memory.
Each time an exporter object is disposed, the set values are written into the stream. This allows you
to create large documents with an excellent performance.

Key Features
Some of the features you can take advantage of are:

 Export to XLSX or CSV files

2038
Telerik UI for Xamarin

 Writing directly into a stream


 Grouping
 Styling and formatting cells
 Hidden rows and columns
 Freezing panes

When to Use RadSpreadStreamProcessing


You can use RadSpreadStreamProcessing to create and export large amount of data with a low
memory footprint and great performance.

Required references
In order to use the RadSpreadStreamProcessing you have to add references to the following
assemblies:

 Telerik.Zip.dll
 Telerik.Documents.SpreadsheetStreaming.dll

2039
Telerik UI for Xamarin

TabView for Xamarin.Android: Overview


RadTabView control allows developers to create user interfaces similar to the android tab view (view
pager and app bar combo) but is a lot easier to use. On top of that, the tabs of RadTabView can be
positioned on all four sides of the parent view (typically of the main view).

Navigation between the different tabs can be done either by tapping on the individual tabs or swiping
over the current tab content to display the tab adjacent to it.

Tabs alignment
Developers can set the tabs alignment if the tabs are less than max tabs. The alignment can be left,
right, center and stretch.By default the tabs are stretched to fill the available tab view area.

Change listeners
Finally developers can listen for tab view events by adding a listener. The listener is notified before
and after a tab is selected or deselected.Before a tab is selected or deselected the callback allows
the developer to cancel the selection/deselection. A tab can either be selected with a tap gesture or
through code by setting the selectedTab property.

The listener is also notified when the tab view needs the content view of a tab. This happens only if a
tab without a content view is added initially. This lazy loading of the content view helps when the tab
view contains content that loads slowly because of network requests or some other time-consuming
operation.

2040
Telerik UI for Xamarin

TabView for Xamarin.Android: Getting Started


To use RadTabView Beta a reference to the Primitives library first must be added to your project.
Then simply create an instance:

C#
RadTabView tabView = new RadTabView(this.Context);
 

Then add some tabs:

C#
tabView.Tabs.Add(new Tab("Tab 1"));
tabView.Tabs.Add(new Tab("Tab 2"));
tabView.Tabs.Add(new Tab("Tab 3"));
 

Add a TabViewChangeListener:

C#
tabView.AddChangeListener(this);
 

Finally, implement the change listener methods. One of those methods is called to create a content
view for each tab:

C#
public Java.Lang.Object GetContentViewForTab(Tab tab)
{
TextView contentView = new TextView(this.Context);
contentView.Text = "Content view for " + tab.Title;
contentView.Gravity = GravityFlags.Center;
return contentView;
}
 

That's all there is to it. The result is a fully functioning tab view:

2041
Telerik UI for Xamarin

2042
Telerik UI for Xamarin

TabView for Xamarin.Android: Tabs Position


RadTabView can position its tabs on its four edges: Top, Left, Right and Bottom. To set the tabs
position simply set the TabsPosition property:

C#
tabView.TabsPosition = TabsPosition.Top;
 

Furthermore if the TabWidth property is set, and the total width of the available tabs is less than the
available screen area, developers can set TabAlignment. The alignment can be Left, Right, Top,
Bottom, Center and Stretch. For example:

C#
tabView.TabStrip.TabsAlignment = TabsAlignment.Center;
 

Max visible tabs


The used inside the TabView TabStrip provides a MaxVisibleTabs property. It determines how many
tabs will be shown on screen. If there are more tabs they will be shown in a scrollview;

C#
tabView.TabStrip.Layout.MaxVisibleTabs = 5;
 

2043
Telerik UI for Xamarin

TabView for Xamarin.Android: Listening for changes


RadTabView Beta will notify its TabViewChangeListener objects before and after a tab selection
occurs. Also the listeners will be asked for a tab's content view if it does not have one.

Here is an example implementation of the selection notifications:

C#
public bool OnSelectingTab(Tab tabToSelect)
{
return false;
}

public void OnTabSelected(Tab selectedTab, Tab deselectedTab)


{
if (deselectedTab != null)
{
Log.Debug("TabView deselected: ", deselectedTab.Title);
}
Log.Debug("TabView selected: ", selectedTab.Title);
}
 

Content view callback example:

C#
public Java.Lang.Object GetContentViewForTab(Tab tab)
{
TextView contentView = new TextView(this.Context);
contentView.Text = "Content view for " + tab.Title;
contentView.Gravity = GravityFlags.Center;
return contentView;
}
 

2044
Telerik UI for Xamarin

ZipLibrary for Xamarin.Android: Overview


Have you ever wondered how to increase the responsiveness of your applications by compressing
the data that you send over the internet? With the new Zip Library you can compress data like
images, docx or pdf files and send them over the wire. Thus, you will achieve fast and secure
transactions.

This is a list with short descriptions of the top-of-the-line features of Telerik's Zip Library control:

 Easy to use API: The Zip Library exposes flexible and easy API to provide you with full
control over the compressed data.
 Load or create ZIP files: You can load data from existing ZIP files, create new ones and edit
ZIPs that can be used by other applications. You can also create ZIP files in memory or add
data to ZIP file from stream.
 Support for large files: The Zip Library works seamlessly with large files.
 Support for encryption: You can protect your ZIP file with password for better security.

Required references
Please note, that the RadZipLibrary is available only for Xamarin.Android.
 
In order to use the Zip Library you have to add references to the following assemblies:

 Telerik.Zip.dll

RadZipLibrary is part of the Telerik Document Processing libraries. The full documentation for this
component is available at http://docs.telerik.com/devtools/document-processing/libraries/radziplibrary.
 

2045
Telerik UI for Xamarin

ScrollView for Xamarin.Android: Overview


RadScrollView is widely based on the traditional Android ScrollView component and extends its
functionality by introducing support for simultaneously scrolling horizontally and vertically. The
component exposes API to control the scrolling behavior whereas three scrolling modes are
available:

 Horizontal
 Vertical
 Both

The component preserves the API of the original ScrollView as documented on the official Android
Documentation website.

2046
Telerik UI for Xamarin

ScrollView for Xamarin.Android: Getting started


To be able to use RadScrollView you need to reference the following libraries:

 Telerik.Xamarin.Android.Common.dll
 Telerik.Xamarin.Android.Primitives.dll

RadScrollView is defined in the Primitives library in the com.telerik.widget.primitives.panels package.


The following code snippet demonstrates how to add an instance of the component in your XML
layout:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".examples.panels.ScrollViewFragment">
<com.telerik.widget.primitives.panels.RadScrollView
android:id="@+id/radScrollView"
app:scrollMode="horizontal|vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">

//Your content comes here

</FrameLayout>
</com.telerik.widget.primitives.panels.RadScrollView>
 

As you can see, the ScrollMode is set to be horizontal|vertical in the XML definition, and a
combination of the SCROLLING_MODE_VERTICAL and SCROLLING_MODE_HORIZONTAL flags
in the programmatic definition.

2047
Telerik UI for Xamarin

SideDrawer for Xamarin.Android: Overview


RadSideDrawer is a component can show a hidden view that contains navigation UI or common
settings. A popular application that uses the drawer UI is the Android Playstore app.The hidden view
can be displayed with a flick gesture and can be shown from any of the four edges of the screen.
The view is also displayed with a transition which can be chosen from a set of pre-defined
transitions.A completely new and custom transition can also be easily created. In order to use
RadSideDrawer developers must add dependencies to the Common and Primitives libraries.

2048
Telerik UI for Xamarin

SideDrawer for Xamarin.Android: Overview Getting


Started
RadSideDrawer is a component similar to Android's DrawerLayout but it provides many transitions
out of the box. The transitions are also extensible so users can provide their own custom transitions
if necessary.

RadSideDrawer has two main properties you need to set in order to get the full drawer experience.
These properties are MainContent and DrawerContent. They are two separate View objects. The
drawer content is displayed beside the main content either through a swipe gesture or via code.
When the drawer content is visible, the main content fades out indicating that interaction with it is not
possible until the drawer is closed.

The transitions are groups of animations that are started when the user opens the drawer either
through code or gestures.

Here the drawer part is not visible with only the main content showing:

2049
Telerik UI for Xamarin

If the user swipes from the left edge to the right, the drawer appears and fades the main content:

2050
Telerik UI for Xamarin

Below is a very simple code example that shows the minimum steps required to display
RadSideDrawer with some static content:

C#
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);

SetContentView (Resource.Layout.Main);

RadSideDrawer drawer = new RadSideDrawer (this);


drawer.SetMainContent (Resource.Layout.drawer_main_content);
drawer.SetDrawerContent (Resource.Layout.drawer_side_content);

// There are also MainContent and DrawerContent properties that accept a View
directly.

ViewGroup rootView = (ViewGroup)this.FindViewById (Resource.Id.rootView);

2051
Telerik UI for Xamarin

rootView.AddView (drawer);
}
 

Please note that SetMainContent() and SetDrawerContent() have two overloads each. One overload
accepts a resource id as the argument and the other accepts a View object directly with the resource
id overload provided for convenience.
 

2052
Telerik UI for Xamarin

SideDrawer for Xamarin.Android: Features


Using transitions
RadSideDrawer provides many transitions out of the box. Some of them slide the drawer on top of
the main content. Others push the main content to the side and so on. Here are a few transitions
classes:PushTransition, FallDownTransition, RevealTransition, SlideAlongTransition,
ScaleUpTransition...The rest can be found in the
com.telerik.android.primitives.widget.sidedrawer.transitions package.

To set a transition simply create a new instance of the transition of choice and pass it to the
drawer.setDrawerTransition() method.

C#
drawer.DrawerTransition = new PushTransition();
 

Each transition can have a specific duration (setDuration()) and an interpolator (setInterpolator()) that
determines the behavior of the animations it encapsulates.Developers can also listen for the end of
the transition by setting a DrawerTransitionEndedListener (addTransitionEndedListener()).

Adding drawer change listeners


RadSideDrawer exposes notifications for when the drawer is opened, closed, opening and closing.
The opened and closed notifications are invoked after the open or close transition has ended
whereasopening and closing are invoked as soon as the close/open operation is started and provide
means to cancel the open/close operation. For example:

C#
public class DrawerListener : Java.Lang.Object, IDrawerChangeListener
{
public void OnDrawerClosed (RadSideDrawer p0)
{

public bool OnDrawerClosing (RadSideDrawer p0)


{
// Return true to cancel closing.
return false;
}

public void OnDrawerOpened (RadSideDrawer p0)


{

public bool OnDrawerOpening (RadSideDrawer p0)


{

2053
Telerik UI for Xamarin

// Return true to cancel opening.


return false;
}
}

drawer.AddChangeListener (new DrawerListener());


 

Customizing the fade layer


RadSideDrawer's fade layer can be swapped with any View object. From simple views with a
background to complex custom renderings if required. The fade layer can be changed by calling
drawer.setFadeLayer(); with the specified view. When the drawer is opened, this fade layer is
stretched over the main content and animated to an opacity of 0.6 by default.

Setting the drawer location and using gestures


The side drawer can be shown from all edges of the screen, not just the left side. For example:

C#
drawer.DrawerLocation = DrawerLocation.Right;
 

The gesture can only be initiated from the edge of the screen and the touchable area can be
tweaked with the setTouchTargetThreshold() method. It accepts the number of pixels from the
screen that will be treated as touchable. Bydefault it is 20dp.

C#
drawer.TouchTargetThreshold = (int)Com.Telerik.Android.Common.Util.GetDimen
((int)Android.Util.ComplexUnitType.Dip, 30.0f);
 

Also once the drawer is opened, developers decide if they want the drawer closed on outside tap or
not:

C#
drawer.TapOutsideToClose = true;
 

Another way to close the drawer is to use the back button on the device.Cosing on back press can
be enabled or disabled with setCloseOnBackPress().

C#
drawer.CloseOnBackPress = true;
 

Finally the side drawer can be locked in place. It can be locked in both the closed and opened
states. The lock only affects screen gestures. The lock can be bypassed through code if the
developer decides to call setIsOpen().

2054
Telerik UI for Xamarin

C#
drawer.IsLocked = true;
 

Setting drawer size


The drawer content by default is left to be auto sized in the main dimension. The main dimension is
dictated by the drawer location. For example if the drawer is on the left or right the main dimension
would the x axis (the width), otherwise it would be the y axis (height). The content by default will take
as much space as it needs. By set calling setDrawerSize(); with a number different than 0 the drawer
content will be arranged with the provided size.

Setting the drawer size back to 0 reverts the drawer content to being auto sized.

C#
drawer.DrawerSize = (int)Com.Telerik.Android.Common.Util.GetDimen
((int)Android.Util.ComplexUnitType.Dip, 300.0f);
 

Toolbar/ActionBar integration
RadSideDrawer can be used with the native Toolbar and ActionBar components. To make the
connection between RadSideDrawer and the toolbar developers need to use the SideDrawerToggle
class.

For example:

C#
SideDrawerToggle drawerToggle = new SideDrawerToggle(drawer, toolbar);
 

Then the drawerToggle variable should be kept in memory for the toolbar/drawer interaction to
remain automatic.Developers also have to call toggle.setDrawerOpenIcon() with a drawable or a
resource id so that the toolbar/action bar displaysthe proper drawer toggle icon (commonly a
hamburger icon).

SideDrawerToggle can only be used with the Toolbar class from the support library.
android.support.v7.widget.Toolbar to be more specific.
 

2055
Telerik UI for Xamarin

Gauges for Xamarin.Android: Overview


RadGaugeView is a highly customizable component that allows you to show the current status of a
value within a range of upper and lower bounds, illustrate progress towards a goal or a summary of a
fluctuating metric.

2056
Telerik UI for Xamarin

Gauges for Xamarin.Android: Getting Started


This article demonstrates how to setup an instance of RadGaugeView from scratch.

Initialization
In order to use RadGuageView you need to add reference to the Gauges library which is part of
Telerik UI for Xamarin.Android.

After your project is set up referencing the library you are ready to add a gauge to your activity.
RadGaugeView is a base class for TelerikUI gauges so you need to instantiate a subclass. The most
common way is to describe the gauge in the XML layout of your activity.

XML
<com.telerik.widget.gauge.RadRadialGaugeView
android:id="@+id/radial_gauge"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"/>
 

Then you can access the gauge in your activity and add scales and indicators to it.

C#
RadRadialGaugeView gauge =
(RadRadialGaugeView)rootView.FindViewById(Resource.Id.radial_gauge);
 

Adding scales
After the gauge is loaded in the activity/fragment you are ready to add scales and indicators to it.
The base class that represents a scale in RadGaugeView is GaugeScale. It has maximum and
minimum values and a set of indicators that show values on the scale. You can also set the count of
labels and ticks drawn on the scale. The code below demonstrates how to instantiate and configure
a scale:

C#
GaugeRadialScale scale = new GaugeRadialScale(this.Context);
scale.Minimum = 0;
scale.Maximum = 6;
scale.MajorTicksCount = 7;
scale.MinorTicksCount = 9;
scale.LabelsCount = 7;
scale.LineVisible = false;
scale.Radius = 0.95f;
scale.TicksOffset = 0;
 

2057
Telerik UI for Xamarin

After the scale is configured you are ready to add indicators to it. In this example you will add a radial
needle and radial bar indicators to the scale. The needle points to a specific value and the bar shows
a range on the scale.

C#
int[] colors = new int[] {
Color.Rgb(221,221,221),
Color.Rgb(157,202,86),
Color.Rgb(240,196,77),
Color.Rgb(226,118,51),
Color.Rgb(167,1,14)
};

float rangeWidth = scale.Maximum / colors.Length;


float start = 0;
foreach (var color in colors)
{
GaugeRadialBarIndicator indicator = new GaugeRadialBarIndicator(this.Context);
indicator.Minimum = start;
indicator.Maximum = start + rangeWidth;
indicator.FillColor = color;
scale.AddIndicator(indicator);
start += rangeWidth;
}

GaugeRadialNeedle needle = new GaugeRadialNeedle(this.Context);


needle.Value = 2;
scale.AddIndicator(needle);
 

The last thing that you need to do is to add the scale to the gauge:

C#
gauge.AddScale(scale);
 

2058
Telerik UI for Xamarin

2059
Telerik UI for Xamarin

Gauges for Xamarin.Android: Indicators


Indicators in RadGaugeView are visual elements that point to value or visualize a range of values on
a scale. They should be added to a scale and their values are aligned to the scale the indicators
belong to.

Bar indicators
Bar indicators are used to visualize a range of values on a scale. Customization of the bars is trivial.

2060
Telerik UI for Xamarin

Changing their range, color, position and width is achieved by just setting a property. Bar indicators
in RadGaugeView have a default animation that animates their maximum value. Below is an
example how to create a bar indicator and add it to GaugeScale.

C#
int[] transparentColors = new int[] {
Color.Argb(100,224,151,36),
Color.Argb(100,196,241,57),
Color.Argb(100,132,235,247)
};

int[] colors = new int[] {


Color.Argb(255,224,151,36),
Color.Argb(255,196,241,57),
Color.Argb(255,132,235,247)
};

for (int i = 0; i < 3; i++)


{
GaugeRadialBarIndicator trnspIndicator = new GaugeRadialBarIndicator(Activity);
trnspIndicator.Minimum = 0;
trnspIndicator.Maximum = 100;
trnspIndicator.FillColor = transparentColors[i];
trnspIndicator.BarWidth = 0.2f;
trnspIndicator.Location = 0.5f + i * 0.25f;
scale.AddIndicator(trnspIndicator);

GaugeRadialBarIndicator indicator = new GaugeRadialBarIndicator(Activity);


indicator.Minimum = 0;
Random r = new Random();
indicator.Maximum = r.Next(100);
indicator.Animated = true;
indicator.AnimationDuration = 500;
indicator.BarWidth = 0.2f;
indicator.Location = 0.5f + i * 0.25f;
indicator.FillColor = colors[i];
indicator.Cap = GaugeBarIndicatorCapMode.Round;
scale.AddIndicator(indicator);
}
 

Note that the indicator's width and location are normalized values. They are calculated based on the
size of the gauge that displays them.

2061
Telerik UI for Xamarin

Needle indicator
The needle indicator is used to point to a specific value. You can easily customize its length, top and
bottom width. It is also possible to change the radius of the needle's circle or to offset the needle by
just setting the corresponding properties. The length of the needle is again value between 0 and 1.
The supports animations when its value is changed.

C#
needle = new GaugeRadialNeedle(Activity);
needle.Length = 0.8f;
needle.BottomWidth = 8;
needle.TopWidth = 8;
 

2062
Telerik UI for Xamarin

Gauges for Xamarin.Android: Scales


GaugeScale is a base class for the scales in RadGaugeView. The scale is a ViewGroup that has
range and a set of indicators that are rendered according to the range of the scale they belog to. The
scale manages the count and appearance of its ticks and labels. GaugeRadialScale also allows
setting its start and sweep angles. It is possible to add more than one scale to a gauge as this
example demonstrates.

Setup scales
GaugeScale allows you to customize every aspect of its visual appearance. You can set the count of
ticks and labels or choose to draw then inside or outside the scale. We are going to create an
configure 2 scales that will be added to a radial gauge. First thing to do is to instantiate a scale and
set its minimum and maximum values:

C#
GaugeRadialScale scale1 = new GaugeRadialScale(Activity);
scale1.LineVisible = true;
scale1.Minimum = 34;
scale1.Maximum = 40;
 

This scale is going to be the inner scale of the gauge so we are going to change its radius. The
radius should be a value between 0 and 1 since the scale works with normalized values. It will then
be calculated base on the size of the gauge. We are also going to change the stroke's width.

C#
scale1.Radius = 0.6f;
scale1.StrokeWidth = 2;
 

Now we can customize the appearance of the ticks and labels.

C#
scale1.LabelsColor = Color.Gray;
scale1.LabelsCount = 7;
scale1.MajorTicksCount = 7;
scale1.LabelsPaint.TextSize = 30;
scale1.TicksOffset = 0;
scale1.LabelsOffset = 0.1f;
 

The same way we are going to create the second scale. The difference is that this time we are going
to draw the labels and the ticks outside the scale.

The scale are ready to be added to the gauge.

Add indicators to GaugeScale

2063
Telerik UI for Xamarin

We now have a gauge with 2 scales, however to be able to show values on the gauge we need to
add some indicators. We are going to add 2 radial bar indicators and a needle to the inner scale of
the gauge. Below is a helper method that returns bar indicator.

C#
private GaugeIndicator GetIndicator(float min, float max, int color)
{
GaugeRadialBarIndicator indicator = new GaugeRadialBarIndicator(Activity);
indicator.Minimum = min;
indicator.Maximum = max;
indicator.FillColor = color;
indicator.Location = 0.69f;
indicator.BarWidth = 0.08f;
return indicator;
}
 

And here is how to add the indicators:

C#
GaugeRadialNeedle needle = new GaugeRadialNeedle(Activity);
needle.Value = 36.5f;
needle.Length = 0.5f;
needle.TopWidth = 8;
needle.BottomWidth = 8;
scale1.AddIndicator(needle);
scale1.AddIndicator(GetIndicator(34, 36, Color.Blue));
scale1.AddIndicator(GetIndicator(36.05f, 40, Color.Red));
 

The last thing to do is to set titles to the gauge.

C#
gauge.Title.Text = "celsius";
gauge.Subtitle.Text = "fahrenheit";
gauge.TitleVerticalOffset = 90;
 

Here is how the gauge should look like.

2064
Telerik UI for Xamarin

2065
Telerik UI for Xamarin

Gauges for Xamarin.Android: Animations


Built-in animations
RadGaugeView has built-in animations that allows animating its indicators. Turning the animations
on is as easy as setting 2 properties. You should use Animated boolean property of an indicator to
allow the animations and then use AnimationDuration which, as its name says, is used to set the
duration of the animation.

C#
needle.Animated = true;
needle.AnimationDuration = 500;
 

You can also set a timing function using TimeInterpolator.

C#
needle.Interpolator = new AccelerateDecelerateInterpolator();
 

After the indicator's animations are turned on, when a change in its value occurs runtime, the
indicator will be animated from the previous to the new value. It is also possible to set a value from
which the animations start every time the value is changed. This can be achieved through indicator's
AnimationStartValue property.

2066
Telerik UI for Xamarin

Xamarin.iOS Wrappers
Telerik UI for Xamarin suite includes Xamarin.iOS wrappers built on top of truly native iOS
components, allowing you to build unique and visually stunning iOS applications. Our controls give
you great customization flexibility to accommodate as many app scenarios as possible.

To learn more please visit the Telerik UI for Xamarin product overview page.

Download Free TrialDownload Free Trial

Controls Overview
Our suite features the following controls for development with Xamarin.iOS:

 Alert: Highly customizable alert view component that offers different predefined animations,
easy to use Block API, many customization options.
 AutoCompleteTextView: An input control that provides users with suggestions, based on the
text or characters they’ve already typed into the search bar. Once the autocomplete shows a
list of suggestions, the user can select one or more of them. The control provides means for
easy customization and data management. To make working with data easier for developers,
TKAutoCompleteTextView works seamlessly with the Telerik DataSource control which
serves as a mediator between the raw suggestions data and the UI component which serves
as suggestion view.
 Calendar: A calendar control that features week, month and year views as well as multiple
dates selection and flexible API for customization.
 Chart: A versatile charting component that offers full customization, great performance and
intuitive object model. Its API allows creating complex charts with stunning animations and
appearance.
 DataForm: A customizable component that allows you to easily create a form for collecting or
editing business object data. It is ideal for settings or registration/login pages. TKDataForm
supports different commit modes allowing you to commit property values one by one or
commit the whole form at once. You could also determine at what moment the properties
should be validated choosing between three validation modes. The control lets you use rich
set of editors out of the box.
 DataSource: It is a non-visual component that consumes data from various sources. It
supports data shaping operations like sorting, filtering and grouping. It adopts the most used
data enabled UI controls in iOS: UITableView and UICollectionView to automate the
presentation of its data. TKDataSource works perfectly with TKListView, TKChart and
TKCalendar too.
 Gauges: A highly customizable component that allows you to show the current status of a
value within a range of upper and lower bounds, illustrate progress towards a goal or a
summary of a fluctuating metric.
 ListView: Provides the most frequently used functionalities associated with a ListView
scenario in one framework, eliminating the overhead of integrating multiple solutions from
different authors. To make working with data easier for developers, the control works
seamlessly with the DataSource control, which serves as a mediator between the raw data
that needs to be displayed and the UI component.
 SideDrawer: Helps you add extra space to your application. It extends the popular slide-out

2067
Telerik UI for Xamarin

design pattern which is mainly associated with navigational purposes. The control is highly
customizable and allows developers to embed any type of content inside the sliding panel.

Trial Version and Commercial License


Telerik UI for Xamarin library is a commercial UI library. You are welcome to explore its full
functionality and get technical support from the team when you register for a free 30-day trial. To use
it commercially, you need to purchase a license. Feel free to review the Telerik UI for Xamarin
License Agreement to get acquainted with the full terms of use.

Support Options
For any issues you might encounter while working with Telerik UI for Xamarin, use any of the
available support channels:

 UI for Xamarin license holders and active trialists can take advantage of the outstanding
customer support delivered by the developers building the library. To submit a support ticket,
use the UI for Xamarin dedicated support system.
 UI for Xamarin forums are part of the free support you can get from the community and from
the UI for Xamarin team on all kinds of general issues.
 UI for Xamarin feedback portal provides information on the features in discussion and also the
planned ones for release.
 You may still need a tailor-made solution for your project. In such cases, go straight to
Progress Services.

Learning Resources
 Knowledge Base
 Support Resources Hub Page

2068
Telerik UI for Xamarin

Telerik UI for Xamarin.iOS: Getting Started


This article explains how to start using Telerik UI for Xamarin.iOS controls inside a Xamarin.iOS
application.

System Requirements
To build for Xamarin.iOS, the following are required:

 the latest version of Visual Studio or Visual Studio for Mac


 the latest iOS SDK
 the latest version of Xcode
 the minimum version of macOS required by Xcode

For specific version requirements, refer to the latest Xamarin.iOS release notes.

Reference the Telerik.Xamarin.iOS library from your project


In order to use any of our Xamarin.iOS controls inside your Xamarin.iOS application, you would need
to add a reference to the Telerik.Xamarin.iOS.dll assembly.

Check Download Product Files topic for detailed instructions on how to navigate to Telerik UI for
Xamarin download page. Download "Telerik_UI_for_Xamarin_[version]_[license].zip" file which
contains the needed assembly for Xamarin.iOS development (named Telerik.Xamarin.iOS.dll) inside
Binaries/iOS folder.
 

1. Click on iOS App (Xamarin) project template in Visual Studio/Visual Studio for Mac to create
a new Xamarin.iOS solution:

2069
Telerik UI for Xamarin

2. Go through the next steps to configure the solution location, minimum iOS version, etc.
3. Add a reference to the Telerik.Xamarin.iOS.dll library by right-clicking the References of your
project and selecting Edit References....

4. Your solution is now ready to use Telerik UI for Xamarin.iOS.

2070
Telerik UI for Xamarin

Opening the Examples solution


Examples solution that shows how to use the controls when developing through Xamarin.iOS is
included in the Telerik UI for Xamarin zip file provided for manual installation.

Telerik_UI_for_Xamarin_[version]_[license].zip, where [version] marks the release and [license] is


replaced with Dev or Trial depending on the license, is available for download from the Downloads
section of your Telerik account. Unzip the archive and go to Examples folder - Xamarin.iOS solution is
available in the iOS folder.

In addition, the Examples solution is included as part of the Telerik UI for Xamarin MSI installation.
You can find it in the "[installation-path]/Telerik UI for Xamarin [version]/Examples" folder.

2071
Telerik UI for Xamarin

Alert for Xamarin.iOS: Overview


TKAlert is a highly customizable alert view component that offers different predefined animations,
easy to use Block API, many customization options.

TKAlert features include:

Key Features:

2072
Telerik UI for Xamarin

 Device orientation change support


 Custom view support
 CustomView
 Easy to use block API
 Fully customizable
 Predefined appear/dismiss animations
 Blurred or dimmed background style
 Parallax effect
 Custom frame support
 Auto dismiss after a specified time interval
 Swipe or pan dismiss options
 Horizontal/vertical buttons layout

Demos for Alert control can be found in our Native Xamarin.iOS examples.
 

2073
Telerik UI for Xamarin

Alert for Xamarin.iOS: Getting Started


This quick start tutorial demonstrates how to create a simple iOS application with TKAlert.

Setting up TKAlert
Now that our project is created and the TelerikUI.framework is added, we can start referencing and
using the TelerikUI types:

Open your UIViewController file and add a reference to Telerik UI header file:

C#
using TelerikUI;
 

Note that starting with Xcode 6 Apple doesn't generate the precompiled headers file automatically.
That is why you should add import the UIKit framework before importing TelerikUI:

C#
using UIKit;
 

In the ViewDidLoad method create a new instance of TKAlert and set its title and message
properties:

C#
TKAlert alert = new TKAlert ();
alert.Title = "Chicken or the egg";
alert.Message = "Which came first, the chicken or the egg?";
 

The next step is to add a few actions to TKAlert:

C#
alert.AddActionWithTitle("Egg", (TKAlert al, TKAlertAction action) => {
TextLabel.Text = "It was the egg!";
return true;
});

alert.AddActionWithTitle("Chicken", (TKAlert al, TKAlertAction action) => {


TextLabel.Text = "It was the chicken!";
return true;
});
 

Now let's show TKAlert on the screen:

2074
Telerik UI for Xamarin

C#
alert.Show (true);
 

And here is what it looks like:

Getting Started Alert example can be found in our Native Xamarin.iOS examples.
 

2075
Telerik UI for Xamarin

Alert for Xamarn.iOS: Customizations

TKAlert allows customizing almost every aspect of its visual appearance. This article demonstrates
some of the customization techniques that can be used with it.

Alert Layout
TKAlert comes with two predefined actions layouts. You can choose between:

 TKAlertActionsLayoutHorizontal - actions horizontal alignment


 TKAlertActionsLayoutVertical - actions vertical alignment

You can switch between layouts by setting TKAlert's property ActionsLayout:

C#
alert.ActionsLayout = TKAlertActionsLayout.Vertical;
 

Alert Style
TKAlert has a property Style of type TKAlertStyle for styling it's appearance. The essential

2076
Telerik UI for Xamarin

properties of TKAlertStyle class are:

 ShowAnimation
 DismissAnimation
 BackgroundStyle

You can switch between two customizable background styles - Blur and Dim.

Background type Figures


Dim

Blur

2077
Telerik UI for Xamarin

None

Setting TKAlert's back behind could be done as follows:

C#
alert.Style.BackgroundStyle = TKAlertBackgroundStyle.None;
 

You can control background's opacity and color by setting TKAlert's style as follows:

C#
alert.Style.BackgroundDimAlpha = 0.5f;
alert.Style.BackgroundTintColor = UIColor.LightGray;
 

TKAlert's parallax effect could be turned on/off with single line of code:

C#
alert.AllowParallaxEffect = true;
 

Custom Content
In some scenarios you may need to use custom views for TKAlert header or content view. TKAlert
allows this by using its HeaderView and ContentView properties:

add a custom content view to te TKAlert ContentView

C#
TKAlert alert = new TKAlert ();
alert.Style.HeaderHeight = 0;
alert.TintColor = new UIColor (0.5f, 0.7f, 0.2f, 1f);

2078
Telerik UI for Xamarin

alert.CustomFrame = new CGRect ((this.View.Frame.Size.Width - 300) / 2, 100, 300,


250);
AlertCustomContentView view = new AlertCustomContentView (new CGRect(0, 0, 300, 210));
alert.ContentView.AddSubview (view);
 

Demos for Alert Customization can be found in our Native Xamarin.iOS examples.
 

2079
Telerik UI for Xamarin

Alert for Xamarin.iOS: Animations


TKAlert supports tree predefined show/dismiss animations:

Animation Type Figures


Fade

Scale

2080
Telerik UI for Xamarin

Slide

In order to get a real understanding of how the animations look and feel, check the Demo application
that ships with the UI for Xamarin suite.
 
These animations can be applied when TKAlert is being shown or dismissed.

Appear/hide animations
Those animations are applied when showing/dismissing the alert. You can add appear/hide
animation by setting the ShowAnimation and DismissAnimation property of TKAlertStyle:

C#
alert.Style.ShowAnimation = TKAlertAnimation.Scale;
alert.Style.DismissAnimation = TKAlertAnimation.Scale;
 

Gesture animations
TKAlert can recognize gestures. This allows end-users to dismiss the alert with a swipe or a tap
gesture.Enabling gesture recognition in TKAlert could be done as fallows:

C#
alert.DismissMode = TKAlertDismissMode.Tap;
 

Animations duration
Animations are controlled by setting properties of TKAlert class. The animation duration is
controlled by setting the AnimationDuration property:

C#
alert.AnimationDuration = 0.5f;
 

2081
Telerik UI for Xamarin

Demos for Alert Animaions can be found in our Native Xamarin.iOS examples.
 

2082
Telerik UI for Xamarin

AutoCompleteTextView for Xamarin.iOS:


Overview
TKAutoCompleteTextView can automatically complete user input string by comparing the text being
entered to all strings in the associated data source. The control provides means for easy
customization and data management. To make working with data easier for developers,
TKAutoCompleteTextView works seamlessly with the Telerik DataSource control which serves as
a mediator between the raw suggestions data and the UI component which serves as a suggestion
view.

Key Features

2083
Telerik UI for Xamarin

 Customizable Tokens
 Token Layout Modes
 Suggest Modes
 Suggestion Match Highlighting
 Completion Modes
 Display Modes

Demos for AutoCompleteTextView control can be found in our Native Xamarin.iOS examples.
 

2084
Telerik UI for Xamarin

AutoCompleteTextView for Xamarin.iOS:


Getting Started
This quick start tutorial demonstrates how to create a simple iOS application with
TKAutoCompleteTextView.

Setting up TKAutoCompleteTextView
Now that our project is created and the TelerikUI.framework is added, we can start referencing and
using the TelerikUI types:

Add the using statement to the view controller:

C#
using TelerikUI;
 

In the ViewDidLoad method of your view controller prepare a small array of sample data to be
presented as suggestions in TKAutoCompleteTextField.

C#
public partial class ViewController : UIViewController
{
public ViewController(IntPtr handle) : base (handle)
{
}

public override void ViewDidLoad()


{
base.ViewDidLoad();

NSString[] sampleArrayOfStrings = new NSString[] { new NSString("Kristina


Wolfe"),
new NSString("Freda Curtis"),
new NSString("Jeffery Francis"),
new NSString("Eva Lawson"),
new NSString("Emmett Santos"),
new NSString("Theresa Bryan"),
new NSString("Jenny Fuller"),
new NSString("Terrell Norris"),
new NSString("Eric Wheeler"),
new NSString("Julius Clayton"),
new NSString("Alfredo Thornton"),
new NSString("Roberto Romero"),
new NSString("Orlando Mathis"),
new NSString("Eduardo Thomas"),
new NSString("Harry Douglas")

2085
Telerik UI for Xamarin

};
}
}
 

Next, create an instance of TKDataSource. This component is used to feed


TKAutoCompleteTextView with our data. Now we need to go through the items of the source array
and create TKAutoCompleteToken objects with which the TKAutoCompleteTextView component
operates.

C#
this.dataSource = new TKDataSource(sampleArrayOfStrings);
this.dataSource.Settings.AutoComplete.CreateToken((index, item) => new
TKAutoCompleteToken((NSString) item));
 

Then create a new instace of TKAutoCompleteTextView and add it as a subview of the


ViewController's main view. The AutoresizingMask property is set in order to allow correct resizing
of the list view when the device is rotated in landscape mode.

C#
TKAutoCompleteTextView autocomplete = new TKAutoCompleteTextView(new
CoreGraphics.CGRect(10, 80, this.View.Bounds.Width - 20, 30));
autocomplete.WeakDataSource = this.dataSource;
autocomplete.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;

this.View.AddSubview(autocomplete);
 

Set up the MinimumCharactersToSearch property which defines after what number of entered
symbols the autocomplete should start suggesting. Set also the SuggestionViewHeight property
which sets the height of the suggestions presenting view.

C#
autocomplete.MinimumCharactersToSearch = 1;
autocomplete.SuggestionViewHeight = this.View.Bounds.Size.Height/2;
 

So far we have got the following view:

2086
Telerik UI for Xamarin

You can change the suggestion logic in order to control which suggestions to be shown. You can
show suggestions which contain the typed phrase or suggestions that start with that phrase. The
CompletionMode property is used to control the suggesting logic. The default behaviour is showing
suggestions which start with the typed in phrase.

C#
this.dataSource.Settings.AutoComplete.CompletionMode =
TKAutoCompleteCompletionMode.StartsWith;
 

This will result in:

For more information about the completion modes, please refer to the Completion Modes article

Finally, right now we get suggestions in a drop-down and we have to tap one of them to perform
selection. What will make the auto completion process even easier is if, in addition to the drop-down
with suggestions, we get a single suggestion that is shown in the text view part of
TKAutoCompleteTextView which we can easily select with a single keyboard stroke. This behavior
is defined by the so called SuggestMode, and in order to get the described functionality, let's set the
SuggestMode to SuggestAppend:

2087
Telerik UI for Xamarin

C#
autocomplete.SuggestMode = TKAutoCompleteSuggestMode.SuggestAppend;
 

The result will be:

Here is the completed example:

C#
using Foundation;
using System;
using UIKit;
using TelerikUI;

public partial class ViewController : UIViewController


{
private TKDataSource dataSource;

public ViewController(IntPtr handle) : base (handle)


{

2088
Telerik UI for Xamarin

public override void ViewDidLoad()


{
base.ViewDidLoad();
// Perform any additional setup after loading the view, typically from a nib.

NSString[] sampleArrayOfStrings = new NSString[] { new NSString("Kristina


Wolfe"),
new NSString("Freda Curtis"),
new NSString("Jeffery Francis"),
new NSString("Eva Lawson"),
new NSString("Emmett Santos"),
new NSString("Theresa Bryan"),
new NSString("Jenny Fuller"),
new NSString("Terrell Norris"),
new NSString("Eric Wheeler"),
new NSString("Julius Clayton"),
new NSString("Alfredo Thornton"),
new NSString("Roberto Romero"),
new NSString("Orlando Mathis"),
new NSString("Eduardo Thomas"),
new NSString("Harry Douglas")
};

this.dataSource = new TKDataSource(sampleArrayOfStrings);


this.dataSource.Settings.AutoComplete.CreateToken((index, item) => new
TKAutoCompleteToken((NSString) item));

this.AutomaticallyAdjustsScrollViewInsets = false;

TKAutoCompleteTextView autocomplete = new TKAutoCompleteTextView(new


CoreGraphics.CGRect(10, 80, this.View.Bounds.Width - 20, 30));
autocomplete.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
autocomplete.WeakDataSource = this.dataSource;

autocomplete.MinimumCharactersToSearch = 1;
autocomplete.SuggestionViewHeight = this.View.Bounds.Size.Height / 2;

this.View.AddSubview(autocomplete);
}
}
 

For more information about the suggest modes, please refer to the Suggest Modes article

AutoCompleteTextView Getting Started example can be found in our Native Xamarin.iOS examples.
 

2089
Telerik UI for Xamarin

AutoCompleteTextView for Xamarin.iOS:


Suggest Modes
There are three suggesting modes in which TKAutoCompleteTextView operates:

 TKAutoCompleteSuggestModeAppend - suggestions are shown in list view.

 TKAutoCompleteSuggestModeSuggest - only one suggestion is shown as an instant


completion to the typed text.

2090
Telerik UI for Xamarin

 TKAutoCompleteSuggestModeSuggestAppend - combines the first two modes.

2091
Telerik UI for Xamarin

The default suggesting mode is TKAutoCompleteSuggestMode.Suggest. It can be changed


through the SuggestMode property of the TKAutoCompleteTextView:

C#
this.Autocomplete.SuggestMode = TKAutoCompleteSuggestMode.Suggest;
 

2092
Telerik UI for Xamarin

AutoCompleteTextView for Xamarin.iOS:


Completion Modes
TKAutoCompleteTextView provides two completion modes:

 TKAutoCompleteCompletionModeStartsWith - returns suggestions that start with what


the end-user has typed.

 TKAutoCompleteCompletionModeContains - returns suggestions that contain what the


end-user has typed.

2093
Telerik UI for Xamarin

They are accessible through the TLKDataSource. The default completion mode is
TKAutoCompleteCompletionModeStartsWith.

C#
this.Autocomplete = new TKAutoCompleteTextView(new CGRect(10, this.View.Bounds.Y + 10,
this.View.Bounds.Size.Width - 20, 30));
this.AutomaticallyAdjustsScrollViewInsets = false;
this.Datasource = new TLKDataSource ();
this.Datasource.Settings.AutoComplete.CompletionMode =
TKAutoCompleteCompletionMode.Contains;
//this.dataSource.Settings.AutoComplete.CompletionMode =
TKAutoCompleteCompletionMode.StartsWith;
 

2094
Telerik UI for Xamarin

AutoCompleteTextView for Xamarin.iOS:


Tokens

In order to provide better user expirience and complete set of functionalities


TKAutoCompleteTextView supports text tokenizing which can be enabled through the
DisplayMode property of the TKAutoCompleteTextView.

C#
this.Autocomplete.DisplayMode = TKAutoCompleteDisplayMode.Tokens;
 

The layout flow of the tokens can be horizontal or vertically wrapped.This feature can be accessed

2095
Telerik UI for Xamarin

through the layoutMode property of the TKAutoCompleteTextView. By default vertical wrapping is


used.
C#
this.Autocomplete.LayoutMode = TKAutoCompleteLayoutMode.Wrap;
 

Tokens appereance can be customized by conforming to the TKAutoCompleteDelegate protocol


and implementing the ViewForToken method. You can change variaty of properties to get custom
look or you can provide a custom token object.
C#
class AutoCompleteTokensDelegate : TKAutoCompleteDelegate
{
public override TKAutoCompleteTokenView ViewForToken(TKAutoCompleteTextView
autocomplete, TKAutoCompleteToken token)
{
TKAutoCompleteTokenView tokenView = new TKAutoCompleteTokenView(token);
tokenView.BackgroundColor = UIColor.LightGray;
tokenView.Layer.CornerRadius = 10;
tokenView.ImageView.Layer.CornerRadius = 3;
return tokenView;
}
}
 

AutoCompleteTextView Token demo can be found in our Native Xamarin.iOS examples.


 

2096
Telerik UI for Xamarin

Calendar for Xamarin.iOS: Overview


TKCalendar is a highly customizable calendar component that offers different view modes,
animations, great performance and customization options. Its EventKit data source helper allows for
easy importing of events from the device.

TKCalendar main features include:

 Different view modes: week, month, year, month names, year numbers, flow and agenda
 Easy way to import device events by using the EventKit framework.
 Transition effects when switching between calendar pages.
 Different selection modes: single, multiple, and range selection.
 Overriding the default calendar appearance with themes and custom cells.
 Localization.

2097
Telerik UI for Xamarin

TKCalendar for Xamarin.iOS: Getting


Started
This quick start tutorial demonstrates how to create a simple iOS application with TKCalendar.

Setting up TKCalendar
Since iOS 10, Apple requires explicit description when NSCalendar is being used, more precisely
when one is trying to access the phone's calendar events. This description is prompted to the user,
only when there is an attempt for accessing events, and requires user's confirmation.

If you are using Telerik UI for Xamarin.iOS but never accessing device's calendar your users won't
get prompted with this message.

In order to submit your application to the AppStore make sure to include a


NSCalendarsUsageDescription variable to your info.plist and provide some description, for
example "This application need to acces your calendar events."

Now that our project is created and the TelerikUI.framework is added, we can start referencing and
using the TelerikUI types:

Open your UIViewController file and add a reference to Telerik UI header file:

C#
using TelerikUI;
 

2098
Telerik UI for Xamarin

Note that starting with Xcode 6 Apple doesn't generate the precompiled headers file automatically.
That is why you should add import the UIKit framework before importing TelerikUI:

C#
using UIKit;
 

Type the following code in ViewDidLoad method:

C#
TKCalendar calendarView = new TKCalendar (this.View.Bounds);
calendarView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth |
UIViewAutoresizing.FlexibleHeight;
this.View.AddSubview (calendarView);
 

This code creates a new instance of TKCalendar and adds it as a subview of the ViewController's
main view. The AutoresizingMask property is set in order to allow correct resizing of the calendar
when the device is rotated in landscape mode.

Events
The next step is to create some random data that will be consumed by the calendar. You can use
the following code:

C#
events = new List<TKCalendarEvent> ();
NSCalendar calendar = new NSCalendar (NSCalendarType.Gregorian);
NSDate date = NSDate.Now;

Random r = new Random ();


for (int i = 0; i < 3; i++) {
TKCalendarEvent ev = new TKCalendarEvent ();
ev.Title = "Sample event";
NSDateComponents components = calendar.Components (NSCalendarUnit.Day |
NSCalendarUnit.Month | NSCalendarUnit.Year, date);
components.Day = r.Next () % 20;
ev.StartDate = calendar.DateFromComponents (components);
ev.EndDate = calendar.DateFromComponents (components);
ev.EventColor = UIColor.Red;
events.Add (ev);
}
 

This code will add 10 events with random dates to an array named events. The arc4random
method is being used to create the random dates. The code also assigns a title and a color to the
events.

Now let's add this random data to the calendar and present it. In order to do this, we should first
adopt the TKCalendarDataSource protocol:

2099
Telerik UI for Xamarin

C#
class CalendarDataSource : TKCalendarDataSource
 

And we should implement its EventsForDate: method:

C#
public TKCalendarEventProtocol[] EventsForDate (TKCalendar calendar, NSDate date)
{
NSDateComponents components = calendar.Calendar.Components (NSCalendarUnit.Day |
NSCalendarUnit.Month | NSCalendarUnit.Year, date);
components.Hour = 23;
components.Minute = 59;
components.Second = 59;
NSDate endDate = calendar.Calendar.DateFromComponents (components);
List<TKCalendarEventProtocol> filteredEvents = new List<TKCalendarEventProtocol>
();
for (int i = 0; i < this.events.Count; i++) {
TKCalendarEventProtocol ev = this.events[i];
if (ev.StartDate.SecondsSinceReferenceDate <= endDate.SecondsSinceReferenceDate
&&
ev.EndDate.SecondsSinceReferenceDate >= date.SecondsSinceReferenceDate) {
filteredEvents.Add (ev);
}
}
return filteredEvents.ToArray ();
}
 

Here, the predicate is used to filter the events array by date. Do not forget to assign the DataSource
property of TKCalendar:

C#
calendarView.DataSource = new CalendarDataSource (this);
 

For information about populating TKCalendar with EventKit events, please refer to the following
article: Populating with data

Calendar MinDate and MaxDate


As a next step you may want to tune up the calendar more precisely by specifying minimum and
maximum allowed dates. This can be done by setting the MinDate and MaxDate properties:

C#
calendarView.MinDate = TKCalendar.DateWithYear (2010, 1, 1, calendar);
calendarView.MaxDate = TKCalendar.DateWithYear (2016, 12, 31, calendar);
 

2100
Telerik UI for Xamarin

NavigateToDate
By default, TKCalendar displays the current date, use the NavigateToDate method to display a
different date:

C#
NSDateComponents newComponents = new NSDateComponents();
newComponents.Year = 2015;
newComponents.Month = 5;
newComponents.Day = 1;
NSDate newDate = calendarView.Calendar.DateFromComponents (newComponents);
calendarView.NavigateToDate (newDate, true);
 

Notification when date is selected


TKCalendar sends different notifications. For example, in order to be notified when a date was
selected, override the DidSelectDate method of TKCalendarDelegate protocol:

C#
class CalendarDelegate : TKCalendarDelegate
{
public override void DidSelectDate (TKCalendar calendar, NSDate date)
{
Console.WriteLine ("{0}", date);
}
}
 

Selection Modes
Note that TKCalendar supports single, multiple and range date selection. Selection modes are
described in detail in the article about Selection.

Along with selection notifications TKCalendar supports navigation and customization notifications by
adopting the TKCalendarDelegate protocol. These notifications are described in the articles about:
Navigation and Customizations.

Here is the full code of this example:

C#
public class CalendarDocsWithSimpleEvent : XamarinExampleViewController
{
CalendarDelegate calendarDelegate;
List<TKCalendarEvent> events;

public TKCalendar CalendarView {


get;

2101
Telerik UI for Xamarin

set;
}

public TKCalendarEventProtocol[] EventsForDate {


get;
set;
}

public override void ViewDidLoad ()


{
base.ViewDidLoad ();
TKCalendar calendarView = new TKCalendar (this.View.Bounds);
calendarView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth |
UIViewAutoresizing.FlexibleHeight;
this.View.AddSubview (calendarView);

calendarDelegate = new CalendarDelegate ();

calendarView.DataSource = new CalendarDataSource (this);

events = new List<TKCalendarEvent> ();


NSCalendar calendar = new NSCalendar (NSCalendarType.Gregorian);
NSDate date = NSDate.Now;

Random r = new Random ();


for (int i = 0; i < 3; i++) {
TKCalendarEvent ev = new TKCalendarEvent ();
ev.Title = "Sample event";
NSDateComponents components = calendar.Components (NSCalendarUnit.Day |
NSCalendarUnit.Month | NSCalendarUnit.Year, date);
components.Day = r.Next () % 20;
ev.StartDate = calendar.DateFromComponents (components);
ev.EndDate = calendar.DateFromComponents (components);
ev.EventColor = UIColor.Red;
events.Add (ev);
}

calendarView.MinDate = TKCalendar.DateWithYear (2010, 1, 1, calendar);


calendarView.MaxDate = TKCalendar.DateWithYear (2016, 12, 31, calendar);

// calendarDelegate.events = this.events;
calendarView.Delegate = calendarDelegate;

NSDateComponents newComponents = new NSDateComponents();


newComponents.Year = 2015;
newComponents.Month = 5;
newComponents.Day = 1;
NSDate newDate = calendarView.Calendar.DateFromComponents (newComponents);
calendarView.NavigateToDate (newDate, true);

calendarView.ReloadData();
}

class CalendarDataSource : TKCalendarDataSource

2102
Telerik UI for Xamarin

{
CalendarDocsWithSimpleEvent main;
public List<TKCalendarEvent> events;
public CalendarDataSource(CalendarDocsWithSimpleEvent main)
{
this.main = main;
}

public TKCalendarEventProtocol[] EventsForDate (TKCalendar calendar, NSDate


date)
{
NSDateComponents components = calendar.Calendar.Components (NSCalendarUnit.Day
| NSCalendarUnit.Month | NSCalendarUnit.Year, date);
components.Hour = 23;
components.Minute = 59;
components.Second = 59;
NSDate endDate = calendar.Calendar.DateFromComponents (components);
List<TKCalendarEventProtocol> filteredEvents = new
List<TKCalendarEventProtocol> ();
for (int i = 0; i < this.events.Count; i++) {
TKCalendarEventProtocol ev = this.events[i];
if (ev.StartDate.SecondsSinceReferenceDate <= endDate.SecondsSinceReferenceDate
&&
ev.EndDate.SecondsSinceReferenceDate >= date.SecondsSinceReferenceDate) {
filteredEvents.Add (ev);
}
}
return filteredEvents.ToArray ();
}
}

class CalendarDelegate : TKCalendarDelegate


{
public override void DidSelectDate (TKCalendar calendar, NSDate date)
{
Console.WriteLine ("{0}", date);
}
}

}
 

Change Calendar View Mode


You can easily change the way data is presented in chart by changing the view mode property:

C#
this.CalendarView.ViewMode = TKCalendarViewMode.Year;
 

All view modes are described in the following article:View modes

2103
Telerik UI for Xamarin

Calendar for Xamarin.iOS: Populating with


Data
Following the Model-View-Controller design pattern, the data source mediates between the
application's data model (that is, its model objects) and the calendar view. The data source provides
the calendar view object with the information it needs to display events.

Following this approach, the TKCalendarDataSource protocol should be implemnted in order to


bind TKCalendar with data. This is easy because this protocol contains a single method
EventsForDate. The adopter should provide the events specific for the provided date. Here is a
sample implementation of this method:

C#
public override TKCalendarEventProtocol[] EventsForDate(TKCalendar calendar, NSDate
date)
{
NSDateComponents components = calendar.Calendar.Components(NSCalendarUnit.Year |
NSCalendarUnit.Month | NSCalendarUnit.Day, date);
components.Hour = 23;
components.Minute = 59;
components.Second = 59;
NSDate endDate = calendar.Calendar.DateFromComponents(components);
List<TKCalendarEventProtocol> filteredEvents = new
List<TKCalendarEventProtocol>();
for (int i = 0; i < this.main.Events.Length; i++)
{
TKCalendarEvent ev = (TKCalendarEvent)this.main.Events[i];
if (ev.StartDate.SecondsSinceReferenceDate <= endDate.SecondsSinceReferenceDate

2104
Telerik UI for Xamarin

&&
ev.EndDate.SecondsSinceReferenceDate >= date.SecondsSinceReferenceDate)
{
filteredEvents.Add(ev);
}
}

return filteredEvents.ToArray();
}
 

In most cases TKCalendar accesses events stored on the device where the application executes. In
this scenario the EventKit framework should be used. TKCalendar provides a helper data source
class which loads the events from device by using the EventKit API.

As a prerequisite, the EventKit and EventKitUI frameworks should be added to the application. Now,
you are ready to use the EventKit data source helper class for TKCalendar.

The simplest scenario is to create a new instance of TKCalendarEventKitDataSource class and


set it as a data source for TKCalendar:

C#
this.CalendarView = new TKCalendar (this.View.Bounds);
this.CalendarView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth |
UIViewAutoresizing.FlexibleHeight;
this.CalendarView.DataSource = this.DataSource;
this.View.AddSubview (this.CalendarView);
 

However, TKCalendarEventKitDataSource supports event filtering. Adopt its


TKCalendarEventKitDataSourceDelegate protocol to enable this feature.

In the cases when you want to filter only specific events, use the ShouldImportEvent method.

A sample Calendar with Events example can be found in our Native Telerik UI for Xamarin.iOS
Examples.
 

2105
Telerik UI for Xamarin

TKCalendar for Xamarin.iOS: Special Slots


With R3 2019 release of Telerik UI for Xamarin TKCalendar for Xamarin.iOS provides the option to
define a collection of special and restricted time slots in order to make them noticeable across the
timeline of the Day and MultiDay views.

Every SpecialSlot has the following properties:

 StartDate(NSDate)
 EndDate(NSDate)
 IsReadOnly(bool) When set to True the slot is disabled (restricted), meaning the end user
wouldn't be able to create or modify appointments at that slot;
 Style(TKCalendarSpecialSlotStyle): Defines the BackgroundColor of the Special Slot
 Location(NSString)

Example
TKCalendarDataSource protocol should be implemnted in order to bind TKCalendar with data. This
is easy because this protocol contains a single method EventsForDate. The adopter should provide
the events specific for the provided date.In addition to add a Special Slots you have to override the
SpecialSlotsForDate method

Below you can find a quick example how to create special slots.

C#
public override TKCalendarSpecialSlotProtocol[] SpecialSlotsForDate(TKCalendar
calendar, NSDate date)
{
var specialslot = new TKCalendarSpecialSlot()
{
StartDate= //add start date here,
EndDate= //add end date here,
IsReadOnly = true,
};
}
 

2106
Telerik UI for Xamarin

Calendar for Xamarin.iOS: View Modes


TKCalendar is able to present its contents in different ways. Those include:

 Month View
 Week View
 Year View
 Day View
 MultiDay View
 Agenda View
 List with years, containing months and month days
 List with year numbers
 List with month names
 Flow layout with months and month days

This article describes those view modes in detail.

The Presenter property of TKCalendar allows customizing settings specific for the current view
mode. Every view mode has its dedicated presenter class:

C#
TKCalendarYearPresenter presenter =
(TKCalendarYearPresenter)this.CalendarView.Presenter;
presenter.Columns = 3;
 

You can determine whether a view change occurred by implementing TKCalendarDelegate


protocol:

C#
public override void DidChangedViewModeFrom(TKCalendar calendar, TKCalendarViewMode
previousViewMode, TKCalendarViewMode viewMode)
{
if (viewMode == TKCalendarViewMode.Week || previousViewMode ==
TKCalendarViewMode.Week)
{
this.main.View.SetNeedsLayout();
}
}
 

Month View

2107
Telerik UI for Xamarin

Use the TKCalendarViewModeMonth to enable the single month view:

C#
this.CalendarView.ViewMode = TKCalendarViewMode.Month;
 

In this mode TKCalendar renders a single month and allows switching to a different month with a
swipe gesture. This transition can be customized with different transition effects. More about this is
available in this help article: Transition effects

In addition to selecting a different month with swipe, users can change the view mode to month
names when the AllowPinchZoom property is set to true:

C#
this.CalendarView.AllowPinchZoom = false;
 

Dates can be selected according to the SelectionMode property. Details about selection are
available in the dedicated help article about selection: Selection

2108
Telerik UI for Xamarin

Dates in this view mode are represented by the TKCalendarCell class which inherits from UIView.
The visual appearance can be customized by creating custom cells and handling the
calendar:viewForCellOfKind: method of TKCalendarDelegate protocol. This technique is
described in Calendar customizations article.

The presenter class responsible for month view is the TKCalendarMonthPresenter class. It
contains a style property where different UI settings can be tuned.

Week View

Set the ViewMode property to TKCalendarViewModeWeek to enable this view:

C#
this.CalendarView.ViewMode = TKCalendarViewMode.Week;
 

This view mode is similar to the previous one, but it displays only one week. The presenter class for
this view mode is TKCalendarWeekPresenter, it inherits from TKCalendarMonthPresenter and
allows the same customization and behavior features.

Year Mode

2109
Telerik UI for Xamarin

Set the viewMode property to TKCalendarViewModeYear to enable this view:

C#
this.CalendarView.ViewMode = TKCalendarViewMode.Year;
 

This view mode displays a list of years with their months and dates. The user can select months by
tapping on them.

The presenter class for this view mode is TKCalendarYearPresenter.

Day View

2110
Telerik UI for Xamarin

Set the viewMode property to TKCalendarViewMode.Day to enable this view:

C#
this.CalendarView.ViewMode = TKCalendarViewMode.Day;
 

MultiDay View

2111
Telerik UI for Xamarin

Set the viewMode property to TKCalendarViewMode.MultiDay to enable this view:

C#
this.CalendarView.ViewMode = TKCalendarViewMode.MultiDay;
 

Agenda View

2112
Telerik UI for Xamarin

Set the viewMode property to TKCalendarViewMode.Agenda to enable this view:

C#
this.CalendarView.ViewMode = TKCalendarViewMode.Agenda;
 

List with year numbers

2113
Telerik UI for Xamarin

Set the ViewMode property to TKCalendarViewMode.YearNumbers to enable this view.

C#
this.CalendarView.ViewMode = TKCalendarViewMode.YearNumbers;
 

The year numbers view is used together with the month view mode when the allowPinchZoom
option is turned on. It allows for selecting a different year faster.

The presenter class for this view mode is TKCalendarYearNumbersPresenter, it inherits from
TKCalendarMonthPresenter and allows the same customization and behavior features.

List with month names

2114
Telerik UI for Xamarin

Set the viewMode property to TKCalendarViewMode.MonthNames to enable this view.

C#
this.CalendarView.ViewMode = TKCalendarViewMode.MonthNames;
 

The month names view is used together with the month view mode when the allowPinchZoom
option is turned on. It allows for selecting a different month faster. Use pinch-in/out gesture to switch
between single month/year numbers view mode.

The presenter class for this view mode is TKCalendarMonthNamesPresenter, it inherits from
TKCalendarMonthPresenter and allows the same customization and behavior features.

Flow layout with months and month days

2115
Telerik UI for Xamarin

Set the viewMode property to TKCalendarViewMode.Flow to enable this view.

C#
this.CalendarView.ViewMode = TKCalendarViewMode.Flow;
 

The flow view displays months with single dates. Single cells are represented by the
TKCalendarCell class and allow customization by handling the calendar:viewForCellOfKind
method.

Only the single selection mode is available when selecting cells in flow view.

The presenter class for this view mode is TKCalendarFlowPresenter.

Examples
Sample View Modes example with different TKClanedar ViewModes can be found in our native
Xamarin.iOS Examples/Calendar folder.
 

2116
Telerik UI for Xamarin

See Also
 Customizations
 Transitions
 Selection

2117
Telerik UI for Xamarin

Calendar for Xamarin.iOS: View Transitions


View transitions allow for switching to the next/previous month with different animation effects. Those
effects are available in all view mode presenters that inherit from TKCalendarPresenterBase.
These include: month, month names, year numbers. Detailed information about view modes is
available in this help article: View modes

The available animations are: card, flip, float, fold, rotate, card and scroll. The default transition is
scroll. You should access the TransitionMode property of the presenter class in order to customize
the transition effect:

C#
TKCalendarMonthPresenter presenter =
(TKCalendarMonthPresenter)this.CalendarView.Presenter;
presenter.TransitionMode = TKCalendarTransitionMode.Flip;
 

The following options can be applied on transitions:

The TransitionIsVertical changes the horizontal/vertical orientation of the transition, this


changes also the activation gesture:

2118
Telerik UI for Xamarin

C#
presenter.TransitionIsVertical = true;
 

The TransitionIsReverse changes the forward/backward direction of the transition, thus


changing its effect.

Finally the transition duration can be customized by setting the TransitionDuration property:

C#
presenter.TransitionDuration = 2;
 

2119
Telerik UI for Xamarin

Calendar for Xamarin.iOS: Navigation


This document describes the options to navigate between dates in TKCalendar and the related
notifications.

There are two methods in TKCalendar used to navigate forward/backward in the calendar:
NavigateForward and NavigateBackward:. These methods are context sensitive and the
navigation period is specific to the current view mode (e.g. when using a week view the navigation
period will be set to one week):

C#
this.CalendarView.NavigateForward(true);
 

The calendar will not allow navigating to a date outside of the allowed period, specified by the
MinDate and MaxDate properties:

C#
this.CalendarView.MinDate = minDate;
this.CalendarView.MaxDate = maxDate;
 

The NavigateToDate method is used to navigate to specific date within the allowed period:

C#
NSDate date = NSDate.Now;
TkCalendar calendarView = new TKCalendar();
calendarView.NavigateToDate(newDate, true);
 

You can determine whether a navigation occurred by implementing TKCalendarDelegate protocol.

You should implement the WillNavigateToDate method if you want to be notified before this
action occurs and DidNavigateToDate method when action occured.

C#
public override void DidNavigateToDate(TKCalendar calendar, NSDate date)
{
base.DidNavigateToDate(calendar, date);
}
public override void WillNavigateToDate(TKCalendar calendar, NSDate date)
{
base.WillNavigateToDate(calendar, date);
}
 

2120
Telerik UI for Xamarin

Calendar for Xamarin.iOS: Selection


This article describes the different selection modes available in TKCalendar

The selection mode in TKCalendar can be altered by using the SelectionMode property. The
available options are:

 TKCalendarSelectionMode.Node - No selection is allowed.


 TKCalendarSelectionMode.Single - A single date can be selected.
 TKCalendarSelectionMode.Multiple - Different dates can be selected by tapping on
them. A second tap will deselect the date.
 TKCalendarSelectionMode.Range - A range between two dates on the same page can be
selected.

Here is an example how to set the SelectionMode:

C#
this.CalendarView.SelectionMode = TKCalendarSelectionMode.Range;
 

Use the SelectedDate property to get or set the currently selected date in TKCalendar when the

2121
Telerik UI for Xamarin

single selection mode is used.

Use the SelectedDates property to get or set the selected dates when multiple selection mode is
selected.

The SelectedDatesRange property is used to store the date range when this selection option is
used.

You can determine whether a selection is changed by adopting TKCalendarDelegate protocol:

C#
public override void DidSelectDate (TKCalendar calendar, NSDate date)
{
Console.WriteLine (String.Format ("{0}", date));
}
 

You can prevent TKCalendar from selecting specific date by handling the ShouldSelectDate
method:

C#
public override bool ShouldSelectDate (TKCalendar calendar, NSDate date)
{
Console.WriteLine (String.Format ("Trying to select the unselectable {0}", date));

return !TKCalendar.IsDate (main.UnselectableDate, date, NSCalendarUnit.Year |


NSCalendarUnit.Month | NSCalendarUnit.Day, main.CalendarView.Calendar);
}
 

Furthermore, the DidDeselectDate is called when using multiple selection to notify for unselected
dates:

C#
public override void DidDeselectedDate (TKCalendar calendar, NSDate date)
{
Console.WriteLine (String.Format ("{0}", date));
}
 

2122
Telerik UI for Xamarin

Calendar for Xamarin.iOS: Localization

By defualt, TKCalendar uses the current system locale and calendar settings. However, it allows for
specifying those settings explicitly, overriding the system settings. This article describes how to do
this.

The Calendar property of TKCalendar specifies the NSCalendar to be used. You can use this
property to change the first day in week to Monday for example:

C#
NSCalendar calendar = new NSCalendar (NSCalendarType.Gregorian);
calendar.FirstWeekDay = 2;
 

2123
Telerik UI for Xamarin

Or, you can change the calendar with one specific for your users:

C#
this.CalendarView.Calendar = new NSCalendar (NSCalendarType.Chinese);
 

Month names and week day names are provided by the Locale property. Use the following code to
customize the current locale:

C#
this.CalendarView.Locale = new NSLocale ("ru_RU");
 

After modifying the locale you should call the update: method for the presenter:

C#
((TKCalendarMonthPresenter)this.CalendarView.Presenter).Update(false);
 

2124
Telerik UI for Xamarin

2125
Telerik UI for Xamarin

Calendar for Xamarin.iOS: Customizations

Customize the visual appearance


TKCalendar allows customizing almost evety aspect of its visual appearance. This article
demonstrates some of the customization techniques that can be used with it.

TKCalendar comes with two predefined themes:

 TKCalendarDefaultTheme - a default theme


 TKCalendarIPadTheme - a theme designed for iPad

You can switch between themes by usig the Theme property:

C#
TKCalendar calendar = new TKCalendar (this.View.Bounds);
calendar.Theme = new TKCalendarIPadTheme ();
calendar.AutoresizingMask = UIViewAutoresizing.FlexibleWidth |
UIViewAutoresizing.FlexibleHeight;
this.View.AddSubview (calendar);
 

TKCalendar uses presenter classes to render different view modes. They all inherit from UIView
and contain subviews with settings that can be changed. Most useful settings are grouped in a style
property in the presenter class:

C#

2126
Telerik UI for Xamarin

TKCalendarMonthPresenter presenter = (TKCalendarMonthPresenter)calendar.Presenter;


presenter.Style.TitleCellHeight = 40;
presenter.Style.BackgroundColor = UIColor.Yellow;
presenter.HeaderIsSticky = true;
presenter.Style.MonthNameTextEffect = TKCalendarTextEffect.Lowercase;
presenter.Update (false);
 

There are cases when specific cells must have custom design based on the cell state (e.g. today,
weekend, selected). This can be dobe by adopging the TKCalendarDelegate protocol and
implementing its UpateVisualsForCell method:

C#
public override void UpdateVisualsForCell (TKCalendar calendar, TKCalendarCell cell)
{
if (cell is TKCalendarDayCell) {
TKCalendarDayCell dayCell = (TKCalendarDayCell)cell;
if ((dayCell.State & TKCalendarDayState.Today) != 0) {
cell.Style.TextColor = UIColor.Red;
}
else {
cell.Style.TextColor = UIColor.Purple;
}
}
}
 

The cell can be replaced with a custom one for more complex scenarios. This can be done by
implementing the ViewForCellOfKind method of TKCalendarDelegate protocol:

C#
public override TKCalendarCell ViewForCellOfKind (TKCalendar calendar,
TKCalendarCellType cellType)
{
if (cellType == TKCalendarCellType.Day) {
DocsCustomCell cell = new DocsCustomCell ();
return cell;
}
return null;
}
 

The following is the implementation of the CustomCell class:

C#
public class DocsCustomCell : TKCalendarDayCell
{
public DocsCustomCell ()
{
}

2127
Telerik UI for Xamarin

public override void UpdateVisuals ()


{
base.UpdateVisuals ();

if ((this.State & TKCalendarDayState.Today) != 0) {


this.Label.TextColor = UIColor.Green;
} else {
this.Label.TextColor = UIColor.Blue;
}
}
}
 

The result is presented below:

Examples
Sample Customization TKCalendar example can be found in our native Xamarin.iOS
Examples/Calendar folder.
 

2128
Telerik UI for Xamarin

Chart for Xamarin.iOS: Overview


RadChart for Xamarin.iOS is a versatile charting component that offers full customization, great
performance and intuitive object model. Its API allows creating complex charts with stunning
animations and appearance.

TKChart main features include:

 Various series types: bar, column, line, spline, area, pie, donut, scatter, bubble, financial
series and indicators.
 Stacking of bar, column, line and area series including stack 100 mode.
 Pan/Zoom and selection functionality.
 Animations that use the CoreAnimations and UIKit dynamics.
 Multiple axes.
 Annotations.
 Trackball.

2129
Telerik UI for Xamarin

Chart for Xamarin.iOS: Getting Started


This quick start tutorial demonstrates how to create a simple iOS application with TKChart.

Setting up TKChart
Now that our project is created and the Telerik.Xamarin.iOS assembly is added, we can start
referencing and using the TelerikUI types:

Open your UIViewController file and add a reference to the chart header file:

C#
using TelerikUI;
 

Type the following code in ViewDidLoad method:

C#
TKChart chart = new TKChart (this.View.Bounds);
chart.AutoresizingMask = UIViewAutoresizing.FlexibleWidth |
UIViewAutoresizing.FlexibleHeight;
this.View.AddSubview (chart);
 

This code creates a new instance of TKChart and adds it as a subview of the ViewController's main
view. The AutoresizingMask property is set in order to allow correct resizing of the chart when the
device is rotated in landscape mode.

2130
Telerik UI for Xamarin

The next step is to create some random data that will be consumed by the chart. You can use the
following code:

C#
Random r = new Random ();
List<TKChartDataPoint> list = new List<TKChartDataPoint> ();
for (int i = 0; i < 12; i++) {
list.Add (new TKChartDataPoint (new NSNumber (i), new NSNumber (r.Next () %
2000)));
}
 

In this case we use the i variable as an x value, and we generate a random number in the range
between 0 and 100 as an y value.

Now let's add this random data to the chart and present it. This is done by the following code:

C#
TKChartLineSeries series = new TKChartLineSeries (list.ToArray());

series.Selection = TKChartSeriesSelection.Series;
chart.AddSeries (series);
 

For more information about populating TKChart with data, please refer to the Populating with Data
article.

The TKChartLineSeries tells the chart to present its data as a line chart and initializes it with the
already created points.

Let's add a title and a legend to our chart. We can do so by setting the corresponding Hidden
properties to false. We can easily employ the built-in animations support to create some fancy
animations. To do so, we should set the AllowAnimations property to true:

C#
chart.Title.Hidden = false;
chart.Title.Text = "This is a chart demo";
chart.Legend.Hidden = false;
chart.AllowAnimations = true;
 

For more information about customizing animations, please refer to the following articles:

 Custom Animations
 Custom UIKit Dynamics Animations

For more information about series types, please refer to the following articles: Chart Structure.

2131
Telerik UI for Xamarin

Chart for Xamarin.iOS: Structure


TKChart consists of the following elements:

 Plot Area - this is the area where chart data is drawn.


 Series - chart data is represented by series objects. Each series object defines the chart
type and contains a set of points to be drawn. The chart can display different series object
simultaneously.
 Axes - there are four axes areas that surround the plot area. The axes define the dimensions
in which data is drawn inside the plot area. Each axis can be attached to a single or many
series.
 Title - this is the chart title. Its style and position can be customized. The chart title is
hidden by default.
 Legend - the chart legend displays additional information about series objects. Its style and
position can be customized. The chart legend is hidden by default.

In addition to these visual objects, TKChart uses the following protocols:

 DataSource - chart data source is used to supply the chart with data. Setting this property is
optional, as you can assign data directly to the series object. In case you decide to use this
property, you have to implement the TKChartDataSource protocol.
 Delegate - The chart delegate is an optional protocol that allows chart consumers to receive
notifications from TKChart. It allows also customizing chart appearance and animations.

Axes
TKChart renders its points in a coordinate system defined by its axes. To do this, axes specify the
minimum and maximum values that can be presented on the plot area. There are a few different
types of axes that can be used with TKChart. They include: numeric, date/time and categoric. You
can assign each axis to different series and you can show multiple axes in a chart. Axes contain
various properties to control their position, style and behavior. All chart axes subclass from

2132
Telerik UI for Xamarin

TKChartAxis.

 Use TKChartNumericAxis to present numeric values.


 Use TKChartDateTimeAxis to present date/time values.
 Use TKChartCategoryAxis to present categoric values.

In order to show multiple axes in TKChart, create several axes and customize their position. Then
use the XAxis and YAxis properties of the series to assign them:

C#
var xAxis = new TKChartNumericAxis ();
xAxis.Position = TKChartAxisPosition.Bottom;
chart.AddAxis (xAxis);

var yAxis1 = new TKChartNumericAxis (new NSNumber (0), new NSNumber (100));
yAxis1.MajorTickInterval = 50;
yAxis1.Position = TKChartAxisPosition.Left;
yAxis1.Style.LineHidden = false;
chart.AddAxis (yAxis1);

var yAxis2 = new TKChartNumericAxis (new NSNumber (0), new NSNumber (200));
yAxis2.MajorTickInterval = 50;
yAxis2.Position = TKChartAxisPosition.Right;
yAxis2.Style.LineHidden = false;
chart.AddAxis (yAxis2);

var incomesData = new List<TKChartDataPoint> ();


var values1 = new [] { 12, 10, 98, 64, 11, 27, 85, 72, 43, 39 };
for (int i=0; i<10; i++) {
incomesData.Add (new TKChartDataPoint (new NSNumber(i), new NSNumber(values1
[i])));
}

var series = new TKChartLineSeries (incomesData.ToArray());


series.XAxis = xAxis;
series.YAxis = yAxis1;
chart.AddSeries (series);
 

The result from this setup is:

2133
Telerik UI for Xamarin

Find further details on this in Chart Axes article.

Series
Series define how data should be visually presented on the plot area. Each series has a collection of
data points, which it displays according to the series type. TKChart supports several series out of
the box. These include: bar, column, line, area, scatter and pie. The base class for all series in
TKChart is TKChartSeries.

 TKChartAreaSeries is used to present points in filled areas.


 TKChartBubbleSeries is used to present points of various size.
 TKChartCandlestickSeries and TKChartOhlcSeries are used to present stock market data.
 Financial indicators are used to present calculated summary of stock market data.
 TKChartBarSeries is used to present points as bars (horizontal rectangles).
 TKChartColumnSeries is used to present points as columns (vertical rectangles).
 TKChartDonutSeries is used to present data as a pie.
 TKChartSplineSeries is used to present points as a spline.
 TKChartSplineAreaSeries is used to present points in filled areas having a spline line at the
top.
 TKChartLineSeries is used to present points as line/spline.
 TKChartPieSeries is used to present data as pie.
 TKChartScatterSeries is used to present data as separate points.

When TKChart contains more than one series of type bar or column, it clusters the series in groups.
You can choose also to show the same information as stacked bars/columns. This is done by setting
the StackInfo property of the series:

C#
var values1 = new [] { 12, 10, 98, 64, 11, 27, 85, 72, 43, 39 };

2134
Telerik UI for Xamarin

var values2 = new [] { 87, 22, 29, 87, 65, 99, 63, 12, 82, 87 };
var expensesData = new List<TKChartDataPoint>();
var incomesData = new List<TKChartDataPoint>();
for (int i=0; i<10; i++) {
expensesData.Add(new TKChartDataPoint(new NSNumber(i), new NSNumber(values2[i])));
incomesData.Add(new TKChartDataPoint(new NSNumber(i), new NSNumber(values1[i])));
}

var stackInfo = new TKChartStackInfo(new NSNumber(1), TKChartStackMode.Stack);

var series1 = new TKChartColumnSeries(expensesData.ToArray());


series1.Title = "Expenses";
series1.StackInfo = stackInfo;
chart.AddSeries(series1);

var series2 = new TKChartColumnSeries(incomesData.ToArray());


series2.Title = "Incomes";
series2.StackInfo = stackInfo;
chart.AddSeries(series2);
 

The result from this setup is:

Line and area series also allow stacking by using the StackInfo property.

Series appearance can be changed by using the Style property.

Interaction
TKChart is an interactive component that supports gestures like touch, pan and rotate. The main
actions that are supported are selection and pan/zoom interaction.

2135
Telerik UI for Xamarin

The AllowPan and AllowZoom properties of TKChartAxis should be set to true in order to allow
pan/zoom functionality.

The SelectionMode property of TKChartSeries should be set to TKChartSelectionModeSeries


or TKChartSelectionModeDataPoint in order to allow selection for the specified series.

Find further details about selection and pan/zoom functionality in the corresponding articles.

Animations
TKChart allows animating chart points by using the CoreAnimation framework. There are built-in
animations specific for every series type and you can define your own animations by implementing
methods in the chart delegate.

You can customize the default animation by implementing the TKChartDelegate interface and
overriding its AnimationForSeries method:

The АllowAnimations property of TKChart should be set to true in order to work with animations.

C#
public override CAAnimation AnimationForSeries (TKChart chart, TKChartSeries series,
TKChartSeriesRenderState state, CGRect rect)
{
var duration = 0.0;
var animations = new List<CAAnimation> ();
for (int i=0; i<(int)state.Points.Count; i++) {
var pointKeyPath = state.AnimationKeyPathForPointAtIndex ((uint)i);
var keyPath = pointKeyPath + ".x";
var point = state.Points.ObjectAtIndex((uint)i) as TKChartVisualPoint;
var animation = new CABasicAnimation ();
animation.KeyPath = keyPath;
animation.Duration = (double) (r.Next (100)) / 100.0;
animation.From = new NSNumber(0);
animation.To = new NSNumber(point.X);
animations.Add (animation);
duration = Math.Max(animation.Duration, duration);
}

var group = new CAAnimationGroup ();


group.Duration = duration;
group.Animations = animations.ToArray();
return group;
}
 

This method returns a single animation, therefore if you create multiple animations, you should group
them inside CAAnimationGroup.

Besides the CoreAnimation framework, TKChart allows animating its points by adding real world
physics by using the new UIKitDynamics framework introduced in iOS 7. With this framework you
can add different behaviors like gravity, elasticity and forces. Read further details about this

2136
Telerik UI for Xamarin

advanced topic in UIKit Dynamics Animations article.

2137
Telerik UI for Xamarin

Chart for Xamarin.iOS: Populating with Data


In order for TKChart to represents data, we should supply this data to it. Following the
Model-View-Controller design pattern, the data source mediates between the application's data
model (that is, its model objects) and the chart view. The data source provides the chart-view object
with the information it needs to construct visualization using different chart types.

TKChart can be bound to a wide variety of data sources. The common way to work with chart-view'
data source is to subclass the UIViewController and adopt the TKChartDataSource protocol or
subclass the built-in TKChartViewController to manage the data source. Another way is to
automate this task using the binding mechanism of TKChart to setup the data source.

Configure data source using the TKChartDataSource


protocol
Following this approach, we supply TKChart with data using a delegate. This works the same way
as with UITableView. You should implement the TKChartDataSource protocol and specify the
number of series, the number of points in each series, the series objects and the point objects. The
TKChartDataSource has two required methods, namely NumberOfSeries and GetSeries.The
NumberOfSeries method tells the chart view how many series to display in the plot area, and the
GetSeries method provides the series to display. Optional methods allow the data source to
configure data points for each series.

Here is a sample subclass of TKChartViewController which will provide TKChart with data points
for one TKChartLineSeries:

C#
public class ChartDocsPopulatingWithData : UIViewController
{
public ChartDocsPopulatingWithData ()
{
}

public override void ViewDidLoad ()


{
base.ViewDidLoad ();

var chart = new TKChart (CGRect.Inflate (this.View.Bounds, -10, -10));


this.View.AddSubview (chart);
chart.DataSource = new ChartDataSource ();
chart.AutoresizingMask = UIViewAutoresizing.FlexibleWidth |
UIViewAutoresizing.FlexibleHeight;
}

class ChartDataSource: TKChartDataSource


{
Random r = new Random();

2138
Telerik UI for Xamarin

public override nuint NumberOfSeries (TKChart chart)


{
return 1;
}

public override nuint PointsInSeries (TKChart chart, nuint seriesIndex)


{
return 10;
}

public override TKChartSeries GetSeries (TKChart chart, nuint index)


{
var series = chart.DequeueReusableSeriesWithIdentifier ("series1") as
TKChartSeries;
if (series == null) {
series = new TKChartLineSeries (null, "series1");
series.Title = "Series title";
}
return series;
}

public override ITKChartData GetPoint (TKChart chart, nuint dataIndex, nuint


seriesIndex)
{
var point = new TKChartDataPoint (new NSNumber (dataIndex), new NSNumber(r.Next
(100)));
return point;
}
}
 

Configure data source using binding to DataPoints


collection

2139
Telerik UI for Xamarin

Another way to configure TKChart data source is to set up data points for the TKChartSeries
object, and using the binding mechanism, the TKChart control will automatically create and set up
the built-in TKChartBindDingataSource for you.

Here is a TKChartColumnSeries with an attached collection of data points:

C#
var chart = new TKChart (CGRect.Inflate (this.View.Bounds, -10, -10));
this.View.AddSubview (chart);
chart.AutoresizingMask = UIViewAutoresizing.FlexibleWidth |
UIViewAutoresizing.FlexibleHeight;

var categories = new [] { "Greetings", "Perfecto", "NearBy", "Family Store", "Fresh &
Green" };
var values = new [] { 70, 75, 58, 59, 88 };
var dataPoints = new List<TKChartDataPoint> ();
for (int i = 0; i < categories.Length; ++i) {
dataPoints.Add (new TKChartDataPoint (new NSString (categories [i]), new NSNumber
(values [i])));
}

chart.AddSeries (new TKChartColumnSeries (dataPoints.ToArray ()));


 

Configure data source using binding to properties of model


object
In order to support full binding mechanism and minimize the amount of code used to initialize data
source with model object of your application, TKChart supports binding to properties of the model
object. To use this powerful mechanism, you should describe in pairs the names of TKChartData
properties related to the property names of your custom object.

Binding to an array of custom object is quite easy with TKChart. Once your array is created, you just

2140
Telerik UI for Xamarin

need to set the necessary members to the desired field. In the code snippet below we create one
application specific custom object and bind its data to three line series:

C#
var chart = new TKChart (CGRect.Inflate (this.View.Bounds, -10, -10));
this.View.AddSubview (chart);
chart.AutoresizingMask = UIViewAutoresizing.FlexibleWidth |
UIViewAutoresizing.FlexibleHeight;

Random r = new Random ();


var dataPoints = new List<CustomObject> ();
for (int i=0; i<5; i++) {
CustomObject obj = new CustomObject () {
ObjectID = i,
Value1 = r.Next (100),
Value2 = r.Next (100),
Value3 = r.Next (100)
};
dataPoints.Add (obj);
}

chart.BeginUpdates ();
chart.AddSeries(new TKChartLineSeries(dataPoints.ToArray(), "ObjectID", "Value1"));
chart.AddSeries(new TKChartAreaSeries(dataPoints.ToArray(), "ObjectID", "Value2"));
chart.AddSeries(new TKChartScatterSeries(dataPoints.ToArray(), "ObjectID", "Value3"));
chart.EndUpdates();
 

TKChart by default creates and sets up axes automatically to support this flexible and codeless
binding behavior using the data types in the provided data source. You can always change or
replace the axis type for TKChartSeries or change it auto-calculated default range.
 

2141
Telerik UI for Xamarin

Chart for Xamarin.iOS: Legend


TKChart has built-in support for legends – descriptions about the charts on the plot. The items
displayed in the legend are series specific i.e. for the pie chart the data points are shown in the
legend, whereas for line series only one item is shown for each series.

Configure legend
If you would like to show the legend in TKChart, you should set its Hidden property to false. The
default value is true. The legend supports showing a series title.

C#
chart.Legend.Hidden = false;
 

You can alter the position and offset origin of legend by setting its Position property:

C#
chart.Legend.Style.Position = TKChartLegendPosition.Right;
 

The legend can be anchored to concrete side by using the following values
TKChartLegendPosition.Left, TKChartLegendPosition.Right,
TKChartLegendPosition.Top and TKChartLegendPosition.SBottom.

2142
Telerik UI for Xamarin

It can float by using TKChartLegendPosition.Floating value. In this case, you can offset its
origin manually by setting its Offset and OffsetOrigin properties:

C#
chart.Legend.Style.Position = TKChartLegendPosition.Floating;
chart.Legend.Style.OffsetOrigin = TKChartLegendOffsetOrigin.TopLeft;
chart.Legend.Style.Offset = new UIOffset(10, 10);
 

Customize legend
You can alter visibility of the legend's title by changing ShowTitle property.

C#
chart.Legend.TitleLabel.Text = "Companies";
chart.Legend.ShowTitle = true;
 

2143
Telerik UI for Xamarin

In addition, you can disable the series selection via legend by setting AllowSelection property to
false.

The legend can be customized by using its Style object. It contains the following properties:

 Position - Determines where the legend should be placed.


 Offset - Determines the offset at which to place the legend, according to the specified
offsetOrigin.
 OffsetOrigin - Determines the starting point for the offset property.
 Fill - Gets or sets the fill color to be used as a background.
 Stroke - Gets or sets stroke color to be used for the legend frame.

C#
chart.Legend.Style.Fill = new TKSolidFill(UIColor.LightGray);
chart.Legend.Style.Stroke = new TKStroke(UIColor.DarkGray);
 

Embedding legend outside TKChart


You can use the legend outside the chart view. You should create an instance of
TKChartLegendView and add it as subview to desired view.

C#
var legendView = new TKChartLegendView (chart);
legendView.Frame = new CGRect (20, 20, 320, 100);
this.View.AddSubview(legendView);
legendView.ReloadItems ();
 

2144
Telerik UI for Xamarin

2145
Telerik UI for Xamarin

Chart for Xamarin.iOS: Selection


This help topic demonstrates how you can make your charts more interactive by enabling a selection
behavior.

Configure
You can alter the selection mode by altering the chart SeriesSelectionMode and
DataPointSelectionMode properties with the following value:

 TKChartSelectionModeNone - No selection.
 TKChartSelectionModeSingle - A single point/series can be selected.
 TKChartSelectionModeMultiple - Multiple points/series can be selected.

In addition you can finely tune the selection by setting the selection property of each series:

 TKChartSeriesSelectionNotSet - Selection not set for this series, fall back to the chart
selection settings.
 TKChartSeriesSelectionNone - Selection disabled.
 TKChartSeriesSelectionSeries - Whole series selection.
 TKChartSeriesSelectionDataPoint - Single data point selection.
 TKChartSeriesSelectionDataPointMultiple - Select multiple data points.

This way each series can have a separate selection mode. One series can select a single point,
another series can select multiple points and a third series canbe selected as a whole series if
necessary. Please note that the series selection has higher priority than the chart selection.

Use the SelectedSeries and SelectedPoints properties to get currently selected series or
points respectively.

C#
foreach (TKChartSeries series in chart.SelectedSeries) {
Console.WriteLine ("selected series at index {0}", series.Index);
}

foreach (TKChartSelectionInfo info in chart.SelectedPoints) {


Console.WriteLine ("selected point at index {0} from series {1}",
info.DataPointIndex, info.Series.Index);
}
 

The IsSelected property of TKChartSeries indicates whether the series is selected.

You can determine whether a selection is changed by adopting TKChartDelegate protocol and
implementing one the following methods:

C#
class ChartDelegate: TKChartDelegate

2146
Telerik UI for Xamarin

{
public override void SeriesSelected (TKChart chart, TKChartSeries series)
{
// Here you can perform the desired action when the selection is changed.
}

public override void PointSelected (TKChart chart, TKChartData point,


TKChartSeries series, nint index)
{
// Here you can perform the desired action when the selection is changed.
}

public override void SeriesDeselected (TKChart chart, TKChartSeries series)


{
// Here you can perform the desired action when the selection is changed.
}

public override void PointDeselected (TKChart chart, TKChartData point,


TKChartSeries series, nint index)
{
// Here you can perform the desired action when the selection is changed.
}
}
 

In addition, you can change the selection programmatically by calling the Select method in the
following manner:

C#
public override void ViewDidAppear (bool animated)
{
base.ViewDidAppear (animated);
chart.Select (new TKChartSelectionInfo (chart.Series [0], 0));
}
 

2147
Telerik UI for Xamarin

Note that you can clear the selection by passing nil value to the Series argument.

2148
Telerik UI for Xamarin

Chart for Xamarin.iOS: Grid Customization


TKChart series, which support axes, can render a grid that facilitates the process of determining the
values of points afar from the axes. Since Pie area does not use axes, the grid is valid only in the
context of Cartesian series. Grid consists of horizontal and vertical lines matching axes major ticks
and fills between them. You can alternate fills to create zebra like effect both horizontally and
vertically.

The essential properties of TKChartGridStyle are the following:

 VerticalLineStroke - defines the vertical line stroke.


 VerticalLineAlternateStroke - defines the vertical alternate line stroke.
 VerticalLinesHidden - determines whether the vertical line is hidden.
 VerticalFill - defines the background pattern of fill among vertical lines.
 VerticalAlternateFill - defines the background pattern of alternate fill among vertical
lines.
 HorizontalLineStroke - defines the horizontal line stroke.
 HorizontalLineAlternateStroke - defines the horizontal alternate line stroke
 HorizontalLinesHidden - determines whether the hidden line is hidden.
 HorizontalFill - defines the background pattern of fill among horizontal lines
 HorizontalAlternateFill - defines the background pattern of alternate fill among
horizontal lines
 BackgroundFill - sets the background fill color. By default, it is nil (no background color is
drawn).
 DrawOrder - sets the draw order. By default, it is TKGridDrawModeHorizontalFirst.
 ZPosition - defines the grid position according to the series.

Customizing grid appearance


Working with grid style properties is easy. Here is a way to make colorful grid lines:

C#
var gridStyle = chart.GridStyle;
gridStyle.VerticalLineStroke = new TKStroke (UIColor.Black);
gridStyle.VerticalLineAlternateStroke = new TKStroke (UIColor.Black);
gridStyle.VerticalLinesHidden = false;
gridStyle.VerticalFill = null;
gridStyle.VerticalAlternateFill = null;

gridStyle.HorizontalLineStroke = new TKStroke (UIColor.Red);


gridStyle.HorizontalLineAlternateStroke =new TKStroke (UIColor.Blue);
gridStyle.HorizontalFill = null;
gridStyle.HorizontalAlternateFill = null;
gridStyle.HorizontalLinesHidden = false;
 

2149
Telerik UI for Xamarin

You can remove vertical lines altogether:

C#
var gridStyle = chart.GridStyle;

gridStyle.VerticalLinesHidden = true;
gridStyle.VerticalFill = null;
gridStyle.VerticalAlternateFill = null;

gridStyle.HorizontalLineStroke = new TKStroke (UIColor.Red);


gridStyle.HorizontalLineAlternateStroke = new TKStroke (UIColor.Blue);
gridStyle.HorizontalFill = null;
gridStyle.HorizontalAlternateFill = null;
gridStyle.HorizontalLinesHidden = false;
 

2150
Telerik UI for Xamarin

Now add some style using alternative fills:

C#
var gridStyle = chart.GridStyle;

gridStyle.HorizontalLineStroke = new TKStroke (UIColor.FromWhiteAlpha(215.0f / 255.0f,


1.0f));
gridStyle.HorizontalLineAlternateStroke = new TKStroke (UIColor.FromWhiteAlpha (215.0f
/ 255.0f, 1.0f));
gridStyle.HorizontalLinesHidden = false;
gridStyle.HorizontalFill = new TKSolidFill (UIColor.FromWhiteAlpha (228.0f / 255.0f,
1.0f));
gridStyle.HorizontalAlternateFill = new TKSolidFill (UIColor.White);

gridStyle.VerticalFill = null;
gridStyle.VerticalAlternateFill = null;
gridStyle.VerticalLinesHidden = true;
 

2151
Telerik UI for Xamarin

Here is how to switching to alternative vertical fills:

C#
var gridStyle = chart.GridStyle;

gridStyle.VerticalLineStroke = new TKStroke (UIColor.FromWhiteAlpha (215.0f / 255.0f,


1.0f));
gridStyle.VerticalLineAlternateStroke = new TKStroke (UIColor.FromWhiteAlpha (215.0f /
255.0f, 1.0f));
gridStyle.VerticalLinesHidden = false;
gridStyle.VerticalFill = new TKSolidFill (UIColor.FromWhiteAlpha (228.0f / 255.0f,
1.0f));
gridStyle.VerticalAlternateFill = new TKSolidFill (UIColor.White);

gridStyle.HorizontalFill = null;
gridStyle.HorizontalAlternateFill = null;
gridStyle.HorizontalLinesHidden = true;
 

2152
Telerik UI for Xamarin

Combining it together
C#
var gridStyle = chart.GridStyle;

gridStyle.HorizontalLineStroke = new TKStroke (UIColor.FromWhiteAlpha (215.0f /


255.0f, 1.0f));
gridStyle.HorizontalLineAlternateStroke = new TKStroke (UIColor.FromWhiteAlpha (215.0f
/ 255.0f, 1.0f));
gridStyle.HorizontalFill = new TKSolidFill(UIColor.FromWhiteAlpha (228.0f / 255.0f,
1.0f));
gridStyle.HorizontalAlternateFill = new TKSolidFill (UIColor.White);
gridStyle.HorizontalLinesHidden = false;

gridStyle.VerticalLineStroke = new TKStroke (UIColor.FromWhiteAlpha (215.0f / 255.0f,


1.0f));
gridStyle.VerticalLineAlternateStroke = new TKStroke (UIColor.FromWhiteAlpha (215.0f /
255.0f, 1.0f));
gridStyle.VerticalLinesHidden = false;
gridStyle.VerticalFill = new TKSolidFill (new UIColor (1.0f, 1.0f, 0.0f, 0.1f));
gridStyle.VerticalAlternateFill = new TKSolidFill (new UIColor (0.0f, 1.0f, 0.0f,
0.1f));
 

2153
Telerik UI for Xamarin

Note how vertical fills are transparent. This is because in default mode horizontal fills are drawn first.
However you can change the drawing order. Adding a single line of code to the snippet above will
produce the effect below:

C#
gridStyle.DrawOrder = TKChartGridDrawMode.VerticalFirst;
 

2154
Telerik UI for Xamarin

As you can see vertical fills are missing. The reason is that in TKGridDrawModeVerticalFirst mode
they are drawn first and then the non-transparent horizontal fills got drawn above. On order to
address this, the fills which are drawn last always need to have some transparency. You can also
draw all the fills with transparency, but in this case you might need to set:

C#
gridStyle.BackgroundFill = new TKSolidFill(UIColor.White);
 

This will create a predictable background for the grid and plot area.

You can also use grid's background to set an image:

C#
gridStyle.BackgroundFill = new TKSolidFill(UIColor.FromPatternImage(new
UIImage("telerk_logo.png")));
 

2155
Telerik UI for Xamarin

Using ZPosition
ZPosition property specifies the Z order of the grid. Grid is drawn below series by default. However
you can change it so grid is above series:

C#
var gridStyle = chart.GridStyle;

gridStyle.HorizontalLineStroke = new TKStroke (UIColor.FromWhiteAlpha (215.0f /


255.0f, 1.0f));
gridStyle.HorizontalLineAlternateStroke = new TKStroke (UIColor.FromWhiteAlpha (215.0f
/ 255.0f, 1.0f));
gridStyle.HorizontalLinesHidden = false;
gridStyle.HorizontalFill = new TKSolidFill (UIColor.FromWhiteAlpha (228.0f / 255.0f,
1.0f));
gridStyle.HorizontalAlternateFill = new TKSolidFill (UIColor.Clear);

gridStyle.VerticalFill = null;
gridStyle.VerticalAlternateFill = null;
gridStyle.VerticalLinesHidden = true;

gridStyle.ZPosition = TKChartGridZPosition.AboveSeries;
 

2156
Telerik UI for Xamarin

2157
Telerik UI for Xamarin

Chart for Xamarin.iOS: Annotations


Annotations are visual elements that can be used to highlight certain areas on the plot area and
denote statistical significance.

TKChart provides the following types of annotations:

 TKChartGridLineAnnotation
 TKChartBandAnnotation
 TKChartCrossLineAnnotation
 TKChartBalloonAnnotation
 TKChartLayerAnnotation
 TKChartViewAnnotation

Adding annotations to the chart


TKChart contains an annotations collection and annotations can be added to the chart by calling
the AddAnnotation method. The following code adds a horizontal grid line annotation in TKChart.
The annotation requires an axis and a value in order to be initialized correctly.

C#
chart.AddAnnotation (new TKChartGridLineAnnotation(new NSNumber(600), chart.XAxis));
 

The annotation visibility can be controlled by setting its Hidden property.The annotation visual
appearance can be changed by using its Style property.

Annotation types
Conceptually, there are three types of annotations - grid line, band and point annotations. Below is a
comparison for each one depending on the scenario.

Grid line
The grid line annotation represents a vertical or horizontal line which crosses the entire plot area. It
is specified by using the TKChartGridLineAnnotation.

The line color can be customized by using the annotation initializer:

C#
chart.AddAnnotation (new TKChartGridLineAnnotation(new NSNumber(80), chart.YAxis, new
TKStroke(UIColor.Red)));
 

2158
Telerik UI for Xamarin

Plot band
The TKChartBandAnnotation is either horizontal or vertical strip, crossing its corresponding axis,
specified by its Range property.

C#
chart.AddAnnotation (new TKChartBandAnnotation(new TKRange(new NSNumber(10), new
NSNumber(40)), chart.YAxis, new TKSolidFill(new UIColor (1, 0, 0, 0.4f)), null));
 

2159
Telerik UI for Xamarin

Point annotations
Point annotations render their content starting at specific position. Besides the position, a pixel
based offset could be added to the point annotation by specifying the Offset property.

Cross line annotation


The TKChartCrossLineAnnotation is a point annotation which represents two crossing lines with a
point at the crossing position.

C#
chart.AddAnnotation (new TKChartCrossLineAnnotation(new NSNumber(900), new
NSNumber(60), chart.Series[0]));
 

2160
Telerik UI for Xamarin

Balloon annotation
The TKChartBalloonAnnotation displays a balloon-like shape next to the position specified by its
arguments. The VerticalAlign and HorizontalAlign properties allow to position the annotation
precisely. The balloon will correct its position automatically if there is not enough space at the
specified coordinates.

C#
NSMutableParagraphStyle paragraphStyle = (NSMutableParagraphStyle)new NSParagraphStyle
().MutableCopy();
paragraphStyle.Alignment = UITextAlignment.Center;
NSMutableDictionary attributes = new NSMutableDictionary ();
attributes.Add (UIStringAttributeKey.ForegroundColor, UIColor.White);
attributes.Add (UIStringAttributeKey.ParagraphStyle, paragraphStyle);
NSMutableAttributedString attributedText = new NSMutableAttributedString ("Important
milestone:\n $55000", attributes);

attributedText.AddAttribute (UIStringAttributeKey.ForegroundColor, UIColor.Yellow, new


NSRange (22, 6));

TKChartBalloonAnnotation balloon = new TKChartBalloonAnnotation (new NSString("Mar"),


new NSNumber(55), series);
balloon.AttributedText = attributedText;
balloon.Style.DistanceFromPoint = 20;
balloon.Style.ArrowSize = new Size (10, 10);
chart.AddAnnotation (balloon);

2161
Telerik UI for Xamarin

The AttributedText property can be used to present formatted text with NSAttributedString.

2162
Telerik UI for Xamarin

Layer and view annotations


The TKChartLayerAnnotation and TKChartViewAnnotations are also point annotations. Those
allow positioning a layer or a view inside the chart. The following code will position an image at the
center of the chart:

C#
UIImageView imageView = new UIImageView ();
imageView.Image = UIImage.FromBundle ("logo.png");
imageView.Bounds = new CGRect (0, 0, imageView.Image.Size.Width,
imageView.Image.Size.Height);
imageView.Alpha = 0.7f;
chart.AddAnnotation (new TKChartViewAnnotation(imageView, new NSNumber(550), new
NSNumber(90), chart.Series[0]));
 

2163
Telerik UI for Xamarin

2164
Telerik UI for Xamarin

Chart for Xamarin.iOS: Custom Drawing


TKChart has a powerful drawing engine to help you customize your chart appearance. It allows you
to:

 define different kinds of fills. Solid color, Linear gradient, Radial gradient, fill with image
content.
 define strokes which contain information about stroke fill, dash pattern, line width etc.
 define fill & stroke's corner radius, which corners to apply that radius to. It also supports
drawing insets.

Working with fills


There are several kinds of fills:

Solid fill
TKSolidFill is the simplest of all fills. It paints chart items with a single color. Here is how you
define it:

C#
var fill = new TKSolidFill (UIColor.Red);
 

After you set it to a palette (discussed later) you get result like this:

2165
Telerik UI for Xamarin

You can also specify corner radius:

C#
var fill = new TKSolidFill (UIColor.Red, 5.0f);
 

This results in columns looking like this:

2166
Telerik UI for Xamarin

All fills and strokes allow you to specify not only corner radius, but also which corners to round.
Semi-transparent red fill with only two corners rounded can be defined like this:

C#
var fill = new TKSolidFill (new UIColor (1.0f, 0.0f, 0.0f, 0.5f), 8.0f);
fill.Corners = UIRectCorner.TopLeft | UIRectCorner.BottomRight;
 

There you get:

2167
Telerik UI for Xamarin

Linear gradient fill


TKLinearGradientFill allows you to fill an item with color gradients. You can specify which colors
to use and relative to the size positions of gradient stops.

Here is how you define linear gradient with 3 colors (green to red to blue) with transparency:

C#
var fill = new TKLinearGradientFill (new UIColor[] {
new UIColor (0.0f, 1.0f, 0.0f, 0.6f),
new UIColor (1.0f, 0.0f, 0.0f, 0.6f),
new UIColor (0.0f, 0.0f, 1.0f, 0.6f)
},
new CGPoint(0, 0),
new CGPoint(1, 1));
 

2168
Telerik UI for Xamarin

If you wish to distribute those colors unevenly and change gradient direction here is how to do it:

C#
var fill = new TKLinearGradientFill (new UIColor[] {
new UIColor (0.0f, 1.0f, 0.0f, 0.6f),
new UIColor (1.0f, 0.0f, 0.0f, 0.6f),
new UIColor (0.0f, 0.0f, 1.0f, 0.6f)
},
new NSObject[] { new NSNumber(0.6), new NSNumber(0.8), new NSNumber(1.0) },
new CGPoint(0, 0),
new CGPoint(1, 1));
 

Warning: All coordinates for locations, startPoint and endPoint parameters are relative to the size of
drawing surface. The values of locations array must be monotonically increasing.

2169
Telerik UI for Xamarin

Radial gradient fill


TKRadialGradientFill draws a fill with two colors using centers relative to the drawing size.
Radius is set in different measures depending on TKGradientRadiusType parameter. It is hard to
master and most of the time you can achieve the same functionality with linear gradient. Here is a
possible usage:

C#
var fill = new TKRadialGradientFill (new UIColor[] {
new UIColor (0.0f, 1.0f, 0.0f, 0.7f),
new UIColor (1.0f, 0.0f, 0.0f, 0.0f)
},
new CGPoint (0.5f, 0.5f),
0.7f,
new CGPoint (0, 1),
0.3f,
TKGradientRadiusType.RectMax);
 

The resulting ghost column chart looks like this:

2170
Telerik UI for Xamarin

Image fill
TKImageFill fills the drawing area with the content of an image. There is also a ResizingMode
which specify how to draw image. Here is an example usage of tiled image:

C#
var fill = new TKImageFill (new UIImage ("pattern1.png"), 4.0f);
fill.ResizingMode = TKImageFillResizingMode.Tile;
 

2171
Telerik UI for Xamarin

this is the source (pattern) image to draw:

<= original     <= 8 times magnified version

Filling with images in stretch mode is even easier:

C#
var fill = new TKImageFill (new UIImage ("building1.png"), 4.0f);
 

2172
Telerik UI for Xamarin

Sometimes you like to specify your own stretchable image. Stretching this image with your own
code, leads to the following result:

C#
UIImage image = new UIImage ("pattern2.png");
var fill = new TKImageFill (image.CreateResizableImage (new UIEdgeInsets (10, 10, 10,
10)));
fill.ResizingMode = TKImageFillResizingMode.None;
 

2173
Telerik UI for Xamarin

Adding stroke
TKStroke is a powerful tool which allows you to customize how you apply strokes to your charts.

You can create a simple stroke like this:

C#
var stroke = new TKStroke (UIColor.Blue);
 

With rounded corners:

C#
var stroke = new TKStroke (UIColor.Blue, 1.0f);
stroke.CornerRadius = 5.0f;
 

With dash pattern:

C#
var stroke = new TKStroke (UIColor.Blue, 1.0f);
stroke.CornerRadius = 5.0f;
stroke.DashPattern = new NSNumber[] { new NSNumber(2), new NSNumber(2), new
NSNumber(5), new NSNumber(2) };
 

2174
Telerik UI for Xamarin

You can fill a stroke with a gradient:

C#
var fill = new TKLinearGradientFill (new UIColor[] {
new UIColor (0.0f, 1.0f, 0.0f, 0.6f),
new UIColor (1.0f, 0.0f, 0.0f, 0.6f),
new UIColor (0.0f, 0.0f, 1.0f, 0.6f)
}, new CGPoint(0, 0), new CGPoint(1, 1));
var stroke = new TKStroke (fill, 1.0f);
stroke.CornerRadius = 5.0f;
 

Or combine most of it in one place:

C#
var fill = new TKLinearGradientFill(new UIColor[] {
new UIColor (0.0f, 1.0f, 0.0f, 0.6f),
new UIColor (1.0f, 0.0f, 0.0f, 0.6f),
new UIColor (0.0f, 0.0f, 1.0f, 0.6f)
}, new CGPoint(0, 0), new CGPoint(1, 1));
var stroke = new TKStroke (fill, 1.0f);
stroke.CornerRadius = 5.0f;
stroke.DashPattern = new NSNumber[] { new NSNumber(2), new NSNumber(2), new
NSNumber(5), new NSNumber(2) };
stroke.Corners = UIRectCorner.TopRight | UIRectCorner.BottomLeft;
 

And here is the result of all samples:

2175
Telerik UI for Xamarin

or with line chart using strokes with width = 2

2176
Telerik UI for Xamarin

Customizing TKChart
Customizing TKChart can be done using TKChartPalette. You can access the palette from
TKChartSeries using series.Style.Palette variable. By default, palette is nil which means that
TKChart will use its default theme. To specify your own, you need to create it:

C#
TKChartSeries series = null;
series.Style.Palette = new TKChartPalette();
 

TKChartPalette is a collection of TKChartPaletteItem instances. Every item contains information


about drawing the item at its index. By default, a palette item index addresses the order in which you
add series. For example, you may have a palette with red and blue fills and two
TKChartColumnSeries using this palette. The first series you add will be red and the second blue.
However, TKChartPieSeries by default uses another mode when every palette item is used to
display a data point at its index. You can explicitly set how you distribute a palette items using:

C#
series.Style.PaletteMode = TKChartSeriesStylePaletteMode.UseItemIndex;
 

or

C#
series.Style.PaletteMode = TKChartSeriesStylePaletteMode.UseSeriesIndex;
 

Whenever TKChartPalette runs out of colors (because there are more series or more data points
than TKChartPaletteItem items inside) it starts over effectively cycling through its items.

To illustrate the difference between palette modes, consider the following setup:

C#
List<TKChartDataPoint> gdpInPoundsPoints = null;

var series = new TKChartColumnSeries (gdpInPoundsPoints.ToArray());


series.Style.Palette = new TKChartPalette ();

var redFill = new TKSolidFill (UIColor.Red);


series.Style.Palette.AddPaletteItem (new TKChartPaletteItem (redFill));

var blueFill = new TKSolidFill (UIColor.Blue);


series.Style.Palette.AddPaletteItem (new TKChartPaletteItem (blueFill));

var greenFill = new TKSolidFill (UIColor.Green);


series.Style.Palette.AddPaletteItem (new TKChartPaletteItem (greenFill));

series.Style.PaletteMode = TKChartSeriesStylePaletteMode.UseItemIndex;
chart.AddSeries (series);

2177
Telerik UI for Xamarin

As you see we are using TKChartSeriesStylePaletteModeUseItemIndex palette mode and the


result is:

Here the palette items are used to color the different data points. Since palette items inside are 3
and data points are 5, the palette starts over reusing the items it has. If you remove the line:

C#
series.Style.PaletteMode = TKChartSeriesStylePaletteMode.UseItemIndex;
 

or change it to:

C#
series.Style.PaletteMode = TKChartSeriesStylePaletteMode.UseSeriesIndex;
 

you will get:

2178
Telerik UI for Xamarin

This is because you have added only one series. Adding a second series with the same palette will
make its data points blue. Adding a third series will make its data points green and fourth would be
red again.

Palette items
TKChartPaletteItem is the building block of TKChartPalette and contains information about
how to draw items. The simple way to use it is to specify a fill and/or stroke. Consider one of the
following constructors:

C#
var paletteItem1 = new TKChartPaletteItem (new TKSolidFill (UIColor.Red));
var paletteItem2 = new TKChartPaletteItem(new TKStroke(UIColor.Blue));
var plaetteItem3 = new TKChartPaletteItem(new TKStroke(UIColor.Blue), new
TKSolidFill(UIColor.Red));

series.Style.Palette.AddPaletteItem (paletteItem1);
 

When you initialize a palette item with stroke and fill the stroke is always drawn last.

There is also an alternative and a more flexible way to create a palette item by specifying an array of
fills and strokes in the order you would like them to be drawn:

C#
series.Style.Palette = new TKChartPalette ();

2179
Telerik UI for Xamarin

var redFill = new TKSolidFill (UIColor.Red, 2.0f);


var stroke1 = new TKStroke (UIColor.Yellow, 1.0f);
stroke1.CornerRadius = 2.0f;
stroke1.Insets = new UIEdgeInsets (1, 1, 1, 1);
var stroke2 = new TKStroke (UIColor.Black, 1.0f);
stroke2.CornerRadius = 2.0f;
series.Style.Palette.AddPaletteItem(new TKChartPaletteItem(new TKDrawing[] { redFill,
stroke1, stroke2 }));
 

here you create a palette item with red fill and two borders. The sample also shows another powerful
feature: insets. Insets can be applied to both fills and strokes. Here is the final result:

Customizing line series


TKChartLineSeries uses only TKStroke instances of TKChartPaletteItem and ignores any fills.
You can specify a wide first stroke and thin second stroke if you need more than one stroke.

Customizing area series


TKChartAreaSeries uses TKStroke instances of TKChartPaletteItem for the line and fills for
area part.

Customizing scatter series


TKChartScatterSeries uses palette items to draw its shapes. However you might also change

2180
Telerik UI for Xamarin

shape's type using code like:

C#
series.Style.PointShape = new TKPredefinedShape (TKShapeType.Rhombus, new CGSize (15,
15));
 

series.Style.PointShape also applies to line and area series in case you need to show shapes on
data points.

Customizing pie series


TKChartPieSeries always use series.Style.PaletteMode =
TKChartSeriesStylePaletteModeUseItemIndex;. If you have strokes with insets, only
Insets.Top value will be used and will be applied relatively to the outer radius of the pie chart slices.

@warning Customization is a very powerful feature of TKChart. However, we recommend using that
feature at an acceptable rate. Using too many fills and strokes may affect performance. Combining
all features like a dashed stroke with gradient plus several semi transparent fills will draw much
slower than a simple solid color fill.

2181
Telerik UI for Xamarin

Chart for Xamarin.iOS: Trackball


TKChart provides a trackball behavior through the TKChartTrackball class. The trackball can be
used to display a vertical (or horizontal) line across the chart plot area and also to display little visual
indicators (circles by default) at points where the trackball line crosses the visualization of a series
object.

For example when the trackball line crosses a line series line segment, a small circle is drawn
highlighting the value of the series at this point. A screenshot should best explain this:

The last capability of the trackball is to display a small tooltip in order to provide more detailed
information about the closest points to the trackball line's cross section, as can be seen in the
screenshot above.

The trackball behavior is activated by setting the AllowTrackball property of TKChart to true. The
trackball is accessible by using the Trackball property of TKChart. It activates automatically when
you touch the chart for a few seconds, however it can be shown/hidden programmatically by calling
its ShowAtPoin and Hide methods.

The trackball exposes four properties that could be used to control its appearance and behavior.
These are:

SnapMode

2182
Telerik UI for Xamarin

SnapMode property determines how the trackball line will be snapped to the chart's data points. Valid
property values are TKChartTrackballSnapMode.ClosestPoint and
TKChartTrackballSnapMode.AllClosestPoints with
TKChartTrackballSnapMode.ClosestPoint snapping to the closest point of all data points in the
chart and TKChartTrackballSnapMode.AllClosestPoints snapping to the closest point from
each series object in the chart, that is, it snaps to multiple data points at once. Again, a few
screenshots will best describe the different values of SnapMode:

With SnapMode set to ClosestPoint:

With SnapMode set to AllClosestPoints:

2183
Telerik UI for Xamarin

Orientation
Оrientation property determines whether the trackball will track points horizontally or vertically.
When the orientation is set to TKChartTrackballOrientation.Vertical, which is the default
option, it will search within the touched area for points with similar x-coordinates by different
y-coordinate and the trackball line will be vertical. If the property is set to
TKChartTrackballOrientation.Horizontal, the trackball will compare y-coordinates instead
and the trackball line will be horizontal.

Line
Line property represents the trackball line. Its Style property could be used to customize the line
appearance. For example, its color and crossing point shape:

C#
chart.Trackball.Line.Hidden = false;
chart.Trackball.Line.Style.VerticalLineStroke = new TKStroke(UIColor.Red);
chart.Trackball.Line.Style.PointShape = new TKPredefinedShape(TKShapeType.Rhombus, new
SizeF(10, 10));
chart.Trackball.Line.Style.PointShapeFill = new TKSolidFill(UIColor.Red);
chart.Trackball.Line.Style.PointShapeStroke = new TKStroke(UIColor.Red);
 

2184
Telerik UI for Xamarin

Tooltip
Tooltip property represents the tooltip that shows information about the crossing points. As usual
its Style property could be used to customize its appearance. The PinPosition property
determines where the trackball tooltip should be located. The available pin positions are specified
below:

 TKChartTrackballPinPosition.None - The tooltip will appear next to the selected point.


 TKChartTrackballPinPosition.Left - The tooltip will appear on the left side of the plot
area.
 TKChartTrackballPinPosition.Right - The tooltip will appear on the right side of the
plot area.
 TKChartTrackballPinPosition.Top - The tooltip will appear on the top side of the plot
area.
 TKChartTrackballPinPosition.Bottom - The tooltip will appear on the bottom side of
the plot area.

The TrackballDidTrackSelection method of the chart delegate will be called as the users drag their
finger across the chart area. The selection argument of this method contains information about the
selected points for every touch position. This method could be used to customize the tooltip text, for
example:

C#
class ChartDelegate: TKChartDelegate

2185
Telerik UI for Xamarin

{
public override void TrackballDidTrackSelection (TKChart chart,
TKChartSelectionInfo[] selection)
{
StringBuilder str = new StringBuilder();
bool first = true;
foreach (TKChartSelectionInfo info in selection) {
var point = info.DataPoint as TKChartDataPoint;
if (!first) {
str.Append ("\n");
} else {
first = !first;
}
str.Append (string.Format ("Day {0} series {1} - {2}", point.DataXValue,
info.Series.Index + 1, point.DataYValue));
}
chart.Trackball.Tooltip.Text = str.ToString();
}
}
 

2186
Telerik UI for Xamarin

Chart for Xamarin.iOS: Zoom and Pan


Zoom and Pan feature handles touch events to enable panning and zooming of the associated chart
plot area.

Zoom
TKChart allows the end-user to zoom the plot area on the X and Y axis independently or on both
axes together. Zooming in and out on an axis can be enabled by setting the AllowZoom property of
the axis to true.

To activate this behavior for both axes, you should apply this setting to each axis separately.

C#
xAxis.AllowZoom = true;
yAxis.AllowZoom = true;
 

TKChartAxis exposes a property ZoomRange of type TKRange by the help of which you can define
the allowed zoom range.

The zoom level could be also explicitly set to a number by using the Zoom property of TKChartAxis.
This way you can control the zoom level at which TKChart appears when initialized.

Pan
The pan functionality allows moving the visible area of the chart when it is zoomed in. To enable
panning, you can use the TKChartAxis property AllowPan. Enabling pan in both sides could be
done by setting both directions pan property.

C#
xAxis.AllowPan = true;
yAxis.AllowPan = true;
 

TKChartAxis exposes two properties dedicated to control the pan level of the axis - Pan and
NormalizedPan .

Pan property can have any value that is compatible with the axis. If the property is set, the chart's
visible area will start from the given value when TKChart is initialized. If the axis is not zoomed
enough, then TKChart will visualize the most right/down area depending on the zoom level.

The value of the NormalizedPan property can be set between 0 and 1 and it represents a
normalized value of the axis. The chart visible area will be moved based on the calculated value
corresponding to the NormalizedPan value depending on the type of the axis.

2187
Telerik UI for Xamarin

Additionally you can apply inertia to your pan gesture by setting the AllowPanDeceleration
property of the TKChart to true.

C#
chart.AllowPanDeceleration = true;
 

2188
Telerik UI for Xamarin

Chart for Xamarin.iOS: Custom Animations


TKChart uses the Core Animation infrastructure available on iOS that you use to animate the visual
points in series. In order to enable the animations, you should set AllowAnimations property to
true. In that case the default animations are performed for each series. If you handle the
TKChartDelegate protocol and implement the AnimationForSeries method, you can perform
custom animations. With Core Animation, most of the work required to draw each frame of an
animation is done for you. All you have to do is configure a few animation parameters (such as the
start and end points).

You can use most of the Core Animation framework to customize the visual points animation. You
can read more about Core Animation at Apple Developer website.

Configuration Prerequisites
You should handle the TKChartDelegate's method AnimationForSeries to create a custom
animation. In addition, you should group the animation created for each point in CAAnimationGroup
to apply animation sequentially. You can access old and new points collection by using the
TKChartSeriesRenderState properties OldPoints and Points. It allows generation for value
key path property for point at a specified index by calling the animationKeyPathForPointAtIndex
method.

Animating Line Series


The code below animates the line series points by moving them from bottom to top.

C#
public override CAAnimation AnimationForSeries (TKChart chart, TKChartSeries series,
TKChartSeriesRenderState state, CGRect rect)
{
double duration = 0;
List<CAAnimation> animations = new List<CAAnimation> ();

for (int i = 0; i<(int)state.Points.Count; i++)


{
TKChartVisualPoint point = (TKChartVisualPoint)state.Points.ObjectAtIndex
((uint)i);

if (Grow)
{
string keyPath = string.Format ("seriesRenderStates.{0}.points.{1}.x",
series.Index, i);

CABasicAnimation animation =
(CABasicAnimation)CABasicAnimation.FromKeyPath(keyPath);
animation.Duration = 0.1 *(i + 0.2);
animation.From = new NSNumber(0);
animation.To = new NSNumber(point.X);
animation.TimingFunction = CAMediaTimingFunction.FromName

2189
Telerik UI for Xamarin

(CAMediaTimingFunction.EaseOut);
animations.Add(animation);

duration = animation.Duration;
}
else
{
string keyPath = string.Format ("seriesRenderStates.{0}.points.{1}.y",
series.Index, i);
nfloat oldY = rect.Height;

if (i > 0)
{
CAKeyFrameAnimation animation =
(CAKeyFrameAnimation)CAKeyFrameAnimation.GetFromKeyPath(keyPath);
animation.Duration = 0.1* (i + 1);
animation.Values = new NSNumber[] { new NSNumber(oldY), new NSNumber(oldY), new
NSNumber(point.Y) };
animation.KeyTimes = new NSNumber[] { new NSNumber(0), new NSNumber(i/(i+1.0)),
new NSNumber(1) };
animation.TimingFunction =
CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseOut);
animations.Add (animation);

duration = animation.Duration;
}
else
{
CABasicAnimation animation =
(CABasicAnimation)CABasicAnimation.FromKeyPath(keyPath);
animation.From = new NSNumber(oldY);
animation.To = new NSNumber(point.Y);
animation.Duration = 0.1f;
animations.Add(animation);
}
}
}

CAAnimationGroup group = new CAAnimationGroup ();


group.Duration = duration;
group.Animations = animations.ToArray();

return group;
}
 

Animating Pie Series


The following lines of code animate the pie's segments by moving them to the pie center together
with changing their opacity.

C#
public override CAAnimation AnimationForSeries (TKChart chart, TKChartSeries series,

2190
Telerik UI for Xamarin

TKChartSeriesRenderState state, CGRect rect)


{
double duration = 0;
List<CAAnimation> animations = new List<CAAnimation>();
for (int i = 0; i<(int)state.Points.Count; i++) {
string pointKeyPath = state.AnimationKeyPathForPointAtIndex ((uint)i);

string keyPath = string.Format("{0}.distanceFromCenter", pointKeyPath);


CAKeyFrameAnimation a = CAKeyFrameAnimation.GetFromKeyPath(keyPath);
a.Values = new NSNumber[] { new NSNumber(50), new NSNumber(50), new NSNumber(0)
};
a.KeyTimes = new NSNumber[] { new NSNumber(0), new NSNumber(i/(i+1.0)), new
NSNumber(1) };
a.Duration = 0.3 * (i+1.1);
animations.Add(a);

keyPath = string.Format("{0}.opacity", pointKeyPath);


a = CAKeyFrameAnimation.GetFromKeyPath(keyPath);
a.Values = new NSNumber[] { new NSNumber(0), new NSNumber(0), new NSNumber(1)
};
a.KeyTimes = new NSNumber[] { new NSNumber(0), new NSNumber(i/(i+1.0)), new
NSNumber(1) };
a.Duration = 0.3 * (i+1.1);
animations.Add(a);

duration = a.Duration;
}
CAAnimationGroup g = new CAAnimationGroup();
g.Duration = duration;
g.Animations = animations.ToArray();
return g;
}
 

2191
Telerik UI for Xamarin

Chart for Xamarin.iOS: UIKit Dynamics Animations


TKChart can uses the UIKit Dynamics physics engine integrated in iOS 7.0 to animate the points in
series. It allows you to create interfaces that feel real by adding behaviors such as gravity,
attachments (springs) and forces. You define the physical traits that you would like your interface
elements to adopt, and the dynamics engine takes care of the rest.

You should set the AllowAnimations property to true to enable UIKit Dynamics animations.

Configuration
The approach below shows how you can apply a fall down animation to the visual points in line
series.

C#
animator = new UIDynamicAnimator (chart.PlotView);
TKChartVisualPoint[] points = chart.VisualPointsForSeries (chart.Series [0]);
TKChartVisualPoint point = points [4];

for (int i=0; i<originalValues.Count; i++) {


TKChartVisualPoint pt = points [i];
if (pt.Animator != null) {
pt.Animator.RemoveAllBehaviors();
pt.Animator = null;
}
pt.Center = ((CGPoint)originalValues[i]);
}

point.Center = new CGPoint (originalLocation.X, 0);

UICollisionBehavior collision = new UICollisionBehavior (points);


collision.TranslatesReferenceBoundsIntoBoundary = true;

UIGravityBehavior gravity = new UIGravityBehavior (points);


gravity.GravityDirection = new CGVector (0.0f, 2.0f);

UIDynamicItemBehavior dynamic = new UIDynamicItemBehavior (points);


dynamic.Elasticity = 0.5f;

animator.AddBehavior(dynamic);
animator.AddBehavior(gravity);
animator.AddBehavior(collision);
 

2192
Telerik UI for Xamarin

Chart for Xamarin.iOS: Axes Overview


TKChart renders its points in a coordinate system defined by its axes. To do this, axes specify the
minimum and maximum values that can be presented on the plot area. There are a few different
types of axes that can be used with TKChart. They include: numeric, date/time and categoric. You
can assign each axis to different series and you can show multiple axes in chart. Axes contain
various properties to control their position, style and behavior. All chart axes subclass from
TKChartAxis.

 Use TKChartNumericAxis to present numeric values.


 Use TKChartLogarithmicAxis to represent numeric values by using logarithmic scale.
 Use TKChartDateTimeAxis to present date/time values.
 Use TKChartDateTimeCategoryAxis to present discontinuous date/time values.
 Use TKChartCategoryAxis to present categoric values.

This article discusses the common characteristics of the abstract class TKChartAxis, which is the
class all TKChart axes derive from. The axes automatically calculate its maximum and minimum
properties, based on the incoming data.

Adding axes in TKChart


By default TKChart creates its axes automatically based on the provided data. The axes can be
accessed by using the XAxis and YAxis properties of TKChartSeries. Use those properties to
customize your axes appearance.

C#
chart.XAxis.Style.LabelStyle.Font = UIFont.SystemFontOfSize (18);
 

TKChart creates the following axes based on your data:

 TKChartNumericAxis is created by default for both axes when using TKChartScatterSeries


 TKChartCategoryAxis is created by default for the x axis when using TKChartColumnSeries
 TKChartCategoryAxis is created by default for the y axis when using TKChartBarSeries
 TKChartNumericAxis is created when your points contain NSNumber values.
 TKChartDateTimeAxis is created when your points contain NSDate values.
 TKChartCategoryAxis is created in all other cases.
 TKChartPieSeries ignore the xAxis and yAxis properties.

Sometimes, it is necessary to set the axes explicitly. For example, you might want to change the axis
type or to set a custom range. In this scenario you can set the XAxis and YAxis properties directly
when creating your series:

C#
TKChartCategoryAxis xAxis = new TKChartCategoryAxis ();
xAxis.Position = TKChartAxisPosition.Bottom;
xAxis.PlotMode = TKChartAxisPlotMode.BetweenTicks;

2193
Telerik UI for Xamarin

series.XAxis = xAxis;
 

The Axes property in TKChart can be used to iterate through all axes in chart.

Axes Common Properties


There are several important properties which allow customization of the behavior and appearance of
each axis:

 Style - contains a set of properties which define the visual style of an axis and its labels.
 Position - defines where the axis is positioned in relation to the plot area.
 PlotMode - defines how the associated series is rendered in relation to the axis.
 AllowZoom - allows zooming by this axis.
 Zoom - determines the zoom level for this axis.
 AllowPan - allows panning by this axis.
 Pan - determines the pan level for this axis.
 Title - defines the axis title. Note that it sets internally the attributedTitle property.
 AttributedTitle - defines the axis attributedTitle, which allows text formatting.
 LabelFormat - defines a format string for axis labels.
 LabelFormatter - defines a label formatter for axis labels.
 TickCount - returns the count of axis labels.

Configure Axes Position


You can change the axis position by setting its position property to one of the following
values:TKChartAxisPositionLeft, TKChartAxisPositionRight, TKChartAxisPositionTop
and TKChartAxisPositionBottom.

The following lines of code demonstrate how you can create multiple axes at different positions:

C#
TKChartDateTimeAxis periodXAxis = new TKChartDateTimeAxis ();
periodXAxis.MajorTickIntervalUnit = TKChartDateTimeAxisIntervalUnit.Years;
periodXAxis.MinorTickIntervalUnit = TKChartDateTimeAxisIntervalUnit.Years;
periodXAxis.MajorTickInterval = 1;
periodXAxis.Position = TKChartAxisPosition.Bottom;
periodXAxis.PlotMode = TKChartAxisPlotMode.BetweenTicks;
chart.AddAxis (periodXAxis);

TKChartNumericAxis gdpInvestmentYAxis = new TKChartNumericAxis (new NSNumber(0), new


NSNumber(20));
gdpInvestmentYAxis.MajorTickInterval = 5;
gdpInvestmentYAxis.Position = TKChartAxisPosition.Right;
gdpInvestmentYAxis.Style.LabelStyle.TextAlignment = TKChartAxisLabelAlignment.Left;
gdpInvestmentYAxis.Style.MajorTickStyle.TicksHidden = false;
gdpInvestmentYAxis.Style.LineHidden = false;
chart.AddAxis (gdpInvestmentYAxis);
 

2194
Telerik UI for Xamarin

Configure Axes Appearance


You can customize any feature of the axis appearance. If you want to hide its line or change its line
stroke or background, you can use the following peace of code:

C#
chart.XAxis.Style.LineStroke = new TKStroke (UIColor.Black);
 

2195
Telerik UI for Xamarin

Configure Axes Ticks Appearance


In numeric/date-time axes you can specify the interval between axis ticks by setting the
MajorTickInterval and MinorTickInterval properties:

C#
xAxis.MajorTickInterval = 1;
xAxis.MinorTickInterval = 1;
 

2196
Telerik UI for Xamarin

You can customize the major and minor ticks of axis by manipulating the MajorTickStyle and
MinorTickStyle properties.

C#
xAxis.Style.MajorTickStyle.TicksOffset = -3;
xAxis.Style.MajorTickStyle.TicksHidden = false;
xAxis.Style.MajorTickStyle.TicksWidth = 1.5f;
xAxis.Style.MajorTickStyle.TicksFill = new TKSolidFill (new UIColor (203 / 255.0f, 203
/ 255.0f, 203 / 255.0f, 1f));
xAxis.Style.MajorTickStyle.MaxTickClippingMode = TKChartAxisClippingMode.Visible;
 

2197
Telerik UI for Xamarin

In addition to the common tick style customizations, you can specify the first and last ticks visibility
by setting MinTickClippingMode and MaxTickClippingMode properties:

C#
series.YAxis.Style.MajorTickStyle.MaxTickClippingMode =
TKChartAxisClippingMode.Visible;
series.YAxis.Style.MajorTickStyle.MinTickClippingMode =
TKChartAxisClippingMode.Visible;
 

Configure Axes Label Appearance


You can configure the axis label appearance by manipulating the LabelStyle property of the axis
style object. If you want to change the font, text color, shadow color and offset, you should modify
the corresponding properties:

C#

2198
Telerik UI for Xamarin

chart.YAxis.Style.LabelStyle.Font = UIFont.SystemFontOfSize (18);


chart.YAxis.Style.LabelStyle.TextColor = UIColor.Black;
 

You can define the label offset and alignment by setting the TextOffset and TextAlignment
properties:

C#
yAxis.Style.LabelStyle.TextAlignment = TKChartAxisLabelAlignment.Right |
TKChartAxisLabelAlignment.Bottom;
yAxis.Style.LabelStyle.FirstLabelTextAlignment = TKChartAxisLabelAlignment.Right |
TKChartAxisLabelAlignment.Top;
yAxis.Style.LabelStyle.TextOffset = new UIOffset (0, 0);
yAxis.Style.LabelStyle.FirstLabelTextOffset = new UIOffset (0, 0);
 

You can change the label fitting mode in the following manner:

C#
yAxis.Style.LabelStyle.FitMode = TKChartAxisLabelFitMode.Rotate;
 

2199
Telerik UI for Xamarin

Configure Axes Title Appearance


In order to change the change the axis title font, text color, shadow color, alignment and offset, you

2200
Telerik UI for Xamarin

should modify the corresponding properties:

C#
xAxis.Title = "Vendors";
xAxis.Style.TitleStyle.TextColor = UIColor.Gray;
xAxis.Style.TitleStyle.Font = UIFont.BoldSystemFontOfSize (11);
xAxis.Style.TitleStyle.Alignment = TKChartAxisTitleAlignment.RightOrBottom;
chart.ReloadData ();
 

Axes Types
Any Cartesian series supports the following axes:

 TKChartNumericAxis
 TKChartCategoryAxis
 TKChartDateTimeAxis
 TKChartLogarithmicAxis

Note that Pie series does not support axes.


 

2201
Telerik UI for Xamarin

Chart for Xamarin.iOS: Categoric Axis


TKChart uses Categoric axis to plot data that contains categoric values. The axis is valid only in the
context of Cartesian series. It also introduces several important properties:

 MajorTickInterval - defines an interval among major axis ticks.


 MinorTickInterval - defines an interval among minor axis ticks.
 Baseline - contains a value, which defines how the series data should be aligned. For
example, The TKChartBarSeries might render its bars up and down depending on whether
its value is greater or less than the baseline value.
 Offset - determines an axis value where the axis is crossed with another axis.

Configure a TKChartCategoryAxis
You can configure a category axis by settings its categories property. You should use the following
code snippet as a sample:

C#
List<TKChartDataPoint> list = new List<TKChartDataPoint> ();
string[] categories = new []{"Apple", "Google", "Microsoft", "Samsung"};
for (int i = 0; i < categories.Length; i++) {
list.Add(new TKChartDataPoint(new NSString(categories[i]), new NSNumber(r.Next() %
100)));
}

TKChartColumnSeries series = new TKChartColumnSeries (list.ToArray());


series.Selection = TKChartSeriesSelection.Series;

TKChartCategoryAxis xAxis = new TKChartCategoryAxis ();


xAxis.Position = TKChartAxisPosition.Bottom;
xAxis.PlotMode = TKChartAxisPlotMode.BetweenTicks;
series.XAxis = xAxis;
 

You can specify the axis range by setting the minimum and maximum indexes of categories.

Setting the plot mode of axis


The TKChartAxisPlotMode is used by the axis to plot the data. Possible values are
TKChartAxisPlotModeBetweenTicks and TKChartAxisPlotModeOnTicks.
TKChartAxisPlotModeBetweenTicks plots points in the middle of the range, defined by two ticks.
OnTicks plots the points over each tick.

You should use the following lines of code to alter this behavior:

C#
xAxis.PlotMode = TKChartAxisPlotMode.BetweenTicks;

2202
Telerik UI for Xamarin

C#
xAxis.PlotMode = TKChartAxisPlotMode.OnTicks;
 

2203
Telerik UI for Xamarin

2204
Telerik UI for Xamarin

Chart for Xamarin.iOS: Datetime Axis


TKChartDateTimeAxis categoric axis is an axis with NSDate values sorted chronologically. It also
allows definitions of categories based on specific date time components – year, month, day etc. For
example, if data values fall in the range of one year, the points can be plotted in categories for each
month. If data values fall in the range of one month, the values can be categorized by days. It also
introduces several important properties:

 MajorTickInterval - defines an interval between major axis ticks.


 Baseline - defines how the series data should be aligned. For example: The
TKChartBarSeries might render its bars up and down depending on whether its value is
greater or less than the baseline value.
 Offset - determines an axis value where the axis is crossed with another axis.

Configure a TKChartDateTimeAxis
You can configure a date-time axis by initializing it and setting it as the main x-axis or y-axis of the
chart:

C#
TKChartDateTimeAxis xAxis = new TKChartDateTimeAxis (minDate, maxDate);
xAxis.MajorTickIntervalUnit = TKChartDateTimeAxisIntervalUnit.Months;
xAxis.MajorTickInterval = 1;
 

You can define the axis categories by changing the interval unit property to one of the following
values:

 TKChartDateTimeAxisIntervalUnit.Seconds
 TKChartDateTimeAxisIntervalUnit.Minutes
 TKChartDateTimeAxisIntervalUnit.Hours
 TKChartDateTimeAxisIntervalUnit.Days
 TKChartDateTimeAxisIntervalUnit.Weeks
 TKChartDateTimeAxisIntervalUnit.Months
 TKChartDateTimeAxisIntervalUnit.Years
 TKChartDateTimeAxisIntervalUnit.Custom

2205
Telerik UI for Xamarin

Setting a plotting mode of axis


The TKChartAxisPlotMode is used by the axis to plot the data. Possible values are
TKChartAxisPlotMode.BetweenTicks and TKChartAxisPlotMode.OnTicks.
TKChartAxisPlotMode.BetweenTicks plots points in the middle of the range, defined by two
ticks. OnTicks plots the points over each tick.

You should use the following lines of code to alter this behavior:

C#
xAxis.PlotMode = TKChartAxisPlotMode.BetweenTicks;
 

2206
Telerik UI for Xamarin

2207
Telerik UI for Xamarin

Chart for Xamarin.iOS: Numeric Axis


TKChart uses Linear axes to plot data containing numerical values. It is valid only in the context of
Cartesian Area, this axis is created by default when you add Bar, Line, Area and Scatter series. It
also introduces several important properties:

 MajorTickInterval - defines the interval between major axis ticks.


 MinorTickInterval - defines the interval between minor axis ticks.
 Baseline - defines how the series data should be aligned. For example, The
TKChartBarSeries might render its bars up and down side depending on whether its value is
greater or less than the baseline value.
 Offset - Determines an axis value where the axis is crossed with another axis.
 IsLogarithmic - Determines whether the axis is linear or logarithmic.

Configure a TKChartNumericAxis
You can configure a numeric axis by initializing it and setting it as the main x-axis or y-axis of the
chart:

C#
TKChartNumericAxis yAxis = new TKChartNumericAxis ();
yAxis.Range = new TKRange (new NSNumber (0), new NSNumber (2000));
yAxis.Position = TKChartAxisPosition.Left;
yAxis.MajorTickInterval = 400;
yAxis.LabelDisplayMode = TKChartNumericAxisLabelDisplayMode.Percentage;
chart.YAxis = yAxis;
 

Numeric axes can also be modified to display percentage or values depending on your needs. This
modification is available with the LabelDisplayMode property - it accepts
TKChartNumericAxisLabelDisplayMode.Value (the default one) and
TKChartNumericAxisLabelDisplayMode.Percentage options.

2208
Telerik UI for Xamarin

2209
Telerik UI for Xamarin

Chart for Xamarin.iOS: Logarithmic Axis


TKChartLogarithmicAxis is used to display values that cover several orders of magnitude in a
more manageable way. This is a special numeric axis that transforms the actual values of the data
points using logarithm function with a specific base. For example if the base of the logarithm is 10,
then the axis will be scaled to show equally spaced powers of 10. The Richter scale and the Decibel
scale are examples of logarithmic scale. TKChartLogarithmicAxis is a subclass of
TKChartNumericAxis and introduces two important properties.

 LogarithmBase - the base of the logarithmic function used to calculate. the value.
 ExponentStep - specifies the exponent step between the axis ticks.

Configure a TKChartLogarithmicAxis
You can configure a logarithmic axis by setting its base property. The default base value is 10.

C#
TKChartLogarithmicAxis yAxis = new TKChartLogarithmicAxis();
yAxis.LogarithmBase = 2;
chart.YAxis = yAxis;
 

Logarithmic axis customization

2210
Telerik UI for Xamarin

You can also specify the exponent step between the axis ticks with the ExponentStep property. The
default value of the exponent step is 1 which means that the axis itself will calculate an exponent
step that will visualize the points in the best possible way. The ExponentStep should be a number
bigger than 0.

2211
Telerik UI for Xamarin

Chart for Xamarin.iOS: DateTimeCategory Axis


TKChartDateTimeCategoryAxis is a special axis that is similar to TKChartCategoryAxis and
adds notation for NSCalendarUnit enumeration. This axis uses the selected calendar units to
extract a key from dates. The key is used to build categories. Once build, categories are sorted in
chronological order.

The most important property of TKChartDateTimeCategoryAxis is the DateComponent. It is used


to specify which parts of the date are important. Its default value is TKCalendarUnitDate which is a
shortcut for NSCalendarUnitDay|NSCalendarUnitMonth|NSCalendarUnitYear.

Configure a TKChartDateTimeCategoryAxis
You can configure a date time category axis by setting the DateComponent property. Optionally you
can set properties like PlotMode and LabelFormatter to control the appearance of the axis:

C#
var xAxis = new TKChartDateTimeCategoryAxis ();
var formatter = new NSDateFormatter ();

2212
Telerik UI for Xamarin

formatter.DateFormat = "d MMM";


xAxis.LabelFormatter = formatter;
 

2213
Telerik UI for Xamarin

Chart for Xamarin.iOS: Axis Customization


The TKChartAxis is responsible for TKChart's axes. You can set custom ticks and color the axis
partially by using its property CustomLabels.

C#
this.chart.YAxis.CustomLabels = new NSDictionary(new NSNumber(100), UIColor.Blue,
new NSNumber(200), UIColor.Yellow,
new NSNumber(400), UIColor.Red);
 

2214
Telerik UI for Xamarin

TKChartAxis can have a custom render that you would use for drawing an axis completely by your
taste. For the purpose a new custom Axis should be created that derives from TKChartAxisRender
and its method RenderForChart should be overridden:

C#
class MyAxis : TKChartNumericAxis
{
public MyAxis (NSNumber minimum, NSNumber maximum)

2215
Telerik UI for Xamarin

: base(minimum, maximum)
{
}

public override TKChartAxisRender Render (TKChart chart)


{ return new AxisRender (this, chart);
}
}
 

Once this is done you are ready to start drawing in the DrawInContext method of your new axis
render:

C#
public class AxisRender: TKChartAxisRender
{
public AxisRender (TKChartAxis axis, TKChart chart)
: base(axis, chart)
{
}

public override void DrawInContext (CoreGraphics.CGContext ctx)


{
CGRect rect = this.BoundsRect();
CGColorSpace colorSpace = CGColorSpace.CreateDeviceRGB ();
nfloat [] colors = new nfloat[] {
0.42f, 0.66f, 0.31f, 1.0f,
0.95f, 0.76f, 0.20f, 1.0f,
0.80f, 0.25f, 0.15f, 1.0f
};

CGGradient gradient = new CGGradient (colorSpace, colors, null);

nuint tickSpaces = this.Axis.MajorTickCount - 1;


nuint pointsCount = 5;
if (this.Chart.Frame.Size.Height < this.Chart.Frame.Size.Width) {
pointsCount = 3;
}

nfloat diameter = 8;
nfloat spaceHeight = rect.Size.Height / tickSpaces;
nfloat spacing = (spaceHeight - (pointsCount * diameter)) / (pointsCount + 1);
nuint allPointsCount = pointsCount * tickSpaces;
CGPath multipleCirclePath = new CGPath ();
double y = rect.GetMinY() + diameter / 2.0f + spacing;

for (uint i = 1; i <= allPointsCount; i++) {


CGPoint center = new CGPoint (rect.GetMidX (), y);
CGPath path = new CGPath ();
path.AddArc (center.X, center.Y, (nfloat)diameter/2.0f, 0, (nfloat)Math.PI * 2,
true);
multipleCirclePath.AddPath (path);
y += spacing + diameter;

2216
Telerik UI for Xamarin

if (i % pointsCount == 0) {
y += spacing;
}
}

ctx.SaveState ();
ctx.AddPath (multipleCirclePath);
ctx.Clip ();
CGPoint startPoint = new CGPoint (rect.GetMidX (), rect.GetMinY ());
CGPoint endPoint = new CGPoint (rect.GetMidX (), rect.GetMaxY());
ctx.DrawLinearGradient (gradient, startPoint, endPoint, 0);
ctx.RestoreState ();

base.DrawInContext (ctx);
}

}
 

2217
Telerik UI for Xamarin

2218
Telerik UI for Xamarin

Chart for Xamarin.iOS: Point Labels Overview


TKChart supports point labels. Point labels are visual elements that are placed on the plot at the
location of series data points showing the data point's value or other string by your choice. By default
point labels are hidden. If you would like to show them, you should set TKChartPointLabelStyle's
TextHidden property to false. You can also alter offset origin of the labels using the LabelOffset
property.

C#
barSeries.Style.PointLabelStyle.TextHidden = false;
barSeries.Style.PointLabelStyle.LabelOffset = new UIOffset (15, 0);
 

2219
Telerik UI for Xamarin

Chart for Xamarin.iOS: Point Labels Customization


TKChart lets you customize point labels using TKChartPointLabelStyle's properties. However,
sometimes you may need to draw specific shapes for the labels. In such cases you should sublcass
TKChartPointLabel to create your own label and implement TKChartDelegate to use it.

Customization using TKChartPointLabelStyle properties


Here is an example how to customize point labels changing TKChartPointLabelStyle settings.

C#
TKChartLineSeries lineSeries = new TKChartLineSeries (dataPoints.ToArray ());
lineSeries.Selection = TKChartSeriesSelection.DataPoint;
lineSeries.Style.PointShape = new TKPredefinedShape (TKShapeType.Circle, new SizeF (8,
8));
lineSeries.Style.PointLabelStyle.TextHidden = false;
lineSeries.Style.PointLabelStyle.LabelOffset = new UIOffset (0, -24);
lineSeries.Style.PointLabelStyle.Insets = new UIEdgeInsets (-1, -5, -1, -5);
lineSeries.Style.PointLabelStyle.LayoutMode = TKChartPointLabelLayoutMode.Manual;
lineSeries.Style.PointLabelStyle.Font = UIFont.SystemFontOfSize (10);
lineSeries.Style.PointLabelStyle.TextAlignment = UITextAlignment.Center;
lineSeries.Style.PointLabelStyle.TextColor = UIColor.White;
lineSeries.Style.PointLabelStyle.Fill = new TKSolidFill (new UIColor ((float)(108 /
255.0), (float)(181 / 255.0), (float)(250 / 255.0), (float)1.0));
lineSeries.Style.PointLabelStyle.ClipMode = TKChartPointLabelClipMode.Hidden;
 

Custom point labels


Subclassing TKChartPointLabel lets you perform custom drawing and calculate the size of the
point label. Once you create your own label you should implement TKChartDelegate to use it.

2220
Telerik UI for Xamarin

C#
public override TKChartPointLabel LabelForDataPoint (TKChart chart, TKChartData
dataPoint, string propertyName, TKChartSeries series, nuint dataIndex)
{
TKChartDataPoint point = (TKChartDataPoint)dataPoint;
if (series.Index == (nuint)this.selectedSeriesIndex && dataIndex ==
(nuint)this.selectedDataPointIndex) {
return new MyPointLabel (point, series, String.Format ("{0}",
point.DataYValue));
}

return new TKChartPointLabel (point, series, String.Format ("{0}",


point.DataYValue));
}
 

2221
Telerik UI for Xamarin

Chart for Xamarin.iOS: Area Series


As a derivative of TKChartLineSeries series, TKChartAreaSeries plots its data points in line.
Once positioned on the plot area the points are connected to form a line. Further, the area enclosed
between this line and the axis is filled.

Below is a sample snippet that demonstrates how to set up two Area series:

C#
var pointsWithCategoriesAndValues = new List<TKChartDataPoint> ();
var pointsWithCategoriesAndValues2 = new List<TKChartDataPoint> ();

var categories = new [] { "Greetings", "Perfecto", "NearBy", "Family Store", "Fresh &
Green" };
var values = new [] { 70, 75, 58, 59, 88 };

for (int i = 0; i < categories.Length; ++i) {


pointsWithCategoriesAndValues.Add (new TKChartDataPoint (new NSString (categories
[i]), new NSNumber (values [i])));
}

var values2 = new [] { 40, 80, 32, 69, 95 };


for (int i = 0; i < categories.Length; ++i) {
pointsWithCategoriesAndValues2.Add (new TKChartDataPoint (new NSString (categories
[i]), new NSNumber (values2 [i])));
}

chart.AddSeries (new TKChartAreaSeries (pointsWithCategoriesAndValues.ToArray ()));


chart.AddSeries (new TKChartAreaSeries (pointsWithCategoriesAndValues2.ToArray ()));
 

2222
Telerik UI for Xamarin

Configure stacking of area series


The TKChartAreaSeries can be combined by using different stack modes.

The Stack plots the points on top of each other:

C#
var stackInfo = new TKChartStackInfo (new NSNumber (1), TKChartStackMode.Stack);

var seriesForIncome = new TKChartAreaSeries (pointsWithCategoriesAndValues.ToArray


());
seriesForIncome.StackInfo = stackInfo;

var seriesForExpenses = new TKChartAreaSeries (pointsWithCategoriesAndValues2.ToArray


());
seriesForExpenses.StackInfo = stackInfo;

chart.BeginUpdates ();
chart.AddSeries (seriesForIncome);
chart.AddSeries (seriesForExpenses);
chart.EndUpdates ();

2223
Telerik UI for Xamarin

The Stack100 displays the value as percent:

2224
Telerik UI for Xamarin

Configure visual appearance of area series


If you want to change the series' fill and stroke, you should modify the corresponding properties of
the TKChartPaletteItem:

C#
series.Style.Palette = new TKChartPalette ();
TKChartPaletteItem palleteItem = new TKChartPaletteItem ();
palleteItem.Stroke = new TKStroke(strokes[i], 1.5f);
palleteItem.Fill = new TKLinearGradientFill (fills[i], new CGPoint(0, 0), new
CGPoint(1, 1));
series.Style.Palette.AddPaletteItem(palleteItem);
 

2225
Telerik UI for Xamarin

Chart for Xamarin.iOS: Bubble Series


TKChartBubbleSeries derives from TKChartScatterSeries and it represents a bubble chart.
Bubble series visualizes TKChartBubbleDataPoint which has three parameters - DataXValue,
DataYValue and Area. The Scale and BiggestBubbleDiameterForAutoscale properties
determine the diameter of a bubble on the chart.

Here is an example of a bubble chart:

C#
Random r = new Random ();
for (int i = 0; i < 2; i++) {
List<TKChartBubbleDataPoint> list = new List<TKChartBubbleDataPoint> ();
for (int j = 0; j < 20; j++) {
list.Add (new TKChartBubbleDataPoint (new NSNumber (r.Next () % 1450), new
NSNumber (r.Next () % 150), new NSNumber (r.Next () % 200)));
}

TKChartBubbleSeries series = new TKChartBubbleSeries (list.ToArray());


 

2226
Telerik UI for Xamarin

Chart for Xamarin.iOS: Candlestick Series


TKChart supports Candlestick stock series. This series operates with a special kind of data in the
form of four parameters defining the stock market - open, high, low, and close. The high and low
values show the price range (the highest and lowest prices) over one unit of time. The open and
close values indicate the opening and closing price of the stock for the corresponding period.

Candlestick series have body, which has a different color depending on the value of open and close
prices of the financial data point. The width of the candlestick body is determined by the period
between 2 candlesticks and the range of the axis. You should use the MinorTickIntervalUnit
property of TKChartDateTimeAxis to change the period between 2 candlesticks. Here is how to set
up Candlestick series:

C#
var openPrices = new [] { 100, 125, 69, 99, 140, 125 };
var closePrices = new [] { 85, 65, 135, 120, 80, 136 };
var lowPrices = new [] { 50, 60, 65, 55, 75, 90 };
var highPrices = new [] { 129, 142, 141, 123, 150, 161 };
var dateNow = NSDate.Now;
var financialDataPoints = new List<TKChartFinancialDataPoint> ();

for (int i = 0; i < openPrices.Length; ++i) {


var date = dateNow.AddSeconds ((double)(60 * 60 * 24 * i));
financialDataPoints.Add (new TKChartFinancialDataPoint (date, new
NSNumber(openPrices [i]), new NSNumber(highPrices [i]),
new NSNumber(lowPrices [i]), new NSNumber(closePrices [i]), null));
}

var candlestickSeries = new TKChartCandlestickSeries (financialDataPoints.ToArray ());


chart.AddSeries (candlestickSeries);

var xAxis = chart.XAxis as TKChartDateTimeAxis;


xAxis.MinorTickIntervalUnit = TKChartDateTimeAxisIntervalUnit.Days;
xAxis.PlotMode = TKChartAxisPlotMode.BetweenTicks;
xAxis.MajorTickInterval = 1.0;
 

2227
Telerik UI for Xamarin

Configure visual appearance of candlestick series


If you want to customize the appearance of the candlestick series, you should implement
theTKChartDelegate protocol as shown below:

C#
public override TKChartPaletteItem PaletteItemForSeries (TKChart chart, TKChartSeries
series, nint index)
{
var dataPoint = series.DataPointAtIndex ((uint)index);
var stroke = new TKStroke (UIColor.Black);
var fill = new TKSolidFill ();
if (dataPoint.Close.DoubleValue < dataPoint.Open.DoubleValue) {
fill.Color = UIColor.Red;
} else {
fill.Color = UIColor.Green;
}
var paletteItem = new TKChartPaletteItem (stroke, fill);
return paletteItem;
}
 

2228
Telerik UI for Xamarin

![]../../images/chart-series-candlestick002.png)

2229
Telerik UI for Xamarin

Chart for Xamarin.iOS: Financial Indicators Series


This article provides a brief description and a list of the important properties of each indicator
supported by TKChart. The indicators are divided in two groups - Technical Overlays and Technical
Indicators. To set up a financial indicator, you have to initialize it with TKChartCandlestickSeries
or TKChartOhlcSeries containing financial data.

Technical Overlays
Here is an example how to create a Bollinger Band indicator:

C#
var candlesticks = new TKChartCandlestickSeries (financialDataPoints.ToArray ());
var bollingerBands = new TKChartBollingerBandIndicator (candlesticks);
financialChart.AddSeries (candlesticks);
financialChart.AddSeries (bollingerBands);
 

2230
Telerik UI for Xamarin

And here are the rest of the available Technical Overlays

 Simple Moving Average (SMA) - A simple moving average (SMA) is the unweighted mean of
the previous n data. To use this indicator you should instantiate
TKChartSimpleMovingAverageIndicator and change its Period property if needed.
 Exponential Moving Average (EMA) - A type of moving average that is similar to a simple
moving average, except that more weight is given to the latest data. Use
TKChartExponentialMovingAverageIndicator class.
 Weighted Moving Average - Weighted averages assign a heavier weighting to more current
data points. Use TKChartWeightedMovingAverageIndicator class.
 Triangular Moving Average - The Triangular Moving Average is a double-smoothed Simple
Moving Average that gives more weight to the middle section of the data interval. Use
TKChartTriangularMovingAverageIndicator class.
 Modified Moving Average - Modified moving averages are similar to simple moving
averages. The first point of the modified moving average is calculated the same way the first
point of the simple moving average is calculated. However, all subsequent points are
calculated by first adding the new price and then subtracting the last average from the
resulting sum. The difference is the new point, or modified moving average. Use
TKChartModifiedMovingAverageIndicator class.
 Adaptive Moving Average - uses three parameters to calculate its value: Period, SlowPeriod
and FastPeriod. Use TKChartAdaptiveMovingAverageIndicator class.
 Bollinger Bands - volatility bands placed above and below a moving average. Use
TKChartBollingerBandIndicator class.
 Moving Average Envelopes - percentage-based envelopes set above and below a moving
average. Use TKChartMovingAverageEnvelopesIndicator class.
 Typical Price - the arithmetic average of the high, low, and closing prices for a given period.
Use TKChartTypicalPriceIndicator class.
 Weighted Close - similar to Typical Price - the difference is that the weighted close place
greater weighting on closing price. Use TKChartWeightedCloseIndicator class.
 Median Price - the midpoint of each day's price. Use TKChartMedianPriceIndicator
class.

Technical Indicators
Here is an example how to set up Moving Average Convergence Divergence indicator:

C#
var candlesticks = new TKChartCandlestickSeries (financialDataPoints.ToArray());
var macdIndicator = new TKChartMACDIndicator (candlesticks);
macdIndicator.LongPeriod = 26;
macdIndicator.ShortPeriod = 12;
macdIndicator.SignalPeriod = 9;
financialChart.AddSeries (macdIndicator);
 

2231
Telerik UI for Xamarin

And here are the rest of the available Technical Indicators

 Moving Average Convergence Divergence - A trend-following momentum indicator that


shows the relationship between two moving averages of prices. Use
TKChartMACDIndicator class.
 Percentage Price Oscillator - a momentum oscillator that measures the difference between
two moving averages as a percentage of the larger moving average. Use
TKChartPercentagePriceOscillator class.
 Percentage Volume Oscillator - a momentum oscillator for volume. PVO measures the
difference between two volume-based moving averages as a percentage of the larger
moving average. Use TKChartPercentageVolumeOscillator class.
 Absolute Volume Oscillator - computes the difference between two average volume
measures. Use TKChartAbsoluteVolumeOscillator.
 Relative Strength Index - intended to chart the current and historical strength or weakness of
a stock or market based on the closing prices of a recent trading period. Use
TKChartRelativeStrengthIndex class.
 Relative Momentum Index - the aim of this indicator is to improve the data provided by the
classical RSI indicator if the price reaches oversold/overbought areas. Use
TKChartRelativeMomentumIndex class.
 Accumulation Distribution Line - a volume-based indicator designed to measure the
cumulative flow of money into and out of a security. Use

2232
Telerik UI for Xamarin

TKChartAccumulationDistributionLine class.
 True Range - measures the daily range plus any gap from the closing price of the preceding
day. Use TKChartTrueRangeIndicator class.
 Average True Range - an indicator that measures volatility. Use
TKChartAverageTrueRangeIndicator class.
 Commodity Channel Index - measures a security’s variation from the statistical mean. Use
TKChartCommodityChannelIndex class.
 Fast Stochastic Indicator - Stochastic Oscillator is a momentum indicator that shows the
location of the close relative to the high - low range over a set number of periods. Use
TKChartFastStochasticIndicator class.
 Slow Stochastic Indicator - The Slow Stochastic Oscillator smooths %K with a 3-day SMA,
which is exactly what %D is in the Fast Stochastic Oscillator. Use
TKChartSlowStochasticIndicator class.
 Full Stochastic Indicators - a fully customizable version of the Slow Stochastic Oscillator. Use
TKChartFullStochasticIndicator class.
 Rate Of Change - a pure momentum oscillator that measures the percent change in price
from one period to the next. Use TKChartRateOfChangeIndicator class.
 TRIX - a momentum oscillator that displays the percent rate of change of a triple
exponentially smoothed moving average. Use TKChartTRIXIndicator class.
 Williams %R Indicator - a momentum indicator that is the inverse of the Fast Stochastic
Oscillator. Use TKChartWilliamsPercentIndicator class.
 Ease Of Movement - a volume-based oscillator that fluctuates above and below the zero line.
Use TKChartEaseOfMovementIndicator class.
 Detrended Price Oscillator - an indicator designed to remove trend from price and make it
easier to identify cycles. Use TKChartDetrendedPriceOscillator class.
 Force Index - an indicator used to illustrate how strong the actual buying or selling pressure
is. Use TKChartForceIndexIndicator class.
 Rapid Adaptive Variance Indicator - measures trend intensity instead of trend direction. Use
TKChartRapidAdaptiveVarianceIndicator class.
 Standard Deviation - a statistical term that measures the amount of variability or dispersion
around an average. Use TKChartStandardDeviationIndicator class.
 On Balance Volume - measures buying and selling pressure as a cumulative indicator that
adds volume on up days and subtracts volume on down days. Use
TKChartOnBalanceVolumeIndicator class.
 Price Volume Trend - technical indicator consisting of a cumulative volume line that adds or
subtracts a multiple of the percentage change in share price trend and current volume,
depending upon their upward or downward movements. Use
TKChartPriceVolumeTrendIndicator class.
 Positive Volume Index - an indicator that is based on days where trading volume has
significantly increased from the previous day. Use
TKChartPositiveVolumeIndexIndicator class.
 Negative Volume Index - a cumulative indicator that uses the change in volume to decide
when the smart money is active. Use TKChartNegativeVolumeIndexIndicator class.
 Money Flow Index - an oscillator that uses both price and volume to measure buying and
selling pressure. Use TKChartMoneyFlowIndexIndicator class.
 Ultimate Oscillator - a technical indicator that uses the weighted average of three different
time periods to reduce the volatility and false transaction signals that are associated with
many other indicators that mainly rely on a single time period. Use
TKChartUltimateOscillator class.
 Market Facilitation Index - designed for evaluation the willingness of the market to move the
price. Use TKChartMarketFacilitationIndex class.

2233
Telerik UI for Xamarin

 Chaikin Oscillator - an oscillator which measures the accumulation distribution line of the
MACD. Use TKChartChaikinOscillator class.

2234
Telerik UI for Xamarin

Chart for Xamarin.iOS: OHLC Series


TKChart supports Ohlc stock series. This series operates with a special kind of data in the form of
four parameters defining the stock market - open, high, low, and close. The high and low values
show the price range (the highest and lowest prices) over one unit of time. The open and close
values indicate the opening and closing price of the stock for the corresponding period. The width of
the ohlc bar is determined by the period between 2 bars and the range of the axis. You should use
the MinorTickIntervalUnit property of TKChartDateTimeAxis to change the period between 2
ohlc bars. Here is how to set up OHLC series:

C#
var openPrices = new [] { 100, 125, 69, 99, 140, 125 };
var closePrices = new [] { 85, 65, 135, 120, 80, 136 };
var lowPrices = new [] { 50, 60, 65, 55, 75, 90 };
var highPrices = new [] { 129, 142, 141, 123, 150, 161 };
var dateNow = NSDate.Now;
var financialDataPoints = new List<TKChartFinancialDataPoint> ();

for (int i = 0; i < openPrices.Length; ++i) {


var date = dateNow.AddSeconds ((double)(60 * 60 * 24 * i));
financialDataPoints.Add (new TKChartFinancialDataPoint (date, new NSNumber
(openPrices [i]), new NSNumber (highPrices [i]),
new NSNumber (lowPrices [i]), new NSNumber (closePrices [i]), null));
}

var ohlcSeries = new TKChartOhlcSeries (financialDataPoints.ToArray ());


chart.AddSeries (ohlcSeries);

var xAxis = chart.XAxis as TKChartDateTimeAxis;


xAxis.MinorTickIntervalUnit = TKChartDateTimeAxisIntervalUnit.Days;
xAxis.PlotMode = TKChartAxisPlotMode.BetweenTicks;
xAxis.MajorTickInterval = 1;
 

2235
Telerik UI for Xamarin

Configure visual appearance of ohlc series


If you want to customize the appearance of ohlc series, you should implement the TKChartDelegate
protocol as shown below::

C#
public override TKChartPaletteItem PaletteItemForSeries (TKChart chart, TKChartSeries
series, nint index)
{
var dataPoint = series.DataPointAtIndex ((uint)index);
TKStroke stroke = null;
if (dataPoint.Close.DoubleValue < dataPoint.Open.DoubleValue) {
stroke = new TKStroke (UIColor.Red);
} else {
stroke = new TKStroke (UIColor.Green);
}
var paletteItem = new TKChartPaletteItem (stroke);
return paletteItem;
}
 

2236
Telerik UI for Xamarin

2237
Telerik UI for Xamarin

Chart for Xamarin.iOS: Bar Series


TKChartBarSeries are used to visualize data points as bar blocks where the width of each bar
denotes the magnitude of its value. The following snippet demonstrates how to manually populate
one Bar series:

C#
Random r = new Random ();
List<TKChartDataPoint> list = new List<TKChartDataPoint> ();
for (int i = 0; i < 8; i++) {
list.Add (new TKChartDataPoint (new NSNumber (r.Next () % 100), new NSNumber (i +
1)));
}

TKChartBarSeries series = new TKChartBarSeries (list.ToArray());


series.Style.PaletteMode = TKChartSeriesStylePaletteMode.UseItemIndex;
series.Selection = TKChartSeriesSelection.DataPoint;
chart.AddSeries (series);
 

Configure clustering of bar series

2238
Telerik UI for Xamarin

If you want to cluster multiple bar series side by side, they should use a shared y-axis:

C#
var pointsWithCategoriesAndValues = new List<TKChartDataPoint> ();
var pointsWithCategoriesAndValues2 = new List<TKChartDataPoint>();
var categories = new [] { "Greetings", "Perfecto", "NearBy", "Family Store", "Fresh &
Green" };
var values = new [] { 70, 75, 58, 59, 88 };

for (int i = 0; i < categories.Length; ++i) {


pointsWithCategoriesAndValues.Add (new TKChartDataPoint (new NSNumber (values
[i]), NSObject.FromObject (categories [i])));
}

var values2 = new [] { 40, 80, 32, 69, 95 };


for (int i = 0; i < categories.Length; ++i) {
pointsWithCategoriesAndValues2.Add (new TKChartDataPoint (new NSNumber(values2
[i]), NSObject.FromObject(categories [i])));
}

List<NSObject> objectCategories = new List<NSObject> ();


for (int i = 0; i < categories.Length; i++) {
objectCategories.Add (new NSString (categories [i]));
}
var categoryAxis = new TKChartCategoryAxis (objectCategories.ToArray());
chart.YAxis = categoryAxis;

var series1 = new TKChartBarSeries(pointsWithCategoriesAndValues.ToArray());


series1.YAxis = categoryAxis;

var series2 = new TKChartBarSeries(pointsWithCategoriesAndValues2.ToArray());


series2.YAxis = categoryAxis;

chart.BeginUpdates();
chart.AddSeries(series1);
chart.AddSeries(series2);
chart.EndUpdates();
 

2239
Telerik UI for Xamarin

Configure stacking of bar series


The TKChartBarSeries can be combined by using different stack modes, available options for
TKChartStackMode are Stack and Stack100.

The Stack plots the points on top of each other:

C#
var stackInfo = new TKChartStackInfo(new NSNumber(1), TKChartStackMode.Stack);

var series1 = new TKChartBarSeries(pointsWithCategoriesAndValues.ToArray());


series1.StackInfo = stackInfo;

var series2 = new TKChartBarSeries(pointsWithCategoriesAndValues2.ToArray());


series2.StackInfo = stackInfo;

chart.BeginUpdates();
chart.AddSeries(series1);
chart.AddSeries(series2);
chart.EndUpdates();
 

2240
Telerik UI for Xamarin

The Stack100 displays the value as percent:

C#
var stackInfo = new TKChartStackInfo(new NSNumber(1), TKChartStackMode.Stack100);

var series1 = new TKChartBarSeries(pointsWithCategoriesAndValues.ToArray());


series1.StackInfo = stackInfo;

var series2 = new TKChartBarSeries(pointsWithCategoriesAndValues2.ToArray());


series2.StackInfo = stackInfo;

chart.BeginUpdates();
chart.AddSeries(series1);
chart.AddSeries(series2);
chart.EndUpdates();
 

2241
Telerik UI for Xamarin

Configure visual appearance of bar series


If you would like to customize the appearance of bar series, you should change its Style properties.
You can change the fill and stroke in the following manner:

C#
var series = new TKChartBarSeries (pointsWithCategoriesAndValues.ToArray());
series.Style.Palette = new TKChartPalette ();

var paletteItem = new TKChartPaletteItem ();


paletteItem.Fill = new TKSolidFill (UIColor.Red);
paletteItem.Stroke = new TKStroke (UIColor.Black);
series.Style.Palette.AddPaletteItem (paletteItem);
chart.AddSeries (series);
 

2242
Telerik UI for Xamarin

You can change the gap between columns with the following code snippet:

C#
var series = new TKChartBarSeries (pointsWithCategoriesAndValues.ToArray ());
series.GapLength = 0.5f;
chart.AddSeries (series);
 

Note that the value should be between 0 and 1, where a value of 0 means that a bar would take the
entire space between two ticks, while a value of 1 means the bar will have zero width as all the
space should appear as a gap.

2243
Telerik UI for Xamarin

It is also possible to limit the height of the bar using MaxBarHeight and MinBarHeight properties.

C#
var series = new TKChartBarSeries (pointsWithCategoriesAndValues.ToArray ());
series.MinBarHeight = 20;
series.MaxBarHeight = 50;
chart.AddSeries (series);
 

2244
Telerik UI for Xamarin

Chart for Xamarin.iOS: Column Series


TKChartColumnSeries are used to visualize data points as column blocks where the height of
each bar denotes the magnitude of its value. The following snippet demonstrates how to manually
populate one Column series:

C#
Random r = new Random ();
List<TKChartDataPoint> list = new List<TKChartDataPoint> ();
for (int i = 0; i < 8; i++) {
list.Add(new TKChartDataPoint (new NSNumber (i+1), new NSNumber (r.Next () %
100)));
}

TKChartColumnSeries series = new TKChartColumnSeries (list.ToArray());


series.Style.PaletteMode = TKChartSeriesStylePaletteMode.UseItemIndex;
series.Selection = TKChartSeriesSelection.DataPoint;

series.MaxColumnWidth = 50;
series.MinColumnWidth = 20;

chart.AddSeries(series);
 

2245
Telerik UI for Xamarin

Configure clustering of column series


If you want to cluster multiple column series side by side, they should use a shared x-axis:

C#
Random r = new Random();
for (int i = 0; i < 4; i++) {
List<TKChartDataPoint> list = new List<TKChartDataPoint>();
for (int j = 0; j < 8; j++) {
list.Add(new TKChartDataPoint(new NSNumber(j), new NSNumber(r.Next() % 100)));
}

TKChartColumnSeries series = new TKChartColumnSeries (list.ToArray ());


series.Title = String.Format ("Series %d", i);
series.StackInfo = stackInfo;
series.Selection = TKChartSeriesSelection.Series;
chart.AddSeries (series);
}
 

2246
Telerik UI for Xamarin

Configure stacking of column series


The TKChartColumnSeries can be combined by using different stack modes, such as Stack and
Stack100.

The Stack plots the points on top of each other.

C#
var stackInfo = new TKChartStackInfo (new NSNumber (1), TKChartStackMode.Stack);

var seriesForIncome = new TKChartAreaSeries (pointsWithCategoriesAndValues.ToArray


());
seriesForIncome.StackInfo = stackInfo;

var seriesForExpenses = new TKChartAreaSeries (pointsWithCategoriesAndValues2.ToArray


());
seriesForExpenses.StackInfo = stackInfo;

chart.BeginUpdates ();
chart.AddSeries (seriesForIncome);
chart.AddSeries (seriesForExpenses);
chart.EndUpdates ();
 

2247
Telerik UI for Xamarin

The Stack100 displays the value as percent.

2248
Telerik UI for Xamarin

Configure visual appearance of column series


If you want to customize the appearance of a column series, you should change its Style
properties.

You can change the fill and stroke in the following manner:

C#
series.Style.Palette = new TKChartPalette ();

var paletteItem = new TKChartPaletteItem ();


paletteItem.Fill = new TKSolidFill (UIColor.Red);
paletteItem.Stroke = new TKStroke (UIColor.Black);
series.Style.Palette.AddPaletteItem (paletteItem);
chart.AddSeries (series);
 

2249
Telerik UI for Xamarin

You can change the gap between columns with the GapLength property.

C#
series.GapLength = 0.6f;
 

GapLength value should be between 0 and 1, where a value of 0 means that a bar would take the
entire space between two ticks, while a value of 1 means the bar will have zero width as all the
space should appear as a gap.
 

2250
Telerik UI for Xamarin

If you need to limit the width of the columns you can set the series MaxColumnWidth and
MinColumnWidth properties. These properties allow you to have required minimum and possible
maximum width for your series.

C#
series.MaxColumnWidth = 50;
series.MinColumnWidth = 20;
 

2251
Telerik UI for Xamarin

Chart for Xamarin.iOS: Donut Series


TKChartDonutSeries derives from TKChartPieSeries and it represents a donut chart. The
InnerRadius property determines the width of the donut, and it is measured in values between 0
and 1. The higher value you set in the range between 0 and 1, the thinner the donut will be. For
example, a value of 0.9 will make the donut chart take only 0.1 percent of the whole pie chart
surface.

Here is an example of a donut chart:

C#
var pointsWithValueAndName = new List<TKChartDataPoint> ();
pointsWithValueAndName.Add (new TKChartDataPoint (new NSNumber (20),
NSObject.FromObject ("Google")));
pointsWithValueAndName.Add (new TKChartDataPoint (new NSNumber (30),
NSObject.FromObject ("Apple")));
pointsWithValueAndName.Add (new TKChartDataPoint (new NSNumber (10),
NSObject.FromObject ("Microsoft")));
pointsWithValueAndName.Add (new TKChartDataPoint (new NSNumber (5),
NSObject.FromObject ("IBM")));
pointsWithValueAndName.Add (new TKChartDataPoint (new NSNumber (8),
NSObject.FromObject ("Oracle")));

var series = new TKChartDonutSeries(pointsWithValueAndName.ToArray());


series.InnerRadius = 0.5f;

chart.AddSeries(series);
chart.Legend.Hidden = false;
chart.Legend.Style.Position = TKChartLegendPosition.Right;
 

2252
Telerik UI for Xamarin

Chart for Xamarin.iOS: Spline Series


TKChartSpineSeries is similar to the line series, but instead of straight line segments, the spline
series connects its data points with smooth curves which represent rough approximations of the
missing data points.

Here is an example of a chart with a spline series:

C#
var profitData = new List<TKChartDataPoint> ();
var profitValues = new [] { 10, 45, 8, 27, 57 };
var categories = new [] { "Greetings", "Perfecto", "NearBy", "Family Store", "Fresh &
Green" };
for (int i = 0; i < categories.Length; ++i) {
profitData.Add(new TKChartDataPoint(new NSString(categories[i]), new
NSNumber(profitValues[i])));
}

chart.AddSeries(new TKChartSplineSeries(profitData.ToArray()));
 

2253
Telerik UI for Xamarin

As TKChartSplineSeries derives from TKChartLineSeries, it shares the same functionality. For more
details go to Chart for Xamarin.iOS: Line Series.

2254
Telerik UI for Xamarin

Chart for Xamarin.iOS: Spline Area Series


TKChartSplineAreaSeries series is a derivative of TKChartAreaSeries. It allows the area
between the curve and the corresponding axis to be colored in an arbitrary way. Below is a sample
snippet that demonstrates how to set up a spline series:

C#
var categories = new [] { "Greetings", "Perfecto", "NearBy", "Family Store", "Fresh &
Green" };
var values = new [] { 70, 75, 58, 59, 88 };
var pointsWithCategoriesAndValues = new List<TKChartDataPoint> ();
for (int i = 0; i < categories.Length; ++i) {
pointsWithCategoriesAndValues.Add (new TKChartDataPoint (new NSString (categories
[i]), new NSNumber (values [i])));
}
chart.AddSeries (new TKChartSplineAreaSeries (pointsWithCategoriesAndValues.ToArray
()));
 

2255
Telerik UI for Xamarin

Chart for Xamarin.iOS: Line Series


TKChartLineSeries plot their data points on Cartesian Area. Points are connected with straight
lines. Here is how to set up a few line series:

C#
var expensesData = new List<TKChartDataPoint> ();
var incomesData = new List<TKChartDataPoint> ();
var profitData = new List<TKChartDataPoint> ();

var categories = new [] { "Greetings", "Perfecto", "NearBy", "Family Store", "Fresh &
Green" };
var expensesValues = new [] { 60, 30, 50, 32, 31 };
var incomesValues = new [] { 65, 75, 58, 59, 88 };
var profitValues = new [] { 5, 45, 8, 27, 57 };

for (int i = 0; i < categories.Length; ++i) {


expensesData.Add (new TKChartDataPoint (new NSString (categories [i]), new
NSNumber (expensesValues [i])));
incomesData.Add (new TKChartDataPoint (new NSString (categories [i]), new NSNumber
(incomesValues [i])));
profitData.Add (new TKChartDataPoint (new NSString (categories [i]), new NSNumber
(profitValues [i])));
}

var seriesForExpenses = new TKChartLineSeries(expensesData.ToArray());


seriesForExpenses.Title = "Expenses";
chart.AddSeries(seriesForExpenses);

var seriesForIncomes = new TKChartLineSeries(incomesData.ToArray());


seriesForIncomes.Title = "Incomes";
chart.AddSeries(seriesForIncomes);

var seriesForProfit = new TKChartLineSeries(profitData.ToArray());


seriesForProfit.Title = "Profit";
chart.AddSeries(seriesForProfit);
chart.Legend.Hidden = false;
 

2256
Telerik UI for Xamarin

Configure input and selection of line series


If you would like to configure the distance between finger touch and line to perform selection, set
Selection property:

C#
series.Selection = TKChartSeriesSelection.Series;
 

If you would like to change the series' stroke, you should use the following code snippet:

C#
var seriesForProfit = new TKChartLineSeries (profitData.ToArray());
seriesForProfit.Style.Palette = new TKChartPalette ();
var paletteItem = new TKChartPaletteItem ();
paletteItem.Stroke = new TKStroke (UIColor.Green);
seriesForProfit.Style.Palette.AddPaletteItem (paletteItem);
chart.AddSeries (seriesForProfit);
 

2257
Telerik UI for Xamarin

Set null values visualization


In order to determines whether gaps should be displayed when there are nil values use
DisplayNilValuesAsGaps property:

C#
var seriesForProfit = new TKChartLineSeries (profitData.ToArray());
seriesForProfit.DisplayNilValuesAsGaps = true;
 

2258
Telerik UI for Xamarin

Chart for Xamarin.iOS: Pie Series


Unlike all other series, TKChartPieSeries do not require axes. They visualize each data point as
pie slices with arc size directly proportional to the magnitude of the raw data point's value.

Pie slices represent data in one direction contrasting with the other series which represent data in
two dimensions. Here is an example of how to create a pie chart with pie series populated with data:

C#
var pointsWithValueAndName = new List<TKChartDataPoint> ();
pointsWithValueAndName.Add (new TKChartDataPoint (new NSNumber (20), null, "Google"));
pointsWithValueAndName.Add(new TKChartDataPoint(new NSNumber(30), null, "Apple"));
pointsWithValueAndName.Add (new TKChartDataPoint (new NSNumber (10), null,
"Microsoft"));
pointsWithValueAndName.Add (new TKChartDataPoint (new NSNumber (5), null, "IBM"));
pointsWithValueAndName.Add (new TKChartDataPoint (new NSNumber (8), null, "Oracle"));

var series = new TKChartPieSeries (pointsWithValueAndName.ToArray());


series.Style.PointLabelStyle.TextHidden = false;

chart.AddSeries (series);
chart.Legend.Hidden = false;
chart.Legend.Style.Position = TKChartLegendPosition.Right;
 

Configure visual appearance of pie series


Pie series can be customized using the following properties:

The LabelDisplayMode property controls whether to show labels inside or outside the pie series.
The possible choices are:

 TKChartPieSeriesLabelDisplayModeInside - labels are displayed inside the pie.


 TKChartPieSeriesLabelDisplayModeOutside - labels are displayed outside the pie.

2259
Telerik UI for Xamarin

Other interesting options that can be used to customize pie labels are StringFormat and
Formatter properties. For example, you can use the Formatter property in order to show slice
values as text:

C#
series.LabelDisplayMode = TKChartPieSeriesLabelDisplayMode.Inside;

var numberFormatter = new NSNumberFormatter ();


numberFormatter.NumberStyle = NSNumberFormatterStyle.SpellOut;
series.Style.PointLabelStyle.Formatter = numberFormatter;
 

Or use StringFormat property to format slice values as percents:

C#
series.Style.PointLabelStyle.StringFormat = "%.0f %%";
 

The OuterRadius property can increase and decrease the diameter of the series. By default, it
occupies the whole plot area and is equal to 1. Setting the outerRadius to 0.9 will decrease the
radius of the series by 10 percent. Similarly, the value 1.1 will increase it. Leaving the property with
value 1 will make the donut fill the available space.

The ExpandRadius property is used when selecting a pie segment. It defines the extent to which
the selected pie segment is shifted. Again, this property is measured in percents. A value of 1.1
defines that the selected segment will expand by 10% of the pie radius.

The StartAngle and endAngle properties are used to define the pie range. The StartAngle sets
the angle in radians from which the drawing of the pie segments will begin. Its default value is 0. The
EndAngle determines whether the chart will appear as a full circle or a partial circle. Its default value
is Pi*2.

The following code sets the startAngle and endAngle properties to show a half circle:

C#

2260
Telerik UI for Xamarin

series.StartAngle = (float)(-Math.PI/4.0/2.0);
series.EndAngle = (float)(Math.PI/4.0/2.0);
series.RotationAngle = (float)Math.PI;
 

By default, the pie chart starts drawing its segments from 0 radians. You can customize this angle
and rotate the chart. This is done by setting the RotationAngle property.

The SelectionAngle property is used to rotate the chart when selecting a pie segment. It rotates
the chart so that the selected pie segment appears at the specified by the property angle.

In order to select the second pie segment, call the select method of TKChart:

C#
series.Selection = TKChartSeriesSelection.DataPoint;
chart.Select(new TKChartSelectionInfo(series, 1));
 

Further information about selection in chart is available in the Chart for Xamarin.iOS: Selection article.

2261
Telerik UI for Xamarin

Chart for Xamarin.iOS: Scatter Series


TKChartScatterSeries plots its data along two axes. Scatter series identify the position of each
point using two dimensional values - XValue and YValue for the horizontal and vertical axes
respectively, just like in the typical Cartesian coordinate system.

Here is how to create a TKChartScatterSeries and populate them manually:

C#
List<TKChartDataPoint> list = new List<TKChartDataPoint> ();
for (int j = 0; j < 20; j++) {

list.Add(new TKChartDataPoint (new NSNumber (r.Next() % 1450), new NSNumber


(r.Next () % 150)));
}

TKChartScatterSeries series = new TKChartScatterSeries (list.ToArray());


 

Customizing the visual appearance


In addition, you can change a point background color by using the following lines of code:

C#
var series = new TKChartScatterSeries (scatterPoints.ToArray());

2262
Telerik UI for Xamarin

var paletteItem = new TKChartPaletteItem();


paletteItem.Fill = new TKSolidFill (UIColor.Red);
series.Style.Palette = new TKChartPalette();
series.Style.Palette.AddPaletteItem (paletteItem);
chart.AddSeries (series);
 

Configure input and selection of line series


Here is how to configure the distance between finger touch and line to perform selection:

C#
var series = new TKChartScatterSeries (scatterPoints.ToArray());
series.Selection = TKChartSeriesSelection.DataPoint;
series.MarginForHitDetection = 30.0f;
chart.AddSeries (series);
 

2263
Telerik UI for Xamarin

Chart for Xamarin.iOS: Series Points Customization


TKChartSeries can draw a point in particular shape. You can customize the appearance and
shape of this point by accessing and altering the styling properties and palette items for
ShapePallete style property.

Note that the approach above is applicable to any series except TKChartPieSeries,
TKChartBarSeries and TKChartColumnSeries. If you want to change the shape of each point,
you should use the following code snippet:

C#
series.Style.PointShape = new TKPredefinedShape (TKShapeType.Circle, new SizeF (10,
10));
 

You can specify many predefined shapes by using the TKShapeType enum. The available options
are listed below:

 TKShapeType.None - No shape
 TKShapeType.Square - Square shape
 TKShapeType.Circle - Circle shape
 TKShapeType.TriangleUp - Triangle pointing up
 TKShapeType.TriangleDown - Triangle pointing down
 TKShapeType.Diamond - Diamond shape
 TKShapeType.Rhombus - Rhombus shape
 TKShapeType.Pentagon - Pentagon shape

2264
Telerik UI for Xamarin

 TKShapeType.Hexagon - Hexagon shape


 TKShapeType.Star - Star shape
 TKShapeType.Heart - Heart shape

In addition, you can change a point background color by using the following lines of code:

C#
var paletteItem = new TKChartPaletteItem ();
paletteItem.Fill = new TKSolidFill (UIColor.Red);
var palette = new TKChartPalette ();
palette.AddPaletteItem (paletteItem);
series.Style.ShapePalette = palette;
 

2265
Telerik UI for Xamarin

Chart for Xamarin.iOS: RangeBar Series


TKChartRangeBarSeries are used to visualize data points as horizontal bars where the width of
each bar denotes the difference between data point's low and high value. The code snippet below
demonstrates how to create range bar series.

Configure clustering of range bar series


If you want to cluster multiple range bar series side by side, they should use a shared y-axis:

C#
var lowValues = new NSNumber[] {
new NSNumber (33), new NSNumber (29),
new NSNumber (55), new NSNumber (21),
new NSNumber (10), new NSNumber (39),
new NSNumber (40), new NSNumber (11)
};

var highValues = new NSNumber[] {


new NSNumber (47), new NSNumber (61),
new NSNumber (64), new NSNumber (40),
new NSNumber (33), new NSNumber (90),
new NSNumber (87), new NSNumber (69)
};

var lowValues2 = new NSNumber[] {


new NSNumber (31), new NSNumber (32),
new NSNumber (57), new NSNumber (18),
new NSNumber (12), new NSNumber (31),
new NSNumber (45), new NSNumber (14)
};

var highValues2 = new NSNumber[] {


new NSNumber (43), new NSNumber (66),
new NSNumber (61), new NSNumber (49),
new NSNumber (31), new NSNumber (80),
new NSNumber (82), new NSNumber (78)
};

List<TKChartRangeDataPoint> list = new List<TKChartRangeDataPoint> ();


List<TKChartRangeDataPoint> list2 = new List<TKChartRangeDataPoint> ();
for (int i = 0; i < 8; i++) {
list.Add(TKChartRangeDataPoint.RangeBarDataPoint(new NSNumber(i), lowValues[i],
highValues[i]));
list2.Add(TKChartRangeDataPoint.RangeBarDataPoint(new NSNumber(i), lowValues2[i],
highValues2[i]));
}

TKChartRangeBarSeries series = new TKChartRangeBarSeries (list.ToArray());

2266
Telerik UI for Xamarin

TKChartRangeBarSeries series2 = new TKChartRangeBarSeries (list2.ToArray());


chart.AddSeries(series);
chart.AddSeries(series2);
 

Configure visual appearance


If you want to customize the appearance of a range bar series, you should change its Style
properties.

You can change the fill and stroke in the following manner:

C#
series.Style.Palette = new TKChartPalette();
var paletteItem = new TKChartPaletteItem ();
paletteItem.Fill = new TKSolidFill (UIColor.Red);
paletteItem.Stroke = new TKStroke (UIColor.Black);
series.Style.Palette.AddPaletteItem (paletteItem);
chart.AddSeries(series);
 

2267
Telerik UI for Xamarin

You can change the gap between the bars with the following code snippet:

C#
series.GapLength = 0.5f;
 

2268
Telerik UI for Xamarin

If you need to limit the height of the bars you can set the series MaxBarHeight and MinBarHeight
properties. These properties allow you to have required minimum and possible maximum height for
your series.

C#
series.MinBarHeight = 20;
series.MaxBarHeight = 50;
 

2269
Telerik UI for Xamarin

Chart for Xamarin.iOS: Range Column Series


TKChartRangeColumnSeries are used to visualize data points as column blocks where the height
of each column denotes the difference between data point's low and high value.

Configure clustering of range column series


If you want to cluster multiple range column series side by side, they should use a shared x-axis:

C#
var lowValues = new NSNumber[] {
new NSNumber (33), new NSNumber (29),
new NSNumber (55), new NSNumber (21),
new NSNumber (10), new NSNumber (39),
new NSNumber (40), new NSNumber (11)
};

var highValues = new NSNumber[] {


new NSNumber (47), new NSNumber (61),
new NSNumber (64), new NSNumber (40),
new NSNumber (33), new NSNumber (90),
new NSNumber (87), new NSNumber (69)
};

var lowValues2 = new NSNumber[] {


new NSNumber (31), new NSNumber (32),
new NSNumber (57), new NSNumber (18),
new NSNumber (12), new NSNumber (31),
new NSNumber (45), new NSNumber (14)
};

var highValues2 = new NSNumber[] {


new NSNumber (43), new NSNumber (66),
new NSNumber (61), new NSNumber (49),
new NSNumber (31), new NSNumber (80),
new NSNumber (82), new NSNumber (78)
};

List<TKChartRangeDataPoint> list = new List<TKChartRangeDataPoint> ();


List<TKChartRangeDataPoint> list2 = new List<TKChartRangeDataPoint> ();
for (int i = 0; i < 8; i++) {
list.Add(TKChartRangeDataPoint.RangeColumnDataPoint(new NSNumber(i), lowValues[i],
highValues[i]));
list2.Add(TKChartRangeDataPoint.RangeColumnDataPoint(new NSNumber(i),
lowValues2[i], highValues2[i]));
}

TKChartRangeColumnSeries series = new TKChartRangeColumnSeries (list.ToArray());


TKChartRangeColumnSeries series2 = new TKChartRangeColumnSeries (list2.ToArray());
chart.AddSeries(series);

2270
Telerik UI for Xamarin

chart.AddSeries(series2);
 

Configure visual appearance


If you want to customize the appearance of a range column series, you should change its Style
properties.

You can change the fill and stroke in the following manner:

C#
series.Style.Palette = new TKChartPalette();
var paletteItem = new TKChartPaletteItem ();
paletteItem.Fill = new TKSolidFill (UIColor.Red);
paletteItem.Stroke = new TKStroke (UIColor.Black);
series.Style.Palette.AddPaletteItem (paletteItem);
 

2271
Telerik UI for Xamarin

You can change the gap between the columns with the following code snippet:

C#
series.GapLength = 0.5f;
 

2272
Telerik UI for Xamarin

If you need to limit the width of the columns you can set the series MaxColumnWidth and
MinColumnWidth properties. These properties allow you to have required minimum and possible
maximum width for your series.

C#
series.MinColumnWidth = 20;
series.MaxColumnWidth = 50;
 

2273
Telerik UI for Xamarin

DataForm for Xamarin.iOS: Overview


RadDataForm for Xamarin.iOS is a customizable component that allows you to easily create a form
for collecting or editing business object data. It is ideal for settings or registration/login pages.
TKDataForm supports different commit modes allowing you to commit property values one by one or
commit the whole form at once. You can also determine at what moment the properties should be
validated choosing between three validation modes. The control lets you use rich set of editors out of
the box.

Editors

 TextField
 Switch
 Stepper
 Slider
 Segmented control
 DatePicker
 PickerView
 Options

For more information on this go to Editors topic.

Commit and validation modes

2274
Telerik UI for Xamarin

 Immediate
 On lost focus
 Delayed

The commit and validation modes can be combined allowing you to perform validation and commit at
different moment.

2275
Telerik UI for Xamarin

DataForm for Xamarin.iOS: Getting Started


This quick start tutorial demonstrates how you can add TKDataForm to your Xamarin.iOS
application.

Setting up TKDataForm
There are two approaches you can use - either add a TKDataForm instance to an existing
UIViewController or utilize our predefined TKDataFormViewController.

Either way you choose, first you will need to reference Telerik.Xamarin.iOS.dll into the Xamarin.iOS
project.

Adding TKDataForm instance


Open your UIViewController file and add a reference to the TelerikUI namespace:

C#
using TelerikUI;
 

You should create a business object that will be displayed and edited by TKDataForm. Let's create a
class called PersonalInfo:

C#
public class PersonalInfo : NSObject
{
[Export("Server")]
public string Server { get; set;}

[Export("Details")]
public string Details { get; set;}

[Export("Account")]
public string Account { get; set;}

[Export("Secure")]
public bool Secure { get; set;}

[Export("Password")]
public string Password { get; set;}

[Export("EncryptionLevel")]
public int EncryptionLevel { get; set;}

[Export("SendAllTraffic")]
public bool SendAllTraffic { get; set;}

2276
Telerik UI for Xamarin

[Export("InfoProtocol")]
public int InfoProtocol{ get; set;}

public PersonalInfo ()
{
this.InfoProtocol = 0;
this.Details = "";
this.Server = "";
this.Secure = false;
this.Password = "";
this.EncryptionLevel = 0;
this.Account = "";
this.SendAllTraffic = true;
}
}
 

The TKDataForm object should be created in ViewDidLoad method of the UIViewController:

C#
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
// Perform any additional setup after loading the view, typically from a nib.
var dataForm = new TKDataForm(this.View.Bounds)
{
WeakDataSource = new TKDataFormEntityDataSource(new PersonalInfo())
};
this.View.AddSubview(dataForm);
}
 

And here is the result:

2277
Telerik UI for Xamarin

Utilizing TKDataFormViewController
The other option is to utilize the TKDataFormViewController - it inherits from UIViewController
and contains a predefined TKDataForm instance.

For the example below the same PersonalInfo class is used as a source of the DataForm.

C#
public partial class MyViewController : TKDataFormViewController
{
public MyViewController(IntPtr handle) : base(handle)
{
}

public override void ViewDidLoad()


{
base.ViewDidLoad();

// Perform any additional setup after loading the view, typically from a nib.
this.DataForm.WeakDataSource = new TKDataFormEntityDataSource(new
PersonalInfo());
}
}
 

Customize the editors


TKDataForm chooses a default editor based on each property's type. You have the option to change
the default editors by utilizing the TKDataFormEntityDataSourceHelper class and set it as the
DataSource of the DataForm. TKDataFormEntityDataSourceHelper gives access to each

2278
Telerik UI for Xamarin

dataform entity for each property of the source object, so you can modify its editor, provide
predefined values, and more.

In addition, if you would like to customize the editors, you would need to adopt
TKDataFormDelegate and override its UpdateEditor method. Then you just need to set thus
created delegate to the Delegate property of the TKDataForm instance.

Check below an example of TKDataFormEntityDataSourceHelper and TKDataFormDelegate:

C#
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
// Perform any additional setup after loading the view, typically from a nib.

var dataSource = new TKDataFormEntityDataSourceHelper(new PersonalInfo());

dataSource["Password"].EditorClass = new Class(typeof(TKDataFormPasswordEditor));


dataSource["InfoProtocol"].ValuesProvider = NSArray.FromStrings(new string[] {
"L2TP", "PPTP", "IPSec" });
dataSource["EncryptionLevel"].ValuesProvider = NSArray.FromStrings(new string[] {
"FIPS Compliant", "High", "Client Compatible", "Low" });

dataSource.AddGroup(" ", new string[] { "InfoProtocol" });


dataSource.AddGroup(" ", new string[] { "Details", "Server", "Account", "Secure",
"Password", "EncryptionLevel", "SendAllTraffic" });

var dataForm = new TKDataForm(this.View.Bounds)


{
BackgroundColor = new UIColor(0.937f, 0.937f, 0.960f, 1.0f),
GroupSpacing = 20,
Delegate = new MydDataFormDelegate(),
WeakDataSource = dataSource.NativeObject
};
this.View.AddSubview(dataForm);
}
 

where MydDataFormDelegate is defined as below:

C#
class MydDataFormDelegate : TKDataFormDelegate
{
public override void UpdateEditor(TKDataForm dataForm, TKDataFormEditor editor,
TKEntityProperty property)
{
TKGridLayoutCellDefinition feedbackDef =
editor.GridLayout.DefinitionForView(editor.FeedbackLabel);
editor.GridLayout.SetHeight(0, feedbackDef.Row.Int32Value);

if (property.Name == "InfoProtocol")
{
editor.Style.TextLabelDisplayMode =

2279
Telerik UI for Xamarin

TKDataFormEditorTextLabelDisplayMode.Hidden;
TKGridLayoutCellDefinition textLabelDef =
editor.GridLayout.DefinitionForView(editor.TextLabel);
editor.GridLayout.SetWidth(0, textLabelDef.Column.Int32Value);
}

if (editor.IsKindOfClass(new Class(typeof(TKDataFormTextFieldEditor))) &&


!(property.Name.Equals("Password")))
{
property.HintText = "Required";
}
}
}
 

The images below show the result after applying the snippet:

2280
Telerik UI for Xamarin

DataForm for Xamarin.iOS: Validation

Validation Modes
TKDataForm supports three validation modes:

 Immediate - validation will be performed every time the property value is changed.
 OnLostFocus - validation will be performed when the editor focus is changed to another
editor.
 Delayed - validation will be performed explicitly whenCommit method of TKDataForm is
called. This option is used only with commit mode TKDataFormCommitModeDelayed

Here is an example how to set a validation mode to TKDataForm:

C#
this.DataForm.ValidationMode = TKDataFormValidationMode.Immediate;
 

Validating TKDataFormEntityProperty

2281
Telerik UI for Xamarin

There are 2 options to validate a property - using TKDataFormDelegate or using validators that
adopt TKDataFormValidator protocol.

Adopting TKDataFormValidator
TKDataFormValidator protocol has 2 required methods - ValidateProperty and
ValidationMessage. ValidateProperty method is used to perform the actual validation and
return a boolean value indicating if the property value is valid. ValidationMessage method should
return a feedback message that will be displayed to the user of your application. After you implement
a validator you should set the Validators property of the TKDataFormEntityProperty that will
be validated.

In addition, you can take advantage of a few predefined validators, for example
TKDataFormEmailValidator, TKDataFormMaximumLengthValidator,
TKDataFormNonEmptyValidator, TKDataFormPhoneValidator and
TKDataFormRangeValidator.

C#
TKDataFormMinimumLengthValidator passwordValidator = new
TKDataFormMinimumLengthValidator (6);
passwordValidator.ErrorMessage = "Password must be at least 6 characters!";
password.Validators = new NSObject[] { passwordValidator };
 

Validating through TKDataFormDelegate


To validate a property through TKDataFormDelegate you should implement its
ValidateProperty that returns a boolean value indicating if the property value is valid:

C#
public override bool ValidateProperty (TKDataForm dataForm, TKEntityProperty property,
TKDataFormEditor editor)
{
}
 

Check for validation errors


When you want to simply check if there are any validation errors in the TKDataForm you can use its
HasValidationErrors method.

C#
var hasValidationErrors = dataForm.HasValidationErrors();
 

2282
Telerik UI for Xamarin

DataForm for Xamarin.iOS: Collapsible Groups


TKDataForm supports expand/collapse behavior for its property groups when the group's header is
tapped. To allow expanding and collapsing groups, you should implement UpdateGroupView of
TKDataFormDelegate and set the Collapsible property of the group view. In addition, you can
customize the group header through the TitleView.Style property of the GroupView.

Check a sample implementation of UpdateGroupView below:

C#
class MyDataFormDelegate : TKDataFormDelegate
{
public override void UpdateGroupView (TKDataForm dataForm,
TKEntityPropertyGroupView groupView, uint groupIndex)
{
groupView.Collapsible = true;
groupView.TitleView.Style.SeparatorColor = new TKSolidFill (new UIColor
(0.784f, 0.780f, 0.8f, 1.0f));
}
}
 

Just need to set the MyDataFormDelegate to TKDataForm instance:


C#
dataForm.Delegate = new MyDataFormDelegate();
 

2283
Telerik UI for Xamarin

2284
Telerik UI for Xamarin

DataForm for Xamarin.iOS: Group Layouts

TKEntityPropertyGroupView allows you to arrange the editors in the group using different
layouts that confirm to TKLayout protocol through its Layout property. By default the group view
uses TKStackLayout, but you could easily change it to let's say TKGridLayout. The code snippet
below shows how to change the layout of a group view inside the UpdateGroupView method of the
DataForm Delegate:

C#
class MyDataFormDelegate : TKDataFormDelegate
{
public override void UpdateGroupView (TKDataForm dataForm,
TKEntityPropertyGroupView groupView, uint groupIndex)
{
groupView.Collapsible = true;
if (groupIndex == 0) {
TKGridLayout grid = new TKGridLayout ();
groupView.EditorsContainer.Layout = grid;
int row = 0;
int col = 0;
foreach (UIView editor in groupView.EditorsContainer.Items) {
TKGridLayoutCellDefinition editorDefinition = grid.DefinitionForView (editor);
editorDefinition.Row = new NSNumber (row);
editorDefinition.Column = new NSNumber (col);
col++;
if (col == 2) {
row++;
col = 0;
}
}
}
}
}
 

2285
Telerik UI for Xamarin

RadDataForm for Xamarin.iOS: Built-in Editors


RadDataForm for Xamarin.iOS contains many built-in property editors that are either automatically
resolved depending on the property's type or can be set by the TKDataFormEntityDataSourceHelper
EditorClass of the TKDataForm. RadDataForm currently ships with the following built-in editors:

 TKDataFormAutocompleteInlinEditor
 TKDataFormTextFieldEditor
 TKDataFormMultilineTextEditor
 TKDataFormEmailEditor
 TKDataFormPasswordEditor
 TKDataFormNamePhoneEditor
 TKDataFormPhoneEditor
 TKDataFormDecimalEditor
 TKDataFormNumberEditor
 TKDataFormSwitchEditor
 TKDataFormStepperEditor
 TKDataFormSliderEditor
 TKDataFormSegmentedEditor
 TKDataFormInlineEditor
 TKDataFormDatePickerEditor
 TKDataFormTimePickerEditor
 TKDataFormOptionsEditor
 TKDataFormPickerViewEditor
 TKDataFormCustomEditor

For more details on how you can define and customize the editors check the Getting Started topic.
 

Using the TKDataFormAutoCompleteInlineEditor


TKDataFormAutoCompleteInlineEditor is a bit more advanced editor which provides an out of the
box quick search functionality. This editor uses the TKAutoCompleteTextView standalone element
and all its functionality like DisplayMode is available to the RadDataForm editor.

Setting the suggestions 'Source'

Because of the nature of the RadAutoCompleteTextView the editor which exposes its functionality
requires some additional data to be passed to it which will be used as the 'suggestions' when a user
starts typing in its textbox. Suggestions can be set through the ValuesProvider property of the
TKDataFormEntityDataSourceHelper and setting it to array of strings.

The example below uses the setup from the Getting Started topic.

C#
var dataSource = new TKDataFormEntityDataSourceHelper(new PersonalInfo());

dataSource["Account"].EditorClass = new

2286
Telerik UI for Xamarin

Class(typeof(TKDataFormAutoCompleteInlineEditor));
dataSource["Account"].ValuesProvider = NSArray.FromStrings(new string[] { "CMOK",
"Drako", "Falkor", "Longma", "Pyrene" });
 

Setting the DisplayMode

If you are familiar with the TKAutoCompleteTextView element you know that is supports out of the
box two different selected items display modes:

 Token - the selected item from the 'suggestion box' is displayed as a box with a remove 'X'
button
 Plain - the selected item's text is appended and autocompleted after an item from the
'suggestion box' is selected

When using the DataFormRadAutoCompleteInlineEditor you too have the option to change the
editor's DisplayMode by simply setting the AutoCompleteDisplayMode of the
AutoCompleteTextView control inside the UpdateEditor method of the DataForm Delegate:

C#
class MydDataFormDelegate : TKDataFormDelegate
{
public override void UpdateEditor(TKDataForm dataForm, TKDataFormEditor editor,
TKEntityProperty property)
{
if(property.Name == "Account")
{
(editor as TKDataFormAutoCompleteInlineEditor).AutoCompleteView.DisplayMode =
TKAutoCompleteDisplayMode.Tokens;
}
}
}
 

Here is the result:

2287
Telerik UI for Xamarin

2288
Telerik UI for Xamarin

DataSource for Xamarin.iOS: Overview


DataSource for Xamarin.iOS is a non-visual component that consumes data from various sources. It
supports data shaping operations like sorting, filtering and grouping. It adopts the most used data
enabled UI controls in iOS: UITableView and UICollectionView to automate the presentation of its
data. TLKDataSource works perfectly with TKListView, TKChart and TKCalendar too.

Consuming data

TLKDataSource can consume various data types: simple arrays, arrays with business objects and
dictionaries coming from various sources. Its easy to use API allows loading data from files and web
services.

Data shaping operations

TLKDataSource supports the following data shaping operations:

 sorting
 filtering
 grouping

For your convenience TLKDataSource provides three different APIs for data shaping operations.

Presenting data

TLKDataSource can present data by using the following UI controls:

2289
Telerik UI for Xamarin

 TKListView
 TKChart
 TKCalendar
 UITableView
 UICollectionView

You can use TLKDataSource to present the same data in different UI controls at the same time. In
this scenario TLKDataSource syncs the current item in the presented controls.

2290
Telerik UI for Xamarin

DataSource for Xamarin.iOS: Getting Started


This quick start tutorial demonstrates how to create a simple Xamarin.iOS application with
TLKDataSource.

Setting up TLKDataSource
Now that our project is created and the Telerik.Xamarin.iOS assembly is added, you can start
referencing and using the TelerikUI types.

Open your UIViewController file and add a reference to the chart header file:

C#
using TelerikUI;
 

The simplest way to use TLKDataSource is to initialize it with an array. The following code creates a
new instance of TLKDataSource and loads it with a numeric array:

C#
dataSource = new TLKDataSource (ArrayWithObjects(new object [] { 10, 5, 12, 7, 44 }),
null);
 

TLKDataSource supports a full range of data shaping operations including filtering, sorting and
grouping. In the code snippet below, we first filter the numbers smaller than 5, then sort the rest,

2291
Telerik UI for Xamarin

group the sorted values depending on whether they are even or odd, multiply every value by 10 and
finally find the max value:

C#
// filter all values less or equal to 5
dataSource.Filter ((NSObject item) => {
return ((NSNumber)item).NIntValue > 5;
});

// sort ascending
dataSource.Sort ((NSObject obj1, NSObject obj2) => {
nint a = ((NSNumber)obj1).NIntValue;
nint b = ((NSNumber)obj2).NIntValue;
if (a<b) return NSComparisonResult.Descending;
else if (a>b) return NSComparisonResult.Ascending;
return NSComparisonResult.Same;
});

// group odd/even values


dataSource.Group ((NSObject item) => {
return NSObject.FromObject(((NSNumber)item).NIntValue % 2 == 0);
});

// multiply every value * 10


dataSource.Map ((NSObject item) => {
return NSObject.FromObject(((NSNumber)item).NIntValue * 10);
});

// find the max value


NSObject maxValue = dataSource.Reduce (NSObject.FromObject(0), (NSObject item,
NSObject value) => {
if (((NSNumber)item).NIntValue > ((NSNumber)value).NIntValue)
return item;
return value;
});
 

TLKDataSource is an independent component and you can use it without connecting it to a UI


control. To show the result just iterate the items:

C#
// output everything to the console
dataSource.Enumerate ((NSObject item) => {
if (item.IsKindOfClass(new ObjCRuntime.Class(typeof(TKDataSourceGroup)))) {
TKDataSourceGroup group = (TKDataSourceGroup)item;
Console.WriteLine("group: {0}", group.Key);
}
else {
Console.WriteLine("{0}", ((NSNumber)item).NIntValue);
}
});

2292
Telerik UI for Xamarin

Or, you can create a UITableView and set its DataSource property:

C#
// bind with a table view
var tableView = new UITableView (this.View.Bounds);
tableView.DataSource = dataSource;
this.View.AddSubview (tableView);
 

Note that the DataSource property of UITableView is weak and you should assign the
DataSource instance to a class variable in order to persist its value!

Here is the full code of this example:

2293
Telerik UI for Xamarin

C#
[Register("DataSourceGettingStarted")]
public class DataSourceGettingStarted: XamarinExampleViewController
{
TLKDataSource dataSource;

public override void ViewDidLoad ()


{
base.ViewDidLoad ();

dataSource = new TLKDataSource (ArrayWithObjects(new object [] { 10, 5, 12, 7,


44 }), null);

// filter all values less or equal to 5


dataSource.Filter ((NSObject item) => {
return ((NSNumber)item).NIntValue > 5;
});

// sort ascending
dataSource.Sort ((NSObject obj1, NSObject obj2) => {
nint a = ((NSNumber)obj1).NIntValue;
nint b = ((NSNumber)obj2).NIntValue;
if (a<b) return NSComparisonResult.Descending;
else if (a>b) return NSComparisonResult.Ascending;
return NSComparisonResult.Same;
});

// group odd/even values


dataSource.Group ((NSObject item) => {
return NSObject.FromObject(((NSNumber)item).NIntValue % 2 == 0);
});

// multiply every value * 10


dataSource.Map ((NSObject item) => {
return NSObject.FromObject(((NSNumber)item).NIntValue * 10);
});

// find the max value


NSObject maxValue = dataSource.Reduce (NSObject.FromObject(0), (NSObject item,
NSObject value) => {
if (((NSNumber)item).NIntValue > ((NSNumber)value).NIntValue)
return item;
return value;
});

Console.WriteLine ("the max value is: {0}", ((NSNumber)maxValue).NIntValue);

// output everything to the console


dataSource.Enumerate ((NSObject item) => {
if (item.IsKindOfClass(new ObjCRuntime.Class(typeof(TKDataSourceGroup)))) {
TKDataSourceGroup group = (TKDataSourceGroup)item;
Console.WriteLine("group: {0}", group.Key);
}
else {

2294
Telerik UI for Xamarin

Console.WriteLine("{0}", ((NSNumber)item).NIntValue);
}
});

// bind with a table view


var tableView = new UITableView (this.View.Bounds);
tableView.DataSource = dataSource;
this.View.AddSubview (tableView);

NSObject[] ArrayWithObjects(object[] objects)


{
List<NSObject> array = new List<NSObject>();
for (int i = 0; i<objects.Length; i++) {
array.Add (NSObject.FromObject (objects [i]));
}
return array.ToArray();
}
}
 

You can easily switch the UI control used to present data coming from TLKDataSource. It supports
the most common data enabled UI controls, so you can use it the same way with
UICollectionView, TKChart, TKListView, or TKCalendar. The following article demonstrates
how to initialize and customize the UI controls supported by TLKDataSource:Binding with UI controls

TLKDataSource supports also different data inputs. This article demonstrates how to load data
coming from files or a web service:Loading with data

Data shaping operations are described in detail in this article:Data shaping operations

2295
Telerik UI for Xamarin

DataSource for Xamarin.iOS: Populating with Data


TLKDataSource can consume data coming from various sources.

The simplest way to load data in TLKDataSource is to use an array with numbers or strings:

C#
dataSource = new TLKDataSource (ArrayWithObjects(new object [] { 10, 5, 12, 7, 44 }),
null);
 

It also supports arrays of business objects. In this scenario you can use DisplayKey and ValueKey
properties to define how to present the data:

C#
var array = new NSMutableArray ();

2296
Telerik UI for Xamarin

array.Add (new DSItem () { Name = "John", Value = 22.0f, Group = "one" });
array.Add (new DSItem () { Name = "Peter", Value = 15.0f, Group = "one" });
array.Add (new DSItem () { Name = "Abby", Value = 47.0f, Group = "one" });
array.Add (new DSItem () { Name = "Robert", Value = 45.0f, Group = "two" });
array.Add (new DSItem () { Name = "Alan", Value = 17.0f, Group = "two" });
array.Add (new DSItem () { Name = "Saly", Value = 33.0f, Group = "two" });

dataSource.DisplayKey = "Name";
dataSource.ValueKey = "Value";
dataSource.ItemSource = array;
 

If a greater precision is necessary, you can implement the FormatText block to define how the data
will be presented:

C#
dataSource.FormatText ((NSObject item, TKDataSourceGroup group) => {
DSItem dsItem = (DSItem)item;
return new NSString(string.Format("{0} has {1} points", dsItem.Name,
dsItem.Value));
});
 

When using NSDictionary as a data provider for TLKDataSource, its Items property contains the
keys collection of the dictionary and the ItemSource property contains the dictionary itself. The
following code manipulates the dictionary by applying sorting and filtering methods and then
presents the data:

C#
NSMutableDictionary dict = new NSMutableDictionary();
dict.Add (new NSString ("John"), NSObject.FromObject (50));
dict.Add (new NSString ("Abby"), NSObject.FromObject (33));
dict.Add (new NSString ("Smith"), NSObject.FromObject (42));
dict.Add (new NSString ("Peter"), NSObject.FromObject (28));
dict.Add (new NSString ("Paula"), NSObject.FromObject (25));

TLKDataSource dataSource = new TLKDataSource ();


dataSource.ItemSource = dict;
dataSource.SortWithKey ("", true);
dataSource.Filter ((NSObject item) => {
return ((NSNumber)dict.ObjectForKey(item)).Int32Value > 30;
});
 

TLKDataSource is handy when loading data from resources. With a simple method call it loads a
JSON formatted file, parses its data and is ready to present or shape the data:

C#
this.Photos = new TLKDataSource ("PhotosWithNames", "json", "photos");
 

2297
Telerik UI for Xamarin

It can load also data coming from a web service. The following code downloads a JSON formatted
data from a web service, groups its items and presents the result in TKChart:

C#
var chart = new TKChart (this.View.Bounds);
chart.AutoresizingMask = UIViewAutoresizing.FlexibleWidth |
UIViewAutoresizing.FlexibleHeight;
this.View.Add (chart);

string url =
"http://www.telerik.com/docs/default-source/ui-for-ios/weather.json?sfvrsn=2";
dataSource.LoadDataFromURL (url, TKDataSourceDataFormat.JSON, "dayList", (NSError err)
=> {
if (err != null) {
Console.WriteLine("Can't connect with the server!");
return;
}

dataSource.Settings.Chart.CreateSeries((TKDataSourceGroup group) => {


TKChartSeries series = null;
if (group.ValueKey == "clouds") {
series = new TKChartColumnSeries();
series.YAxis = new TKChartNumericAxis(NSObject.FromObject(0),
NSObject.FromObject(100));
series.YAxis.Title = "clouds";
series.YAxis.Style.TitleStyle.RotationAngle = (float)Math.PI/2.0f;
}
else {
series = new TKChartLineSeries();
series.YAxis = new TKChartNumericAxis(NSObject.FromObject(-10),
NSObject.FromObject(30));
if (group.ValueKey == "temp.min") {
series.YAxis.Position = TKChartAxisPosition.Right;
series.YAxis.Title = "temperature";
series.YAxis.Style.TitleStyle.RotationAngle = (float)Math.PI/2.0f;
chart.AddAxis(series.YAxis);
}
}
return series;
});

dataSource.Map((NSObject item) => {


double interval = ((NSNumber)item.ValueForKey(new
NSString("dateTime"))).DoubleValue;
NSDate date = NSDate.FromTimeIntervalSince1970(interval);
item.SetValueForKey(date, new NSString("dateTime"));
return item;
});

NSObject[] items = this.dataSource.Items;


NSMutableArray newItems = new NSMutableArray();
newItems.Add(new TKDataSourceGroup(items, "clouds", "dateTime"));
newItems.Add(new TKDataSourceGroup(items, "temp.min", "dateTime"));
newItems.Add(new TKDataSourceGroup(items, "temp.max", "dateTime"));

2298
Telerik UI for Xamarin

dataSource.ItemSource = newItems;

chart.DataSource = dataSource;

var formatter = new NSDateFormatter();


formatter.DateFormat = "dd";
TKChartDateTimeAxis xAxis = (TKChartDateTimeAxis)chart.XAxis;
xAxis.MajorTickInterval = 1;
xAxis.PlotMode = TKChartAxisPlotMode.BetweenTicks;
xAxis.LabelFormatter = formatter;
xAxis.Title = "date";
xAxis.MinorTickIntervalUnit = TKChartDateTimeAxisIntervalUnit.Days;
});
 

2299
Telerik UI for Xamarin

DataSource for Xamarin.iOS: Data Shaping Operations


TLKDataSource supports a full range of data shaping operations with APIs specific for your
scenario.

The simplest way to shape your data is to use the block API. Just specify the block function
responsible for the data operation:

C#
// filter all values less or equal to 5
dataSource.Filter ((NSObject item) => {
return ((NSNumber)item).NIntValue > 5;
});

// sort ascending
dataSource.Sort ((NSObject obj1, NSObject obj2) => {
nint a = ((NSNumber)obj1).NIntValue;
nint b = ((NSNumber)obj2).NIntValue;
if (a<b) return NSComparisonResult.Descending;
else if (a>b) return NSComparisonResult.Ascending;
return NSComparisonResult.Same;
});

// group odd/even values


dataSource.Group ((NSObject item) => {
return NSObject.FromObject(((NSNumber)item).NIntValue % 2 == 0);
});

// multiply every value * 10


dataSource.Map ((NSObject item) => {
return NSObject.FromObject(((NSNumber)item).NIntValue * 10);
});

// find the max value


NSObject maxValue = dataSource.Reduce (NSObject.FromObject(0), (NSObject item,
NSObject value) => {
if (((NSNumber)item).NIntValue > ((NSNumber)value).NIntValue)
return item;
return value;
});
 

TLKDataSource supports also NSPredicate style queries. The following methods use queries and
property names instead of block methods:

C#
public class DataSourceDocsQueries : XamarinExampleViewController
{
TLKDataSource dataSource;

2300
Telerik UI for Xamarin

public DataSourceDocsQueries ()
{
}

public override void ViewDidLoad ()


{
base.ViewDidLoad ();

NSMutableArray items = new NSMutableArray();


items.Add (new DSItem () { Name = "John", Value = 50, Group = "A" });
items.Add (new DSItem () { Name = "Abby", Value = 33, Group = "A" });
items.Add (new DSItem () { Name = "Smith", Value = 42, Group = "B" });
items.Add (new DSItem () { Name = "Peter", Value = 28, Group = "B" });
items.Add (new DSItem () { Name = "Paula", Value = 25, Group = "B" });

this.dataSource = new TLKDataSource();


this.dataSource.ItemSource = items;
this.dataSource.DisplayKey = "Name";

this.dataSource.FilterWithQuery ("Value > 30");


this.dataSource.SortWithKey ("Value", true);
this.dataSource.GroupWithKey ("Group");

UITableView tableView = new UITableView (this.View.Bounds);


tableView.DataSource = this.dataSource;
this.View.AddSubview (tableView);
}
}
 

All the methods mentioned above execute immediately when called. They operate directly on the
current Items view in TLKDataSource. TLKDataSource extends its API by supporting three
collections with sorting, filtering and group descriptors.

The descriptors API supports both code blocks and queries with property names. This allows for
specifying the data shaping operations before loading the data. In this scenario all descriptors are
applied after the data is actually loaded in TLKDataSource. This data-loading operation can happen
on setting the itemSource property. The following code demonstrates this API:

C#
public class DataSourceDescriptorsAPI: XamarinExampleViewController
{
TLKDataSource dataSource;

public override void ViewDidLoad ()


{
base.ViewDidLoad ();

dataSource = new TLKDataSource ();

dataSource.AddFilterDescriptor (new TKDataSourceFilterDescriptor ("NOT (Name


like 'John')"));

2301
Telerik UI for Xamarin

dataSource.AddSortDescriptor (new TKDataSourceSortDescriptor ("Name", true));


dataSource.AddGroupDescriptor (new TKDataSourceGroupDescriptor ("Group"));

var array = new NSMutableArray ();


array.Add (new DSItem () { Name = "John", Value = 22.0f, Group = "one" });
array.Add (new DSItem () { Name = "Peter", Value = 15.0f, Group = "one" });
array.Add (new DSItem () { Name = "Abby", Value = 47.0f, Group = "one" });
array.Add (new DSItem () { Name = "Robert", Value = 45.0f, Group = "two" });
array.Add (new DSItem () { Name = "Alan", Value = 17.0f, Group = "two" });
array.Add (new DSItem () { Name = "Saly", Value = 33.0f, Group = "two" });

dataSource.DisplayKey = "Name";
dataSource.ValueKey = "Value";
dataSource.ItemSource = array;

dataSource.FormatText ((NSObject item, TKDataSourceGroup group) => {


DSItem dsItem = (DSItem)item;
return new NSString(string.Format("{0} has {1} points", dsItem.Name,
dsItem.Value));
});

var tableView = new UITableView (this.View.Bounds);


tableView.DataSource = dataSource;
this.View.AddSubview (tableView);
}
}
 

You can modify descriptor collections by using the corresponding add and remove methods. You
can reapply all descriptors when data has changed by calling the ReloadData method.

2302
Telerik UI for Xamarin

DataSource for Xamarin.iOS: Accessing remote data


With TLKDataSource it is easy to utilize data coming from remote sources, for example web
services. To do this you should call the LoadDataFromURL method like demonstrated below:

C#
var chart = new TKChart (this.View.Bounds);
chart.AutoresizingMask = UIViewAutoresizing.FlexibleWidth |
UIViewAutoresizing.FlexibleHeight;
this.View.Add (chart);

string url =
"http://www.telerik.com/docs/default-source/ui-for-ios/weather.json?sfvrsn=2";
dataSource.LoadDataFromURL (url, TKDataSourceDataFormat.JSON, "dayList", (NSError err)
=> {
if (err != null) {
Console.WriteLine("Can't connect with the server!");
return;
}

dataSource.Settings.Chart.CreateSeries((TKDataSourceGroup group) => {


TKChartSeries series = null;
if (group.ValueKey == "clouds") {
series = new TKChartColumnSeries();
series.YAxis = new TKChartNumericAxis(NSObject.FromObject(0),
NSObject.FromObject(100));
series.YAxis.Title = "clouds";
series.YAxis.Style.TitleStyle.RotationAngle = (float)Math.PI/2.0f;
}
else {
series = new TKChartLineSeries();
series.YAxis = new TKChartNumericAxis(NSObject.FromObject(-10),
NSObject.FromObject(30));
if (group.ValueKey == "temp.min") {
series.YAxis.Position = TKChartAxisPosition.Right;
series.YAxis.Title = "temperature";
series.YAxis.Style.TitleStyle.RotationAngle = (float)Math.PI/2.0f;
chart.AddAxis(series.YAxis);
}
}
return series;
});

dataSource.Map((NSObject item) => {


double interval = ((NSNumber)item.ValueForKey(new
NSString("dateTime"))).DoubleValue;
NSDate date = NSDate.FromTimeIntervalSince1970(interval);
item.SetValueForKey(date, new NSString("dateTime"));
return item;
});

NSObject[] items = this.dataSource.Items;

2303
Telerik UI for Xamarin

NSMutableArray newItems = new NSMutableArray();


newItems.Add(new TKDataSourceGroup(items, "clouds", "dateTime"));
newItems.Add(new TKDataSourceGroup(items, "temp.min", "dateTime"));
newItems.Add(new TKDataSourceGroup(items, "temp.max", "dateTime"));
dataSource.ItemSource = newItems;

chart.DataSource = dataSource;

var formatter = new NSDateFormatter();


formatter.DateFormat = "dd";
TKChartDateTimeAxis xAxis = (TKChartDateTimeAxis)chart.XAxis;
xAxis.MajorTickInterval = 1;
xAxis.PlotMode = TKChartAxisPlotMode.BetweenTicks;
xAxis.LabelFormatter = formatter;
xAxis.Title = "date";
xAxis.MinorTickIntervalUnit = TKChartDateTimeAxisIntervalUnit.Days;
});
 

The code above downloads a JSON formatted data from the specified web service, sets the
ValueKey property and presents the result in TKChart.

Authenticating
In some cases the data coming from a remote source is protected. In such scenarios you should
inherit a class from TLKDataSource and override the appropriate NSURLConnectionDelegate
method. TLKDataSource supports all authentication modes supported by NSURLConnection.
Further information about authentication modes is available in Apple documentation.

The following code demonstrates the usage of basic authentication with TLKDataSource:

C#
public class DataSourceDocsAuth : TLKDataSource
{
public DataSourceDocsAuth ()
{
}
public class MyDataSource: TLKDataSource
{
[Export ("connection:didReceiveAuthenticationChallenge:")]
public void ReceivedAuthenticationChallenge (NSUrlConnection connection,
NSUrlAuthenticationChallenge challenge)
{
if (challenge.PreviousFailureCount == 0) {
var credential = new NSUrlCredential ("USER", "PASSWORD",
NSUrlCredentialPersistence.ForSession);
challenge.Sender.UseCredential (credential, challenge);
}
else {
Console.WriteLine("previous authentication failure");
}
}

2304
Telerik UI for Xamarin

}
}
 

2305
Telerik UI for Xamarin

Gauges for Xamarin.iOS: Overview


The TKGauge control serve as instrument that indicate and give a visual display of amount, level, or
contents of something. These values are presented via indicators (needles, arrows, and others). In
addition TKGauge is a highly customizable component that allows you to show the current status of
a value within a range of upper and lower bounds, illustrate progress towards a goal or a summary of
a fluctuating metric.

TKGauge main features include:

 Different display layouts: RadialGauge and LinearGauge


 Various components types: indicators, segments, ranges, scales
 Multiple scales with different ranges
 Multiple indicators
 Animations
 User interactions

Examples with Gauge control can be found in our Native Xamarin.iOS examples.
 

2306
Telerik UI for Xamarin

Gauges for Xamarin.iOS: Getting Started


This quick start tutorial demonstrates how to create a simple gauge view with TKGauge.

Setting up the TKGauge


In order to use the Telerik UI for Xamarin.iOS Gauge control you need to add the following
namespace:

Open your *UIViewController file and add a reference to the chart header file:

C#
using TelerikUI;
 

Note that starting with Xcode 6 Apple doesn't generate the precompiled headers file automatically.
That is why you should add import the UIKit framework before importing TelerikUI:

C#
using UIKit;
 

Add Radial Gauge


You can start by creating a TKGauge view object in ViewDidLoad() method. TelerikUI supports
radial and linear type of gauge. You can instantiate TKRadialGauge by using the following lines:

C#
radialGauge = new TKRadialGauge ();
this.radialGauge.Delegate = new GaugeDelegate ();
this.View.AddSubview (this.radialGauge);
 

There is few tipes of components - scales, segments and indicators - allowing you to fully customize
the overall look and feel.

Add Scale
Here is an example how to add scale:

C#
TKGaugeRadialScale scale = new TKGaugeRadialScale (new NSNumber (0), new NSNumber
(6));
this.radialGauge.AddScale (scale);
 

2307
Telerik UI for Xamarin

Add Segment
Now add a segment to the scale:

C#
TKGaugeSegment segment = new TKGaugeSegment (new NSNumber(-10), new NSNumber(18));
segment.Location = 0.56f;
segment.Width = 0.05f;
segment.Width2 = 0.05f;
segment.Cap = TKGaugeSegmentCap.Round;
 

Add Indicator
Add an indicator to the scale:

2308
Telerik UI for Xamarin

C#
TKGaugeNeedle needle = new TKGaugeNeedle();
needle.Width = 3;
needle.TopWidth = 3;
needle.Length = 0.6f;
needle.ShadowOffset = new CGSize(1, 1);
needle.ShadowOpacity = 0.8f;
needle.ShadowRadius = 1.5f;
scale.AddIndicator(needle);
 

Gauge Getting Started example can be found in our Native Xamarin.iOS examples.
 

2309
Telerik UI for Xamarin

Gauges for Xamarin.iOS: Animations


You can simulate an animation to change the Gauge Needle position in the TKGauge component.

Gauge Animation example can be found in our Native Xamarin.iOS examples.


 

2310
Telerik UI for Xamarin

Gauges for Xamarin.iOS: Scales


TKGauge component TKGaugeScale provides two types of visual representation:

Radial
C#
TKGaugeRadialScale scale1 = new TKGaugeRadialScale ();
scale1.Range = new TKRange (new NSNumber(34), new NSNumber(40));
scale1.Ticks.Position = TKGaugeTicksPosition.Inner;
this.radialGauge.AddScale(scale1);
 

 Blue Segment

C#
TKGaugeSegment blueSegment = new TKGaugeSegment ();
blueSegment.Range = new TKRange (new NSNumber(34), new NSNumber(36));
blueSegment.Location = 0.70f;
blueSegment.Width = 0.08f;
scale1.AddSegment(blueSegment);
 

 Red Segment

C#
TKGaugeSegment redSegment = new TKGaugeSegment();
redSegment.Range = new TKRange (new NSNumber(36.05), new NSNumber(40));
redSegment.Location = 0.70f;
redSegment.Width = 0.08f;
redSegment.Fill = new TKSolidFill(UIColor.Red);
scale1.AddSegment(redSegment);

2311
Telerik UI for Xamarin

 Additional customizations for ticks and label:

C#
TKGaugeRadialScale scale2 = new TKGaugeRadialScale ();
scale2.Range = new TKRange (new NSNumber(93.2), new NSNumber(104));
scale2.Ticks.Position = TKGaugeTicksPosition.Outer;
scale2.Ticks.MajorTicksCount = 6;
scale2.Ticks.MinorTicksCount = 20;
scale2.Labels.Offset = 0.15f;
scale2.Labels.Position = TKGaugeLabelsPosition.Outer;
scale2.Labels.LabelFormat = "%.01f";
scale2.Labels.Count = 6;
this.radialGauge.AddScale(scale2);

for(int i = 0; i< this.radialGauge.Scales.Length; i++) {


TKGaugeRadialScale scale = this.radialGauge.Scales[i] as TKGaugeRadialScale;
scale.Stroke = new TKStroke(UIColor.Gray, 2);
scale.Ticks.MajorTicksStroke = new TKStroke(UIColor.Gray, 1);
scale.Labels.Color = UIColor.Gray;
scale.Ticks.Offset = 0;
scale.Radius = i*0.12f + 0.60f;
}
 

Linear
C#
TKGaugeLinearScale scale1 = new TKGaugeLinearScale ();
scale1.Range = new TKRange (new NSNumber(34), new NSNumber(40));
scale1.Ticks.Position = TKGaugeTicksPosition.Inner;
this.linearGauge.AddScale(scale1);
 

The scales appereance can be easily customized by adding different segments to it.

 Red Segment

C#
TKGaugeSegment blueSegment = new TKGaugeSegment ();
blueSegment.Range = new TKRange (new NSNumber(34), new NSNumber(36));
blueSegment.Location = 0.62f;
blueSegment.Width = 0.08f;
blueSegment.Width2 = 0.08f;
scale1.AddSegment(blueSegment);
 

 Blue Segment

2312
Telerik UI for Xamarin

C#
TKGaugeSegment redSegment = new TKGaugeSegment();
redSegment.Range = new TKRange (new NSNumber(36.05), new NSNumber(40));
redSegment.Location = 0.62f;
redSegment.Width = 0.08f;
redSegment.Width2 = 0.08f;
redSegment.Fill = new TKSolidFill(UIColor.Red);
scale1.AddSegment(redSegment);
 

TKGauge also allows applying multiple scales on a single gauge.

TKGaugeScale has various properties for customizing its ticks and labels.

So, let's add a second scale and customize both:

C#
TKGaugeLinearScale scale2 = new TKGaugeLinearScale ();
scale2.Range = new TKRange (new NSNumber(93.2), new NSNumber(104));
scale2.Ticks.Position = TKGaugeTicksPosition.Outer;
scale2.Ticks.MajorTicksCount = 6;
scale2.Ticks.MinorTicksCount = 20;
scale2.Labels.Position = TKGaugeLabelsPosition.Outer;
scale2.Labels.LabelFormat = "%.01f";
scale2.Labels.Count = 6;
this.linearGauge.AddScale(scale2);

for(int i = 0; i< this.linearGauge.Scales.Length; i++) {

TKGaugeLinearScale scale = this.linearGauge.Scales[i] as TKGaugeLinearScale;


scale.Stroke = new TKStroke(UIColor.Gray, 2);
scale.Ticks.MajorTicksStroke = new TKStroke(UIColor.Gray, 1);
scale.Labels.Color = UIColor.Gray;
scale.Ticks.Offset = 0;
scale.Offset = i*0.12f + 0.60f;
}
 

Example
Sample Gauges Scale example with Linear and Radial Gauge can be found in our Native
Xamarin.iOS examples.
 

2313
Telerik UI for Xamarin

2314
Telerik UI for Xamarin

Gauges for Xamarin.iOS: Segments


TKGauge Segment is a class representing a color range indicating a portion of the gauge with
different width, radius, start and end value.

You can use the following properties when applying a Segment:

 Location property of TKGaugeSegment determines how far from the center the segment will
be placed. Its value could be between 0 and 1.
 The width of a segment is controlled by the Width property which can also be between 0
and 1.
 The segment has properties as Fill and Stroke that are used for customizing the look of
the segment.
 Cap property (of type TelerikUI.TKGaugeSegmentCap) determines if the ends of the
segment are rounded or edgy.

C#
TKGaugeSegment segment = new TKGaugeSegment (this.greenValues[i],
this.greenValues[i+1]);
segment.Fill = new TKSolidFill(this.greenColors[i]);

2315
Telerik UI for Xamarin

segment.Location = 0.67f;
segment.Cap = TKGaugeSegmentCap.Round;
 

Sample example Segments can be found in our Native Xamarin.iOS examples Gauge Ranges demo.
 

2316
Telerik UI for Xamarin

ListViewfor Xamarin.iOS: Overview


The Telerik ListView for iOS provides the most frequently used functionalities associated with a
ListView scenario in one and the same framework eliminating the overhead of integrating multiple
solutions from different authors. To make working with data easier for developers, the control works
seamlessly with the Telerik DataSource control, which serves as a mediator between the raw data
that needs to be displayed and the UI component.

The features at a glance are:

 Cells Swipe
 Cells Reordering
 Pull-to-refresh
 Load-on-demand
 Different Layout Modes
 Single/Multiple Selection
 Grouping

Demos for ListView can be found in our Native Xamarin.iOS examples.


 

2317
Telerik UI for Xamarin

ListView for Xamarin.iOS: Getting Started


This quick start tutorial demonstrates how to create a simple iOS application with TKListView.

Setting up TKListView
Now that our project is created and the TelerikUI.framework is added, we can start referencing and
using the TelerikUI types:

Open your UIViewController file and add a reference to Telerik UI header file:

C#
using TelerikUI;
 

Note that starting with Xcode 6 Apple doesn't generate the precompiled headers file automatically.
That is why you should add import the UIKit framework before importing TelerikUI:

C#
using UIKit;
 

In the ViewDidLoad method of your view controller prepare a small array of sample data to be
presented in TKListView.

C#
simpleArrayOfStrings = new NSMutableArray();
simpleArrayOfStrings.Add (new NSString ("Kristina Wolfe"));
simpleArrayOfStrings.Add (new NSString ("Freda Curtis"));
simpleArrayOfStrings.Add (new NSString ("Eva Lawson"));
simpleArrayOfStrings.Add (new NSString ("Emmett Santos"));
simpleArrayOfStrings.Add (new NSString ("Theresa Bryan"));
simpleArrayOfStrings.Add (new NSString ("Jenny Fuller"));
simpleArrayOfStrings.Add (new NSString ("Terrell Norris"));
simpleArrayOfStrings.Add (new NSString ("Eric Wheeler"));
simpleArrayOfStrings.Add (new NSString ("Julius Clayton"));
simpleArrayOfStrings.Add (new NSString ("Harry Douglas"));
simpleArrayOfStrings.Add (new NSString ("Eduardo Thomas"));
simpleArrayOfStrings.Add (new NSString ("Orlando Mathis"));
simpleArrayOfStrings.Add (new NSString ("Alfredo Thornton"));
 

Next, create an instance of TLKDataSource. This components is used to feed our data to
TKListView.

C#
dataSource.ItemSource = simpleArrayOfStrings;

2318
Telerik UI for Xamarin

Then create a new instance of TKListView and add it as a subview of the ViewController's main
view. The AutoresizingMask property is set in order to allow correct resizing of the list view when
the device is rotated in landscape mode.

C#
TKListView listView = new TKListView ();
listView.Frame = new CGRect (0, 0,
this.View.Bounds.Size.Width,this.View.Bounds.Size.Height-20);
listView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth |
UIViewAutoresizing.FlexibleHeight;
listView.WeakDataSource = dataSource;
this.View.AddSubview(listView);
 

So far we have got the following view:

Enable Multiple selection:


C#
listView.AllowsMultipleSelection = true;
 

To see the result, after running this sample, select to select a few items:

2319
Telerik UI for Xamarin

Enable Reordering
Adding a single line of code should allow the user to reorder items by dragging a handle.

C#
listView.AllowsCellReorder = true;
 

2320
Telerik UI for Xamarin

A sample Getting Started example can be found in our Native Xamarin.iOS examples.
 

2321
Telerik UI for Xamarin

ListView: Populating with data


There are two ways to feed TKListView data you need to display. You can do that by implementing
several methods from the TKListViewDataSource protocol or you could let the TLKDataSource
component do the dirty work for you.

Populating with data using TKDataSource


TKDataSource contains implementation of the TKListViewDataSource protocol that you may use
out-of-the box. In addition TLKDataSource provides handy data shaping capabilities such as sorting
and filtering.

The following example shows how to initialise TKDataSource with data and feed that data to
TKListView.

C#
public class ListViewBasicSetup : XamarinExampleViewController
{
NSMutableArray simpleArrayOfStrings;
TLKDataSource dataSource = new TLKDataSource();

public ListViewBasicSetup ()
{
}

public override void ViewDidLoad()


{
base.ViewDidLoad();
simpleArrayOfStrings = new NSMutableArray();
simpleArrayOfStrings.Add (new NSString ("Kristina Wolfe"));
simpleArrayOfStrings.Add (new NSString ("Freda Curtis"));
simpleArrayOfStrings.Add (new NSString ("Eva Lawson"));
simpleArrayOfStrings.Add (new NSString ("Emmett Santos"));
simpleArrayOfStrings.Add (new NSString ("Theresa Bryan"));
simpleArrayOfStrings.Add (new NSString ("Jenny Fuller"));
simpleArrayOfStrings.Add (new NSString ("Terrell Norris"));
simpleArrayOfStrings.Add (new NSString ("Eric Wheeler"));
simpleArrayOfStrings.Add (new NSString ("Julius Clayton"));
simpleArrayOfStrings.Add (new NSString ("Harry Douglas"));
simpleArrayOfStrings.Add (new NSString ("Eduardo Thomas"));
simpleArrayOfStrings.Add (new NSString ("Orlando Mathis"));
simpleArrayOfStrings.Add (new NSString ("Alfredo Thornton"));

dataSource.ItemSource = simpleArrayOfStrings;

TKListView listView = new TKListView ();


listView.Frame = new CGRect (0, 0,
this.View.Bounds.Size.Width,this.View.Bounds.Size.Height-20);

2322
Telerik UI for Xamarin

listView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth |
UIViewAutoresizing.FlexibleHeight;
listView.WeakDataSource = dataSource;
this.View.AddSubview(listView);

listView.AllowsMultipleSelection = true;

listView.AllowsCellReorder = true;
}

}
 

Populating with data using TKListViewDataSource


protocol
Alternatively TKListView may be populated with data by manually implementing several methods
from the TKListViewDataSource protocol. This way requires a bit more code but gives more
flexibility.First we need to set the datasource property of TKListView to a class adopting the
TKListViewDatasource protocol. In the sample code bellow it is our view controller.

C#
public class ListViewDocsSetupDataSource : XamarinExampleViewController
{
public NSArray sampleArrayOfStrings;

public ListViewDocsSetupDataSource ()
{
}

public override void ViewDidLoad ()


{
base.ViewDidLoad ();
this.sampleArrayOfStrings = NSArray.FromStrings (new String [] {
"Kristina Wolfe",
"Freda Curtis",
"Jeffery Francis",
"Eva Lawson",
"Emmett Santos",
"Theresa Bryan",
"Jenny Fuller",
"Terrell Norris",
"Eric Wheeler",
"Julius Clayton",
"Alfredo Thornton",
"Roberto Romero",
"Orlando Mathis",
"Eduardo Thomas",
"Harry Douglas"
});

2323
Telerik UI for Xamarin

TKListView listView = new TKListView (this.View.Bounds);


listView.RegisterClassForCell (new Class (typeof(TKListViewCell)), "cell");
listView.DataSource = new ListViewDataSource (this);

this.View.AddSubview (listView);

class ListViewDataSource: TKListViewDataSource


{
ListViewDocsSetupDataSource owner;

public ListViewDataSource(ListViewDocsSetupDataSource owner)


{
this.owner = owner;
}

public override int NumberOfItemsInSection (TKListView listView, int section) {


return (int)this.owner.sampleArrayOfStrings.Count;
}

public override int NumberOfSectionsInListView (TKListView listView)


{
return 1;
}

public override TKListViewCell CellForItem (TKListView listView, NSIndexPath


indexPath)
{
TKListViewCell cell = listView.DequeueReusableCell ("cell", indexPath) as
TKListViewCell;
cell.TextLabel.Text = this.owner.sampleArrayOfStrings.GetItem<NSString>
((uint)indexPath.Row);
return cell;
}
}
}
 

2324
Telerik UI for Xamarin

ListView for Xamarin.iOS: Grouping


ListView may be set up to display items in groups divided visually by section headers and
footers.There are two ways to implement grouping with TKListView - manually implementing the
required methods of the TKListViewDataSource delegate or using TLKDataSource and let it do the
dirty work for you.

Displaying grouped data using TKDataSource


In case you need more flexibility you may implement grouping manualy as follows.

C#
NSMutableArray items = new NSMutableArray ();
items.Add (new DataSourceItem ("John", 50f, "A"));
items.Add (new DataSourceItem ("Abby", 33f, "A"));
items.Add (new DataSourceItem ("Smith", 42f, "B"));
items.Add (new DataSourceItem ("Peter", 28f, "B"));
items.Add (new DataSourceItem ("Paula", 25f, "B"));

this.dataSource = new TLKDataSource ();


this.dataSource.ItemSource = items;
this.dataSource.GroupWithKey ("Group");
dataSource.DisplayKey = "Name";

TKListView listView = new TKListView (new CGRect (20, 20, this.View.Bounds.Size.Width


- 40, this.View.Bounds.Size.Height - 40));
listView.WeakDataSource = dataSource;
this.View.AddSubview (listView);

var layout = listView.Layout as TKListViewLinearLayout;


layout.HeaderReferenceSize = new CGSize (200, 22);
 

Displaying grouped data using a TKListViewDataSource

2325
Telerik UI for Xamarin

delegate methods
Here is the code:

C#
public class ListViewDocsGroupsDelegate : XamarinExampleViewController
{
public NSMutableArray groups;

public ListViewDocsGroupsDelegate ()
{
}

public override void ViewDidLoad ()


{
base.ViewDidLoad ();
groups = new NSMutableArray ();
groups.Add (NSArray.FromStrings (new string[] { "John", "Abby" }));
groups.Add(NSArray.FromStrings (new string[] { "Smith", "Peter", "Paula" }));

TKListView listView = new TKListView (new CGRect (20, 20,


this.View.Bounds.Size.Width - 40, this.View.Bounds.Size.Height - 40));
listView.RegisterClassForCell (new Class (typeof(TKListViewCell)), "cell");

listView.RegisterClassForSupplementaryView (new Class


(typeof(TKListViewHeaderCell)), TKListViewElementKindSectionKey.Header, new
NSString("header"));
listView.DataSource = new ListViewDataSource (this);
TKListViewLinearLayout layout = (TKListViewLinearLayout)listView.Layout;
layout.HeaderReferenceSize = new CGSize (200, 22);

this.View.AddSubview (listView);
}
}

class ListViewDataSource : TKListViewDataSource


{
ListViewDocsGroupsDelegate owner;

public ListViewDataSource (ListViewDocsGroupsDelegate owner)


{
this.owner = owner;
}

public override int NumberOfSectionsInListView (TKListView listView)


{
return (int)this.owner.groups.Count;
}

public override int NumberOfItemsInSection (TKListView listView, int section)


{
return (int)this.owner.groups.GetItem<NSArray>((uint)section).Count;
}

2326
Telerik UI for Xamarin

public override TKListViewCell CellForItem (TKListView listView, NSIndexPath


indexPath)
{
TKListViewCell cell = listView.DequeueReusableCell("cell", indexPath) as
TKListViewCell;
cell.TextLabel.Text = this.owner.groups.GetItem<NSArray>
((uint)indexPath.Section).GetItem<NSString> ((uint)indexPath.Row);
return cell;
}

public override TKListViewReusableCell ViewForSupplementaryElementOfKind


(TKListView listView, NSString kind, NSIndexPath indexPath)
{
TKListViewReusableCell headerCell =
listView.DequeueReusableSupplementaryView(kind, "header", indexPath) as
TKListViewReusableCell;
headerCell.TextLabel.Text = String.Format ("Group {0}", indexPath.Section);
return headerCell;
}
}
 

ListView Grouping example can be found in our Native Xamarin.iOS examples.


 

2327
Telerik UI for Xamarin

ListView for Xamarin.iOS: Selection


TKListView supports different selection modes:

 Single selection
 Multiple selection

The end-user can use different gestures to trigger cell selection:

 Selection on press.
 Selection on hold (long press).

Additionaly, TKListView provides a few methods to programmatically control the selection state as
well as delegate methods to react to user interactions related to selection.

This article describes the selection API of TKListView in detail.

The AllowsMultipleSelection property of TKListView defines whether the user is allowed to


select multiple items at the same time. It also affects the default appearance of the selected items.

Single seletion mode

The default value of the AllowsMultipleSelection property is false

2328
Telerik UI for Xamarin

Multiple selection mode

Set the allowsMultipleSelection property to true to enable this view:

C#
this.listView.AllowsMultipleSelection = true;
 

Selection behavior
The selectionBehavior property determines on what type of interaction cells get selected. It's values
are By default TKListView will allow user to select on press.

C#
this.listView.SelectionBehavior = TKListViewSelectionBehavior.Press;
 

2329
Telerik UI for Xamarin

Selection on hold (long press)


In this mode a long-press gesture is required in order to select a cell.

C#
this.listView.SelectionBehavior = TKListViewSelectionBehavior.LongPress;
 

Disable selection
In order to disable the selection, you need to set the SelectionBehavior property to
TKListViewSelectionBehavior.None:

C#
this.listView.SelectionBehavior = TKListViewSelectionBehavior.None;
 

Programatically selecting and deselecting items


Cells can be selected programatically as well.

C#
NSIndexPath indexPath = NSIndexPath.FromRowSection (1, 0);
this.listView.SelectItem (indexPath, false, UICollectionViewScrollPosition.None);
 

To deselected a cell programatically, you should call the DeselectItem method giving the
indexPath of the cell.

TKListViewDelegate methods
The TKListViewDelegate protocol provides a few handy delegate methods to be used to control
and respond to selection events triggered by user. In order to take advantage of these methods, you
should set the delegate proeprty of TKListView to a class adopting the TKListViewDelegate
protocol. For example:

C#
this.listViewDelegate = new ListViewDelegate(this);
 

Bellow you can find some details on how you can use the delegate methods from
TKListViewDelegate.

Responding to user triggered cell selection / deselection


If you need to perform a specific action after the user selects or deselects a cell, you can use the

2330
Telerik UI for Xamarin

following methods from the TKListViewDelegate protocol:

C#
public override void DidSelectItemAtIndexPath (TKListView listView, NSIndexPath
indexPath)
{
this.owner.label.Text = string.Format("Selected: {0}",
this.owner.dataSource.Items[indexPath.Row]);
Console.WriteLine ("Did select item at row {0}", this.owner.dataSource.Items
[indexPath.Row]);
TKListViewCell cell = listView.CellForItem (indexPath);
if (cell != null) {
cell.SelectedBackgroundView.Hidden = false;
}
}

public override void DidDeselectItemAtIndexPath (TKListView listView, NSIndexPath


indexPath)
{
Console.WriteLine("Did deselect item at row {0}",
this.owner.dataSource.Items[indexPath.Row]);
}
 

ListView Selection example can be found in our Native Xamarin.iOS examples.


 

2331
Telerik UI for Xamarin

ListView for Xamarin.iOS: Layouts


TKListView provides the same layout mechanism as UICollectionView. There are three additionally
implemented layouts and you can also create your own by inheriting from UICollectionViewLayout
class. However, all list view features will be available only when using a layout which inherits from
TKListViewLinearLayout.

By default TKListView uses Linear layout but you can easily change that with the layout property.
The layouts that are implemented are:

 Linear - the default layout which orders items in a simple list.


 Grid - lays out items in a grid.
 Staggered - lays out items in a staggered grid formation.

Each of these layouts can layout items in either horizontal or vertical direction.
 

Linear layout
In linear layout cells are distributed in a simple list horizontally or vertically depending on the
selected scroll direction.

2332
Telerik UI for Xamarin

C#
TKListViewLinearLayout layout = new TKListViewLinearLayout ();
layout.ItemSize = new CGSize(200, 200);
layout.HeaderReferenceSize = new CGSize(100, 30);
layout.ItemSpacing = 1;
layout.ScrollDirection = this.scrollDirection;
this.listView.Layout = layout;
this.SetSelectedOption (1, 1);
 

Cells can be aligned left, right, center, stretch by setting the ItemAlignment property:

C#
layout.ItemAlignment = TKListViewItemAlignment.Center;
 

Grid layout

2333
Telerik UI for Xamarin

The grid layout allows for distributing cells in a fixed number of columns/rows. The grid layout
inherits from TKListViewLinearLayout, therefore all properties of TKListViewLinearLayout are also
available in TKListViewGridLayout.

C#
TKListViewGridLayout layout = new TKListViewGridLayout ();
layout.ItemSize = new CGSize(200, 100);
layout.HeaderReferenceSize = new CGSize(100, 30);
layout.SpanCount = 2;
layout.ItemSpacing = 1;
layout.LineSpacing = 1;
layout.ScrollDirection = this.scrollDirection;
this.listView.Layout = layout;
 

Staggered layout
The staggered layout lays out items in a staggered grid formation. It supports horizontal & vertical
layout as well as an ability to align cells. It inherits from TKListViewGridLayout.

2334
Telerik UI for Xamarin

Staggered layout lays its items based on their size. The item size is determined by using the
SizeForItem method of TKListViewLinearLayoutDelegate protocol:

C#
public override CGSize SizeForItem (TKListView listView, TKListViewLinearLayout
layout, NSIndexPath indexPath)
{
if (layout.ScrollDirection == TKListViewScrollDirection.Vertical) {
return new CGSize(100, sizes[indexPath.Row]);
}
else {
return new CGSize(sizes[indexPath.Row], 100);
}
}
 

Staggered grids are likely to have gaps at the edges of the layout. To avoid these gaps, set the
AlignLastLine property to true.

C#

2335
Telerik UI for Xamarin

TKListViewStaggeredLayout layout = new TKListViewStaggeredLayout ();


layout.Delegate = this.staggeredLayoutDelegate;
layout.ItemSize = new CGSize(200, 100);
layout.HeaderReferenceSize = new CGSize(100, 30);
layout.SpanCount = 2;
layout.ItemSpacing = 1;
layout.LineSpacing = 1;
layout.ScrollDirection = this.scrollDirection;
layout.AlignLastLine = true;
this.listView.Layout = layout;
 

LiatView Layout example can be found in our Native Xamarin.iOS examples.


 

2336
Telerik UI for Xamarin

ListView for Xamarin.iOS: Animations


TKListView supports the following predefined animations:

Animation Type Figures


Fade-in

2337
Telerik UI for Xamarin

Scale-in

2338
Telerik UI for Xamarin

Slide-in

The animated images above are just for illustration purposes. They are missing some fps quality
because of the image processing software used to create these images. In order to get a real
understanding of how the animations look and feel, check the Demo application that ships with the
UI for Xamarin suite.
 
These animations can be applied when items enter different states. The following list contains all
states where animations can be applied:

 when an item appears when scrolling


 when adding/inserting an item
 when removing an item

Accessing the Animations API


The animations can be controlled from the animations-related properties of the Telerik ListView
layouts. These properties are exposed at the TKListViewLinearLayout which is the base layout for
the TKListViewGridLayout and TKListViewStaggeredLayout. So, in order to apply some animation
settings to that layout, you can take it like this:

C#
TKListViewLinearLayout layout = (TKListViewLinearLayout)listView.Layout;

2339
Telerik UI for Xamarin

Appear Animations
Those animations are applied when scrolling the list view. You can add a scroll animation by setting
the ItemAppearAnimation property of TKListViewLinearLayout:

C#
layout.ItemAppearAnimation = TKListViewItemAnimation.Scale;
 

Add/Remove animations
To animate an item on insert set the ItemInsertAnimation property:

C#
layout.ItemInsertAnimation = TKListViewItemAnimation.Scale;
 

To animate an item on delete set the ItemDeleteAnimation property:

C#
layout.ItemDeleteAnimation = TKListViewItemAnimation.Slide;
 

Be sure to update your data source before triggering item insert/delete methods in TKListView.

Animations Duration
Animations are controlled by setting properties of TKListViewLinearLayout class. The animation
duration is controlled by setting the AnimationDuration property:

C#
layout.AnimationDuration = 0.4f;
 

A sample ListView Animations example can be found in our Native Xamarin.iOS examples.
 

2340
Telerik UI for Xamarin

ListView for Xamarin.iOS: Reordering Cells


TKListView supports reordering cells. When reordering is enabled a drag handle appears in each
cell. Using this handle cells can be dragged thus changing the order of items.

Enable cell reorder


Use the AllowsCellReorder property to enable user to reorder cells. When reordering is allowed
cells will display a draggable reorder handle as a visual hint.

C#
this.listView.AllowsCellReorder = true;
 

Responding to cell reorder interaction

2341
Telerik UI for Xamarin

After the user performs a reorder gesture the following delegate method from the
TKListViewDelegate will be called - DidReorderItemFromIndexPath

This is the place where you get information about which item was reordered and from what position
and to what position. There you need to reorder your source data.

C#
class ListViewDelegate: TKListViewDelegate
{
ListViewReorder owner;

public ListViewDelegate(ListViewReorder owner)


{
this.owner = owner;
}

public override void WillReorderItemAtIndexPath (TKListView listView, NSIndexPath


indexPath)
{
TKListViewCell cell = listView.CellForItem(indexPath);
cell.BackgroundView.BackgroundColor = UIColor.Yellow;
}

public override void DidReorderItemFromIndexPath (TKListView listView, NSIndexPath


originalIndexPath, NSIndexPath targetIndexPath)
{
TKListViewCell cell = listView.CellForItem(originalIndexPath);
cell.BackgroundView.BackgroundColor = UIColor.White;
this.owner.dataSource.DidReorderItemFromTo (listView, originalIndexPath,
targetIndexPath);
}
}
 

In case you are using TLKDataSource you may set it as a delegate for TKListView. With such a
setup you will not need to reorder your data manually. TLKDataSource will handle that for you.

C#
TKListView listView = new TKListView();
TLKDataSource dataSource = new TLKDataSource();
this.listView.WeakDataSource = this.dataSource;
this.dataSource.AllowItemsReorder = true;
 

A sample ListView Reorder example can be found in our Native Xamarin.iOS examples.
 

2342
Telerik UI for Xamarin

ListView for Xamarin.iOS: Cell Swipe


Gesture
The swipe gesture feature allows end-users to use swipe the ListView cell. When the user swipes,
the content view moves revealing a designated swipe background view where you can place custom
views ready for interaction e.g. buttons images etc.

Enable Cell Swipe Gesture


Use the AllowsCellSwipe property to allow the user to perform swipe gesture on cells.

C#

2343
Telerik UI for Xamarin

this.listView.AllowsCellSwipe = true;
 

Configure Cell Swipe Gesture


Use the CellSwipeLimits property to set how far the cell may be swiped.

C#
this.listView.CellSwipeLimits = new UIEdgeInsets (0, 60, 0, 180);
 

Use the CellSwipeTreshold property to set the minimum distance the user needs to swipe before
the gesture is considered effective. If the user swipes below the treshold, the cell will auto-revert to
its original state.

C#
this.listView.CellSwipeTreshold = 30;
 

Use the CellSwipeAnimationDuration property to set the cell swipe animation duration

Add the content that should be visible when swipe is applied to the backgroundView of
TKListViewCell:

C#
if (cell.SwipeBackgroundView.Subviews.Length == 0) {
CGSize size = cell.Frame.Size;
UIFont font = UIFont.SystemFontOfSize(14);
UIButton bMore = new UIButton(new CGRect(size.Width - 180, 0, 60, size.Height));
bMore.SetTitle("More", UIControlState.Normal);
bMore.BackgroundColor = UIColor.LightGray;
bMore.TitleLabel.Font = font;
bMore.AddTarget(ButtonTouched, UIControlEvent.TouchUpInside);
cell.SwipeBackgroundView.AddSubview(bMore);

UIButton bFlag = new UIButton(new CGRect(size.Width - 120, 0, 60, size.Height));


bFlag.SetTitle("Flag", UIControlState.Normal);
bFlag.BackgroundColor = UIColor.Orange;
bFlag.TitleLabel.Font = font;
bFlag.AddTarget(ButtonTouched, UIControlEvent.TouchUpInside);
cell.SwipeBackgroundView.AddSubview(bFlag);

UIButton bTrash = new UIButton(new CGRect(size.Width - 60, 0, 60, size.Height));


bTrash.SetTitle("Trash", UIControlState.Normal);
bTrash.BackgroundColor = UIColor.Red;
bTrash.TitleLabel.Font = font;
bTrash.AddTarget(ButtonTouched, UIControlEvent.TouchUpInside);
cell.SwipeBackgroundView.AddSubview(bTrash);

UIButton bUnread = new UIButton(new CGRect(0, 0, 60, size.Height));

2344
Telerik UI for Xamarin

bUnread.SetTitle("Mark as Unread", UIControlState.Normal);


bUnread.BackgroundColor = UIColor.Blue;
bUnread.TitleLabel.Font = font;
bUnread.TitleLabel.LineBreakMode = UILineBreakMode.WordWrap;
bUnread.TitleLabel.TextAlignment = UITextAlignment.Center;
bUnread.AddTarget(ButtonTouched, UIControlEvent.TouchUpInside);
cell.SwipeBackgroundView.AddSubview(bUnread);
}
 

Responding to swipe interactions


In order to respond programmatically to a swipe gesture performed by user, you will need to
implement one or more of the following methods from the TKListViewDelegate protocol.

 ShouldSwipeCell
 DidSwipeCell
 DidFinishSwipeCell

C#
class ListViewDelegate: TKListViewDelegate
{
ListViewSwipe owner;

public ListViewDelegate(ListViewSwipe owner)


{
this.owner = owner;
}

public override void DidSwipeCell (TKListView listView, TKListViewCell cell,


NSIndexPath indexPath, CGPoint offset)
{
this.owner.AnimateButtonInCell (cell, offset);
}

public override void DidFinishSwipeCell (TKListView listView, TKListViewCell cell,


NSIndexPath indexPath, CGPoint offset)
{
Console.WriteLine ("Did swipe cell at index: {0}", indexPath.Row);
}
}
 

A sample ListView Cell Swipe example can be found in our Native Xamarin.iOS examples.
 

2345
Telerik UI for Xamarin

ListView for Xamarin.iOS: Pull-to-refresh


TKListView can be refreshed by a pull-to-refresh gesture. If enabled, the feature allows the user to
refresh data by swiping his finger down when the content is scrolled up to the top. This will trigger an
animated activity indicator which will stay visible until data is refreshed.

Enabling pull-to-refresh
Use the AllowsPullToRefresh property to enable the feature.

C#
listView.AllowsPullToRefresh = true;
 

2346
Telerik UI for Xamarin

Responding to the pull-to-refresh gesture


To be able to respond to the a pull-to-refresh gesture, you will need to implement the
ListViewShouldRefreshOnPull method from the TKListViewDelegateprotocol. After fresh data
is available you will need to notify TKListView by calling the didRefreshOnPull method. This call
will allow TKListView to hide the activity indicator and display the fresh data.

C#
public override bool ListViewShouldRefreshOnPull (TKListView listView)
{
DispatchQueue.DefaultGlobalQueue.DispatchAsync (() => {
Random r = new Random();
this.owner.newItemsCount = this.owner.UpdateData(1 + r.Next(0, 4));
DispatchQueue.MainQueue.DispatchAfter(new DispatchTime(DispatchTime.Now, 2 *
500000000), () => {
listView.DidRefreshOnPull();
if (this.owner.newItemsCount < 1) {
UIAlertView alert = new UIAlertView("Pull to refresh", "No more data
available!",null,"Close",null);
alert.Show();
}
});
});

return true;
}
 

ListView Pull to Refresh example can be found in our Native Xamarin.iOS examples.
 

2347
Telerik UI for Xamarin

ListView for Xamarin.iOS: Load-on-demand


There are certain scenarios typically with remote data over the wire where data needs to be loaded
continuously on small portions. TKListView can load data on demand.

Enabling the load-on-demand


To enable the load on demand feature, you shoud set the LoadOnDemandMode property to one of
the two supported modes Auto or Manual.

C#
listView.LoadOnDemandMode = TKListViewLoadOnDemandMode.Manual;
 

When using the Auto LoadOnDemand mode the LoadOnDemandBufferSize of type int property
defines the number of cells from the bottom of the list view up at which to start requesting data.

C#
listView.LoadOnDemandBufferSize = 5;
 

After setting the desired LoadOnDemandMode you should implement the TKListViewDelgate
method ShouldLoadMoreDataAtIndexPath: to determine if more data should be loaded. After the
data is loaded you should notify the ListView by calling its DidLoadDataOnDemand method:

C#
class ListViewDelegate: TKListViewDelegate
{
ListViewLoadOnDemand owner;

public ListViewDelegate(ListViewLoadOnDemand owner)


{
this.owner = owner;
}

public override bool ShouldLoadMoreDataAtIndexPath (TKListView listView,


NSIndexPath indexPath)
{
DispatchQueue.DefaultGlobalQueue.DispatchAsync (() => {
this.owner.lastRetrievedDataIndex = Math.Min(this.owner.names.Items.Length,
this.owner.lastRetrievedDataIndex + 10);
DispatchQueue.MainQueue.DispatchAfter(new DispatchTime(DispatchTime.Now, 2 *
400000000), new Action(delegate {
if (this.owner.names.Items.Length == this.owner.lastRetrievedDataIndex) {
listView.LoadOnDemandMode = TKListViewLoadOnDemandMode.None;
}
listView.DidLoadDataOnDemand();
}));

2348
Telerik UI for Xamarin

});

return true;
}
}
 

When using Manual LoadOnDemand mode, TKListView appends a special cell at the end of the list.
Touching this cell starts the process of loading more data. In this scenario you should process
CellForItem method of TKListViewDataSource and check whether this is a "load on demand cell":

C#
public override TKListViewCell CellForItem (TKListView listView, NSIndexPath
indexPath)
{
TKListViewCell cell = listView.DequeueLoadOnDemandCell (indexPath);

if (cell == null) {
cell = listView.DequeueReusableCell ("cell", indexPath) as TKListViewCell;
cell.ImageView.Image = UIImage.FromBundle (this.owner.photos.Items
[indexPath.Row] as NSString);
cell.TextLabel.Text = this.owner.names.Items [indexPath.Row] as NSString;
Random r = new Random ();
cell.DetailTextLabel.Text = this.owner.loremIpsum.RandomString (10 + r.Next (0,
16), indexPath);
cell.DetailTextLabel.TextColor = UIColor.White;
}

cell.BackgroundView.BackgroundColor = UIColor.FromWhiteAlpha (0.3f, 0.5f);


((TKView)cell.BackgroundView).Stroke = null;

return cell;
}
 

ListView Load On Demand example can be found in our Native Xamarin.iOS examples.
 

2349
Telerik UI for Xamarin

SideDrawer for Xamarin.iOS: Overview


The SideDrawer for iOS steps on the popular navigation pattern where you can access all your
application screens from a single sliding menu. Polished effects and transitions are two major
advantages of Telerik SideDrawer which are available out-of-the-box. The control is highly
customizable and slides in from all four sides of the screen. What also distinguishes the Telerik
SideDrawer control is that its items’ content is not limited to navigation options; it can serve arbitrary
content.

Transition modes

SideDrawer provides lot’s of transition modes to appeal to every app’s design. The transitions modes
are:

 Push
 Reveal
 Reverse Slide Out
 Slide Along
 Slide In On Top
 Scale Up

2350
Telerik UI for Xamarin

 Fade In
 Scale Down Pusher

These transitions can be combined with the SideDrawer’s ability to slide from the one of the four
sides of your device, achieving virtually any combination.

Support for custom content

Normally, SideDrawer will display a list of your menu items. In addition, you can use the menu
surface as a generic container and instead of the standard menu items put a content entirely of your
choice.

Sections

The SideDrawer supports displaying section headers for a groups of items, thus allowing the
end-user to better understand how the app and its navigation are structured.

SideDrawer examples can be found in our Native Xamarin.iOS examples.


 

2351
Telerik UI for Xamarin

SideDrawer for Xamarin.iOS: Getting


Started
This quick start tutorial demonstrates how to create a simple iOS application with TKSideDrawer.

Setting up TKSideDrawer with TKSideDrawerController


Now that our project is created and the TelerikUI.framework is added, we can start referencing and
using the TelerikUI types:

Open your UIViewController file and add a reference to the TelerikUI namespace:

C#
using TelerikUI;
 

Note that starting with Xcode 6 Apple doesn't generate the precompiled headers file automatically.
That is why you should add import the UIKit framework before importing TelerikUI:

2352
Telerik UI for Xamarin

C#
using UIKit;
 

Type the following code in your AppDelegate implementation class inside the FinishedLaunching
method:

C#
[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
// class-level declarations

public override UIWindow Window {


get;
set;
}

public override bool FinishedLaunching (UIApplication application, NSDictionary


launchOptions)
{
SideDrawerGettingStarted main = new SideDrawerGettingStarted ();
TKSideDrawerController sideDrawerController = new TKSideDrawerController
(main);
this.Window.RootViewController = sideDrawerController;

return true;
}

//..
}
 

This code creates an instance of TKSideDrawerController and sets it as a root view controller.
TKSideDrawerController is a containter controller that has an TKSideDrawer instance
embedded inside. The instance is then used by the content controllers of the
TKSideDrawerController.

The next step is to add UINavigationBar, and items to our SideDrawer. You can get the
TKSideDrawer instance from the TKSideDrawerController using the sideDrawer property.

Or, instead of using the sideDrawer property, you can call the TKSideDrawer class method
findSideDrawerForViewController: (especially useful and necessary for the C#
implementation).

Type the following code in the viewDidLoad method of the content controller:

C#
public class SideDrawerGettingStarted : UIViewController
{
TKSideDrawer SideDrawer;

2353
Telerik UI for Xamarin

public override void ViewDidLoad ()


{
base.ViewDidLoad ();

this.View.BackgroundColor = UIColor.Gray;

UINavigationBar navBar = new UINavigationBar (new CGRect (0, 0,


this.View.Frame.Size.Width, 64));
UINavigationItem navItem = new UINavigationItem ("Getting Started");
UIBarButtonItem showSideDrawerButton = new UIBarButtonItem ("Show",
UIBarButtonItemStyle.Plain, this, new Selector ("ShowSideDrawer"));
navItem.LeftBarButtonItem = showSideDrawerButton;
navBar.Items = new UINavigationItem[]{ navItem };
this.View.AddSubview (navBar);

this.SideDrawer = TKSideDrawer.FindSideDrawer (0, this);


TKSideDrawerSection sectionPrimary = this.SideDrawer.AddSection ("Primary");
sectionPrimary.AddItem ("Social");
sectionPrimary.AddItem ("Promotions");

TKSideDrawerSection sectionLabels = this.SideDrawer.AddSection ("Labels");


sectionLabels.AddItem ("Important");
sectionLabels.AddItem ("Starred");
sectionLabels.AddItem ("Sent Mail");
sectionLabels.AddItem ("Drafts");
}

[Export ("ShowSideDrawer")]
public void ShowSideDrawer ()
{
this.SideDrawer.Show ();
}
}
 

Attaching TKSideDrawer to UIViewController


TKSideDrawer can be attached to your view controllers without TKSideDrawerController. In
such a scenario, you should initialize TKSideDrawerView that should be added as subview to your
UIViewController's view and use its mainView property to set up the content of the view.

C#
[Register("SideDrawerGettingStarted")]
public class SideDrawerGettingStarted : XamarinExampleViewController
{
private TKSideDrawerSection primarySection;
private TKSideDrawerSection labelsSection;
SideDrawerDelegate sideDrawerDelegate;

public UINavigationItem NavItem {


get;

2354
Telerik UI for Xamarin

set;
}

public TKSideDrawerView SideDrawerView {


get;
set;
}

public override void ViewDidLoad ()


{
base.ViewDidLoad ();

this.SideDrawerView = new TKSideDrawerView (this.View.Bounds);


this.SideDrawerView.AutoresizingMask = UIViewAutoresizing.FlexibleHeight |
UIViewAutoresizing.FlexibleWidth;
this.View.AddSubview (this.SideDrawerView);

UIImageView backgroundView = new UIImageView


(this.SideDrawerView.MainView.Bounds);
backgroundView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth |
UIViewAutoresizing.FlexibleHeight;
backgroundView.Image = UIImage.FromBundle ("sdk-examples-bg.png");
this.SideDrawerView.MainView.AddSubview (backgroundView);

UINavigationBar navBar = new UINavigationBar (new CGRect (0, 0,


this.SideDrawerView.MainView.Bounds.Width, 44));
navBar.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
this.NavItem = new UINavigationItem ();
UIBarButtonItem showSideDrawer = new UIBarButtonItem (UIImage.FromBundle
("menu.png"), UIBarButtonItemStyle.Plain, this, new Selector ("ShowSideDrawer"));
this.NavItem.LeftBarButtonItem = showSideDrawer;
navBar.Items = new UINavigationItem[] { this.NavItem };
this.SideDrawerView.MainView.AddSubview (navBar);

primarySection = new TKSideDrawerSection ("Primary");


primarySection.AddItem ("Social");
primarySection.AddItem ("Promotions");

labelsSection = new TKSideDrawerSection ("Labels");


labelsSection.AddItem ("Important");
labelsSection.AddItem ("Starred");
labelsSection.AddItem ("Sent Mail");
labelsSection.AddItem ("Drafts");

this.sideDrawerDelegate = new SideDrawerDelegate ();


TKSideDrawer sideDrawer = this.SideDrawerView.SideDrawers[0];
sideDrawer.HeaderView = new SideDrawerHeader (true, this, new Selector
("DismissSideDrawer"));
sideDrawer.AddSection (primarySection);
sideDrawer.AddSection (labelsSection);
sideDrawer.Delegate = this.sideDrawerDelegate;

sideDrawer.Style.HeaderHeight = 44;
sideDrawer.Style.ShadowMode = TKSideDrawerShadowMode.Hostview;
sideDrawer.Style.ShadowOffset = new CGSize (-2f, -0.5f);

2355
Telerik UI for Xamarin

sideDrawer.Style.ShadowRadius = 5;
}

public override void ViewWillDisappear (bool animated)


{
base.ViewWillDisappear (animated);
if (this.NavigationController != null) {
this.NavigationController.InteractivePopGestureRecognizer.Enabled = true;
}

[Export ("ShowSideDrawer")]
public void ShowSideDrawer()
{
this.SideDrawerView.SideDrawers[0].Show();
}

[Export ("DismissSideDrawer")]
public void DismissSideDrawer()
{
this.SideDrawerView.SideDrawers[0].Dismiss();
}
 

SideDrawer Getting Started example can be found in our Native Xamarin.iOS examples.
 

2356
Telerik UI for Xamarin

TKSideDrawer for Xamarin.iOS: Transitions


TKSideDrawer transitions let you use different animation effects for showing/dismissing. You can
also easily create your custom animation by subclassing the base class
TKSideDrawerTransition.

Transition Types
Transition Type Figures

2357
Telerik UI for Xamarin

Push

2358
Telerik UI for Xamarin

Reveal

2359
Telerik UI for Xamarin

ReverseSlideOut

2360
Telerik UI for Xamarin

SlideAlong

2361
Telerik UI for Xamarin

SlideInOnTop

2362
Telerik UI for Xamarin

ScaleUp

2363
Telerik UI for Xamarin

FadeIn

2364
Telerik UI for Xamarin

ScaleDownPusher

The default transition is SlideInOnTop. In order to change the transition type, you should set the
TransitionType property of TKSideDrawer:

C#
sideDrawer.TransitionType = TKSideDrawerTransitionType.Reveal;
 

Transition Duration

2365
Telerik UI for Xamarin

You can configure the speed of the transition setting the TransitionDuration property of
TKSideDrawer

C#
sideDrawer.TransitionDuration = 0.5f;
 

SideDrawer Transitions example can be found in our Native Xamarin.iOS examples.


 

Using Custom Transitions


You can create a custom transition by sublcassing TKSideDrawerTransition and overriding its
methods. After you create your transtion you should tell the side drawer to use this transition by
setting its TransitionManager property.

2366
Telerik UI for Xamarin

C#
MyTransition transition = new MyTransition (sideDrawer);
sideDrawer.TransitionManager = transition;
 

Here is the MyTransition implementation:

C#
public class MyTransition : TKSideDrawerTransition
{
private CGPoint sideDrawerIdentityCenter;
private CGPoint hostviewIdentityCenter;

public MyTransition(TKSideDrawer sideDrawer) : base(sideDrawer)


{
}

public override void Show ()


{
if (!this.SideDrawer.IsVisible) {
this.SideDrawer.Frame = new CGRect (0,
-this.SideDrawer.Superview.Bounds.Size.Height, this.SideDrawer.Width,
this.SideDrawer.Superview.Bounds.Size.Height);
sideDrawerIdentityCenter = this.SideDrawer.Center;
hostviewIdentityCenter = this.SideDrawer.Hostview.Center;
}

this.TransitionBegan (true);
UIView.Animate (this.SideDrawer.TransitionDuration, delegate {
this.SideDrawer.Center = new CGPoint(sideDrawerIdentityCenter.X,
sideDrawerIdentityCenter.Y + this.SideDrawer.Bounds.Size.Height);
this.SideDrawer.Hostview.Center = new CGPoint(hostviewIdentityCenter.X +
this.SideDrawer.Width, hostviewIdentityCenter.Y);
}, delegate {
this.TransitionEnded(true);
});
}

public override void Dismiss ()


{
this.TransitionBegan (false);
UIView.Animate (this.SideDrawer.TransitionDuration, delegate {
this.SideDrawer.Center = new CGPoint(this.SideDrawer.Width / 2.0,
-this.SideDrawer.Frame.Size.Height / 2.0);
this.SideDrawer.Hostview.Center = new
CGPoint(this.SideDrawer.Hostview.Superview.Bounds.Width / 2.0,
this.SideDrawer.Hostview.Superview.Bounds.Height / 2.0);
}, delegate {
this.TransitionEnded(false);
});
}

public override void TransitionBegan (bool showing)

2367
Telerik UI for Xamarin

{
if (showing) {
this.SideDrawer.Hidden = false;
this.SideDrawer.Superview.BringSubviewToFront (this.SideDrawer.Hostview);
this.SideDrawer.Hostview.UserInteractionEnabled = false;
}
}

public override void TransitionEnded (bool showing)


{
if (!showing) {
this.SideDrawer.Hidden = true;
this.SideDrawer.Hostview.UserInteractionEnabled = true;
}
}
}
 

SideDrawer Custom Transition example can be found in our Native Xamarin.iOS examples.
 

2368
Telerik UI for Xamarin

TKSideDrawer for Xamarin.iOS:


Appearance Positions
TKSideDrawer can be shown from all four sides of the screen.

In order to change the postion of TKSideDrawer, you should set its Position property of type
TKSideDrawerPosition. The available options are: Left, Right, Top and Bottom.

Default position is Left


 
C#
sideDrawer.Position = TKSideDrawerPosition.Left;
 

2369
Telerik UI for Xamarin

SideDrawer Positions example can be found in our Native Xamarin.iOS examples.


 

2370
Telerik UI for Xamarin

TKSideDrawer for Xamarin.iOS:


Customizations

TKSideDrawer allows customizing almost every aspect of its visual appearance. This article
demonstrates some of the customization techniques that can be used with it.

The most useful settings for changing the visual appearance of TKSideDrawer are grouped in its
Style property of type TelerikUI.TKSideDrawerStyle.

Styling
Here are the SideDrawer styling options:

2371
Telerik UI for Xamarin

Blur

 BlurEffect(UIKit.UIBlurEffectStyle)
 BlurTintColor(UIKit.UIColor)
 BlurType(TelerikUI.TKSideDrawerBlurType)

Note that the default transition set to TKSideDrawer is SlideInOnTop with blur enabled. If you
prefer a solid color instead, you should set the BlurType property to
TKSideDrawerBlurType.None before setting the desired Fill:

Example

C#
sideDrawer.Fill = new TKSolidFill (UIColor.Gray);
sideDrawer.Style.BlurType = TKSideDrawerBlurType.None;
 

Height

 FooterHeight(nfloat): Defines the height of the FooterView


 HeaderHeight(nfloat): Defines the height of the HeaderView
 ItemHeight(nfloat): Defienes the height of the item
 SectionHeaderHeight(nfloat): Defines the height of the header when it is selected.

Example

C#
sideDrawer.Style.HeaderHeight = 44;
 

Shadow

 ShadowMode(TelerikUI.TKSideDrawerShadowMode). Defins the mode of the shadow.


There are three options: None, HostView and SideDrawer.
 ShadowOffset(CGSize)
 ShadowOpacity(nfloat)
 ShadowRadius(nfloat)

Example

C#
sideDrawer.Style.ShadowMode = TKSideDrawerShadowMode.Hostview;
sideDrawer.Style.ShadowOffset = new CGSize (-2f, -0.5f);
sideDrawer.Style.ShadowRadius = 5;
 

There are cases when you may need to update the styles of specific TKSideDrawer items like the
text color. Or, you may need to show a separator. This can be done by adopting the

2372
Telerik UI for Xamarin

TKSideDrawerDelegate protocol and implementing its


sideDrawer:updateVisualsForItem:inSection: method.

C#
public override void UpdateVisualsForItem (TKSideDrawer sideDrawer, NSIndexPath
indexPath)
{
TKSideDrawerItem item =
sideDrawer.Sections[indexPath.Section].Items[indexPath.Item];
item.Style.ContentInsets = new UIEdgeInsets (0, -5, 0, 0);
item.Style.SeparatorColor = new TKSolidFill (UIColor.Clear);
}
 

If needed you can easily update the visual styles of the sections. This is done by implementing
TKSideDrawerDelegate method UpdateVisualsForSection:

C#
public override void UpdateVisualsForSection (TKSideDrawer sideDrawer, int
sectionIndex)
{
TKSideDrawerSection section = sideDrawer.Sections[sectionIndex];
section.Style.ContentInsets = new UIEdgeInsets (0, -15, 0, 0);
}
 

Custom content
In some scenarios you may need to use custom views for TKSideDrawer header or footer. The
TKSideDrawer properties headerView and footerView inherit from UIView allowing you to use
the view that best suit your needs.

Setting the Content property of TKSideDrawer you can easily change the content of the side
drawer. It also inherits from UIView. By default the content is TKSideDrawerTableView.

2373
Telerik UI for Xamarin

SideDrawer CustomContent example can be found in our Native Xamarin.iOS examples.


 

2374
Telerik UI for Xamarin

TKSideDrawer for Xamarin.iOS: Selection


Handling item selection in TKSideDrawer is as simple as adopting TKSideDrawerDelegate and
implementing its DidSelectItem method. Use the passed NSIndexPath to determine which item
was selected and take the appropriate action:

C#
public override void DidSelectItem (TKSideDrawer sideDrawer, NSIndexPath indexPath)
{
Console.WriteLine ("Selected item in section: {0} at index: {1}",
indexPath.Section, indexPath.Row);
}
 

2375
Telerik UI for Xamarin

TKSideDrawer for Xamarin.iOS:


SideDrawer with UINavigationController
Sometimes, you may want to use UINavigationController to navigate in your app and also have a
TKSideDrawer that slides on top of it. Such scenario can be achieved easily using
TKSideDrawerController. TKSideDrawerController is a content controller that will present your
UINavigationController and also has a SideDrawer property which is accessible from every
UIViewController you push in the stack. To set up the TKSideDrawerController, open your
AppDelegate and paste the code below inside FinishedLaunching:

C#
[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
// class-level declarations

public override UIWindow Window {


get;
set;
}

public override bool FinishedLaunching (UIApplication application, NSDictionary


launchOptions)
{
SideDrawerGettingStarted main = new SideDrawerGettingStarted ();
TKSideDrawerController sideDrawerController = new TKSideDrawerController
(main);
this.Window.RootViewController = sideDrawerController;

return true;
}

//..
}
 

In this example, SideDrawerGettingStarted is a UIViewController subclass which is the


initially displayed controller by the UINavigationController. From there on you can set up the side
drawer inside the SideDrawerController's ViewDidLoad:

C#
public class SideDrawerGettingStarted : UIViewController
{
TKSideDrawer SideDrawer;

public override void ViewDidLoad ()


{
base.ViewDidLoad ();

2376
Telerik UI for Xamarin

this.View.BackgroundColor = UIColor.Gray;

UINavigationBar navBar = new UINavigationBar (new CGRect (0, 0,


this.View.Frame.Size.Width, 64));
UINavigationItem navItem = new UINavigationItem ("Getting Started");
UIBarButtonItem showSideDrawerButton = new UIBarButtonItem ("Show",
UIBarButtonItemStyle.Plain, this, new Selector ("ShowSideDrawer"));
navItem.LeftBarButtonItem = showSideDrawerButton;
navBar.Items = new UINavigationItem[]{ navItem };
this.View.AddSubview (navBar);

this.SideDrawer = TKSideDrawer.FindSideDrawer (0, this);


TKSideDrawerSection sectionPrimary = this.SideDrawer.AddSection ("Primary");
sectionPrimary.AddItem ("Social");
sectionPrimary.AddItem ("Promotions");

TKSideDrawerSection sectionLabels = this.SideDrawer.AddSection ("Labels");


sectionLabels.AddItem ("Important");
sectionLabels.AddItem ("Starred");
sectionLabels.AddItem ("Sent Mail");
sectionLabels.AddItem ("Drafts");
}

[Export ("ShowSideDrawer")]
public void ShowSideDrawer ()
{
this.SideDrawer.Show ();
}
}
 

2377
Telerik UI for Xamarin

Overview
Thank you for choosing Telerik RadSpreadStreamProcessing!

This article briefly explains the specifics of RadSpreadStreamProcessing - what is spread streaming,
how it works compared to other libraries and when to use it.

RadSpreadStreamProcessing is part of the Telerik Document Processing libraries. The full


documentation for this component is available at
http://docs.telerik.com/devtools/document-processing/libraries/radspreadstreamsprocessing.
 

What is Spread Streaming?


Spread streaming is a document processing paradigm that allows you to create big spreadsheet
documents with great performance and minimal memory footprint.

The key for the memory efficiency is that the spread streaming library writes the spreadsheet content
directly to a stream without creating and preserving the spreadsheet document model in memory.
Each time an exporter object is disposed, the set values are written into the stream. This allows you
to create large documents with an excellent performance.

Key Features
Some of the features you can take advantage of are:

 Export to XLSX or CSV files

2378
Telerik UI for Xamarin

 Writing directly into a stream


 Grouping
 Styling and formatting cells
 Hidden rows and columns
 Freezing panes

When to Use RadSpreadStreamProcessing


You can use RadSpreadStreamProcessing to create and export large amount of data with a low
memory footprint and great performance.

Required references
In order to use the RadSpreadStreamProcessing you have to add references to the following
assemblies:

 Telerik.Zip.dll
 Telerik.Documents.SpreadsheetStreaming.dll

2379
Telerik UI for Xamarin

Overview
Have you ever wondered how to increase the responsiveness of your applications by compressing
the data that you send over the internet? With the new Zip Library you can compress data like
images, docx or pdf files and send them over the wire. Thus, you will achieve fast and secure
transactions.

This is a list with short descriptions of the top-of-the-line features of Telerik's Zip Library control:

 Easy to use API: The Zip Library exposes flexible and easy API to provide you with full
control over the compressed data.
 Load or create ZIP files: You can load data from existing ZIP files, create new ones and edit
ZIPs that can be used by other applications. You can also create ZIP files in memory or add
data to ZIP file from stream.
 Support for large files: The Zip Library works seamlessly with large files.
 Support for encryption: You can protect your ZIP file with password for better security.

Required references
Please note, that the RadZipLibrary is available only for Xamarin.iOS.
 
In order to use the Zip Library you have to add references to the following assemblies:

 Telerik.Zip.dll

RadZipLibrary is part of the Telerik Document Processing libraries. The full documentation for this
component is available at http://docs.telerik.com/devtools/document-processing/libraries/radziplibrary.
 

2380
Telerik UI for Xamarin

Blazor Mobile Bindings for Xamarin


Overview
Experimental Mobile Blazor Bindings enable developers to create native mobile apps for iOS and
Andoid using .Net and C#. The UI components and behaviors, which are based on Xamarin.Forms,
are defined using the Razor syntax. With Telerik mobile Blazor Bindings you can take full advantage
of the Telerik UI for Xamarin suite in a Mobile Blazor Bindings project.

The available controls which can be used in Mobile Blazor Bindings projects are listed in the table
below:

Controls
AutoCompleteView
Border
BusyIndicator
Button
CheckBox
DataGrid
Expander
ListView
SideDrawer

Getting Started
Let’s review the steps needed to get started with the Telerik UI for Xamarin controls in a Mobile
Blazor Bindings project.

1. Setting up the project.


Let's begin with a new Xamarin Mobile Blazor project. Visit the Getting Started article in the Microsoft
documentation. Now, we can start adding our Telerik Controls.

For a faster quick-start, visit Walkthrough: Creating your First App.


 
Please make sure you have the 0.3.26-preview release of Microsoft.MobileBlazorBindings. Telerik UI
for Xamarin Blazor controls are built and tested against it, and that's the version we currently
support.
 

2. Adding the required Telerik references

2381
Telerik UI for Xamarin

You have two options:

 Add the Telerik UI for Xamarin Blazor Nuget package following the instructions from the
Telerik Nuget package server topic.
 Add the references to Telerik assemblies manually. Each control's Getting Started article
contains a section which describes the needed Telerik assemblies.

No matter whether the Telerik UI for Xamarin Blazor assemblies are added manually or using the
Telerik NuGet server, they the references need to be added in the _Imports.razor page:
 
for example:

C#
@using Telerik.XamarinForms.Blazor.Primitives
@using Telerik.XamarinForms.Blazor.Input
@using Telerik.XamarinForms.Blazor.Common
@using Telerik.XamarinForms.Blazor.DataControls
 

RadBusyIndicator is rendered via the SkiaSharp graphics library so you need to install ,
RadDataGrid is renderer for Android via the SkiaSharp graphics library, so you need to install also
SkiaSharp.Views.Forms in the .NET Standard and Android projects.
 

2382
Telerik UI for Xamarin

Overview
Telerik AutoCompleteView for Xamarin Mobile Blazor Bindings can automatically complete user
input string by comparing the text being entered to all strings in the associated data source. The
control has a number of advanced features such as different filtering options, tokens support, clear
button and customization options.

Figure 1: RadAutoCompleteView Overview

Key features
Tokens Support
With RadAutoCompleteView you can enable users to search for and select several items in one
control. These items appear as tokens that can easily be deselected using their close button.

DisplayMode ( of type SuggestionsDisplayMode) property determines whether a single or multiple


selection is enabled. The default DisplayMode is "Plain", for multiple selection you would need to set
it to "Tokens".

<RadAutoCompleteView ItemsSource="@AcvItemSource"
TextSearchPath="Name"
BackgroundColor="Color.White"

DisplayMode="Telerik.XamarinForms.Input.AutoComplete.SuggestionsDisplayMode.Tokens" />
 

2383
Telerik UI for Xamarin

Filtering Options
Through the CompletionMode property (of type CompletionMode) you can define the filtering
behavior to display all the matches that either "StartsWith" (default) or "Contains" the typed symbols.

<RadAutoCompleteView ItemsSource="@AcvItemSource"
TextSearchPath="Name"

CompletionMode="Telerik.XamarinForms.Input.AutoComplete.CompletionMode.Contains" />
 

Watermark
Watermark property is used to give guidance to the end user on what should be entered in the text
input. The watermark text is displayed when the control is empty. You can also use the
WatermarkTextColor property to define the Watermark text color of the component.

<RadAutoCompleteView ItemsSource="@AcvItemSource"
TextSearchPath="Name"
Watermark="Enter name..."
WatermarkTextColor="Color.LightBlue" />
 

NoResults Message
NoResults message appears in the popup used for the list of suggestions whenever the control
cannot find any matching items. You can modify the message text through NoResultsMessage
property:

<RadAutoCompleteView ItemsSource="@AcvItemSource"
TextSearchPath="Name"
NoResultsMessage="there are no matching items..." />
 

2384
Telerik UI for Xamarin

Clear Button Visibility


The Clear button, which appears at the right side of the input field when the AutoCompleteView is on
focus, gives the end-user the option to quickly clear the entered values. You could control the
visibility of the button through the IsClearButtonVisible property.

<RadAutoCompleteView ItemsSource="@AcvItemSource"
TextSearchPath="Name"
IsClearButtonVisible="true" />
 

Search Threshold
By default the search is triggered as soon as the user types into the input field. By using
SearchThreshold you can configure AutoCompleteView to trigger the search after a certain number
of letters is entered.

<RadAutoCompleteView ItemsSource="@AcvItemSource"
TextSearchPath="Name"
SearchThreshold="3" />
 

Show/Hide SuggestionView
You can control the visibility of the popup containing the search results of the AutoCompleteView
through ShowSuggestionView property. In addition, through the SuggestionViewHeight and
SuggestionViewBackgroundColor properties you can customize the visual appearance of the popup.

<RadAutoCompleteView ItemsSource="@AcvItemSource"
TextSearchPath="Name"
ShowSuggestionView="true"
SuggestionViewHeight="100"
SuggestionViewBackgroundColor="Color.LightBlue" />
 

See Also
 Getting Started

2385
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadAutoCompleteView control in
your application.

 Setting up the app


 Adding the required Telerik references
 Adding RadAutoCompleteView control

1. Setting up the app


Take a look at the Getting Started article how to setup the Telerik Blazor Mobile Bindings for Xamarin
project.

2. Adding the required Telerik references


You have two options:

 Add the Telerik.UI.for.Xamarin.Blazor Nuget package following the instructions in Telerik


NuGet package server topic.
 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadAutoCompleteView component:

Platform Assemblies
Portable Telerik.XamarinForms.Blazor.Input.dll
Telerik.XamarinForms.Input.dll
Android Telerik.Xamarin.Android.Input.dll
Telerik.XamarinForms.Input.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Input.dll
After that we need to add the Telerik.XamarinForms.Blazor.Input in our _Imports.razor page:

C#
@using Telerik.XamarinForms.Blazor.Input;
 

3. Adding RadAutoCompleteView control


<ContentView>
<StackLayout>
<RadAutoCompleteView ItemsSource="@AcvItemSource"
Watermark="Search here..." />
</StackLayout>
</ContentView>

2386
Telerik UI for Xamarin

@code
{
public List<string> AcvItemSource { get; set; }

protected override void OnInitialized()


{
base.OnInitialized();

this.AcvItemSource = new List<string>()


{
"Freda Curtis",
"Jeffery Francis",
"Eva Lawson",
"Emmett Santos",
"Theresa Bryan",
"Jenny Fuller",
"Terrell Norris",
"Eric Wheeler",
"Julius Clayton",
"Alfredo Thornton",
"Roberto Romero",
"Orlando Mathis",
"Eduardo Thomas",
"Harry Douglas"
};
}
}
 

Here is the result:

See Also
 Xamarin Mobile Blazor Bindings Overview

2387
Telerik UI for Xamarin

Border for Xamarin Mobile Blazor Bindings


With the new Telerik Border for Xamarin Mobile Blazor Bindings component you will have full control
over the look & feel of the border that wraps around your blazor component/view. You could
surround any view such as Label, Image, and other, and specify different border thickness and
corner radius on each side.

Figure 1: RadBorder Overview

Key features
 BorderThickness and BorderColor: RadBorder provides a BorderThickness property which
you can use together with BorderColor in order to have various types of borders around your
views.

<RadBorder BorderColor="@Color.FromHex("#4488F6")"
BorderThickness="new Thickness(5)"
HeightRequest="100">
<Label Text="Hello there!"
Margin="new Thickness(2)" />
</RadBorder>
 

 Defining different corner radius on each side: Through the CornerRadius property you could
specify separate corner radius value on all four angles of RadBorder.

2388
Telerik UI for Xamarin

<RadBorder BorderColor="@Color.FromHex("#4488F6")"
CornerRadius="new Thickness(5)"
HeightRequest="100">
<Label Text="Hello there!"
Margin="new Thickness(2)" />
</RadBorder>
 

Here is the result:

See Also
 Getting Started

2389
Telerik UI for Xamarin

Getting Started with Border for Xamarin


Mobile Blazor Bindings
This article will guide you through the steps needed to add a basic RadBorder control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadBorder control

1. Setting up the app


Take a look at the Getting Started article how to setup the Telerik Blazor Mobile Bindings for Xamarin
project.

2. Adding the required Telerik references


You have two options:

 Add the Telerik.UI.for.Xamarin.Blazor Nuget package following the instructions in Telerik


NuGet package server topic.
 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadBorder component:

Platform Assemblies
Portable Telerik.XamarinForms.Blazor.Primitives.dll
Telerik.XamarinForms.Primitives.dll
Android Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Primitives.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Primitives.dll
After that we need to add the Telerik.XamarinForms.Blazor.Primitives in our _Imports.razor page:

C#
@using Telerik.XamarinForms.Blazor.Primitives;
 

3. Adding RadBorder control


<RadBorder BorderColor="@Color.FromHex("#4488F6")"
CornerRadius="new Thickness(5)"
HeightRequest="100">

2390
Telerik UI for Xamarin

<Label Text="Hello there!"


Margin="new Thickness(2)" />
</RadBorder>
 

Here is the result:

See Also
 Xamarin Mobile Blazor Bindings Overview

2391
Telerik UI for Xamarin

BusyIndicator for Xamarin Mobile Blazor


Bindings
Telerik BusyIndicator for Xamarin Mobile Blazor Bindings allows you to display a notification
whenever a longer-running process is being handled by the application. This makes the UI more
informative and the user experience smoother.

Figure 1: RadBusyIndicator Overview

Key features
Built-in Animations
The busy indicator component provides few built-in animations which you can use. RadBusyIndicator
provides a set of built-in animations which you can use. They can be changed via the

2392
Telerik UI for Xamarin

AnimationType property.

The property is an enum called AnimationType and it accepts values named Animation1 to
Animation10. Animation1, Animation2, Animation3, etc. to Animation10. Animation1 is the
default one.

 Changing animation size and color: You can set the size of the animation content, which is
the animated element. This can be done via the AnimationContentWidthRequest and
AnimationContentHeightRequest properties. By default the size of the default animation
content is 25x25 pixels.

You can also change the color of the animation with the AnimationContentColor property.

The snippet below shows how you can configure the predefined animations of RadBusyIndicator:

<RadBusyIndicator AnimationContentHeightRequest="100"
AnimationContentWidthRequest="100"
AnimationType="Telerik.XamarinForms.Primitives.AnimationType.Animation2"
AnimationContentColor="Color.Blue"
IsBusy="true"/>
 

and the result:

2393
Telerik UI for Xamarin

BusyContent
Content which is displayed when the IsBusy it false:

<RadBusyIndicator AnimationContentHeightRequest="100"
AnimationContentWidthRequest="100"
IsBusy="false">
<Content>
<Telerik.XamarinForms.Blazor.Primitives.BusyIndicator.Content>
<Label Text="This is the content of the RadBusyIndicator control displayed when
the indicator is not busy." />
</Telerik.XamarinForms.Blazor.Primitives.BusyIndicator.Content>
</Content>
</RadBusyIndicator>
 

and the result:

2394
Telerik UI for Xamarin

Custom Busy Content


Setting BusyContent property of RadBusyIndicator allows you to display any content together with
the built-in animations while the control is in Busy state.

<RadBusyIndicator AnimationContentHeightRequest="100"
AnimationContentWidthRequest="100"
AnimationType="Telerik.XamarinForms.Primitives.AnimationType.Animation6"
IsBusy="true">
<BusyContent>
<Telerik.XamarinForms.Blazor.Primitives.BusyIndicator.BusyContent>
<Label Text="This is the content of the RadBusyIndicator control displayed when
the indicator is not busy." />
</Telerik.XamarinForms.Blazor.Primitives.BusyIndicator.BusyContent>
</BusyContent>
</RadBusyIndicator>
 

and the result:

2395
Telerik UI for Xamarin

See Also
 Getting Started

2396
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadBusyIndicator control in your
application.

1. Setting up the app


Take a look at the Getting Started article how to setup the Telerik Blazor Mobile Bindings for Xamarin
project.

2. Adding the required Telerik references


Let’s add the RadBusyIndicator to the project. To do this, we'll need to add the Telerik references
that the RadBusyIndicator requires.

You have two options:

 Add the Telerik.UI.for.Xamarin.Blazor Nuget package following the instructions from the
Telerik Nuget package server topic.
 Add the references to Telerik assemblies manually, check the list bellow with the required
assemblies for RadBusyIndicator component:

Platform Assemblies
Portable Telerik.XamarinForms.Blazor.Primitives.dll
Telerik.XamarinForms.Primitives.dll
Android Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.SkiaSharp.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.SkiaSharp.dll
After that we need to add the Telerik.XamarinForms.Blazor.Primitives in our _Imports.razor page:

C#
@using Telerik.XamarinForms.Blazor.Primitives;
 

RadBusyIndicator is rendered via the SkiaSharp graphics library so you need to install also
SkiaSharp.Views.Forms in all projects of the xamarin solution (.NET Standard, Android, iOS).
 

3. Adding RadBusyIndicator control

2397
Telerik UI for Xamarin

The busy indicator is a layout control that can display two views depending on its current state - busy
and not-busy. You can define the state of the control via its IsBusy property. The default value is
False and the control's normal content is displayed. If you change it to True, the busy content is
displayed, which by default is a spinning balls animation. Check the Animations article to see the
built-in animations, how to change them and how to us a custom animation.

<RadBusyIndicator AnimationContentHeightRequest="100"
AnimationContentWidthRequest="100"
IsBusy="true">
<Content>
<Telerik.XamarinForms.Blazor.Primitives.BusyIndicator.Content>
<Label Text="This is the content of the RadBusyIndicator control displayed when
the indicator is not busy." />
</Telerik.XamarinForms.Blazor.Primitives.BusyIndicator.Content>
</Content>
</RadBusyIndicator>
 

And the result when RadBusyIndicator IsBusy is True

2398
Telerik UI for Xamarin

See Also

 Xamarin Mobile Blazor Bindings Overview

2399
Telerik UI for Xamarin

Button for Xamarin Mobile Blazor Bindings


Telerik Button for Xamarin Mobile Blazor Bindings is a button control with includes the followiong
feartures that allows you to add borders, transparency, text alignment, backgrounds and images.

Key features
 Content alignment options: With RadButton you will be able to apply different horizontal and
vertical positioning of its content.

<RadButton Text="Text"
HorizontalContentAlignment="Xamarin.Forms.TextAlignment.Center"
VerticalContentAlignment="Xamarin.Forms.TextAlignment.Center" />
 

 Setting Border Thickness: RadButton provides a BorderThickness property which you can
use together with BorderColor in order to have various types of borders around your
buttons.

<RadButton Text="Click me!"


BorderThickness="new Thickness(6, 2, 2, 6)"
BorderColor="@Color.FromHex("#4488F6")" />
 

and the result:

2400
Telerik UI for Xamarin

 Setting Background Image: You can customize the appearance of RadButton by applying am
image as its background.

<RadButton Text="Click me!"


BackgroundImage="@(new FileImageSource { File = "image.png" })" />
 

You can also use the ImageSource property.

<RadButton Text="Click me!"


ImageSource="@(new FileImageSource { File = "image.png" })" />
 

Check out RadButton Getting Started help article that shows how to use it in a basic scenario.
 

See Also
 Getting Started

2401
Telerik UI for Xamarin

Getting Started with Button for Xamarin


Mobile Blazor Bindings
This article will guide you through the steps needed to add a basic RadButton control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadButton control

1. Setting up the app


Take a look at the Getting Started article how to setup the Telerik Blazor Mobile Bindings for Xamarin
project.

2. Adding the required Telerik references


You have two options:

 Add the Telerik.UI.for.Xamarin.Blazor Nuget package following the instructions in Telerik


NuGet package server topic.
 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadButton component:

Platform Assemblies
Portable Telerik.XamarinForms.Blazor.Input.dll
Telerik.XamarinForms.Input.dll
Android Telerik.Xamarin.Android.Input.dll
Telerik.XamarinForms.Input.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Input.dll
After that we need to add the Telerik.XamarinForms.Blazor.Primitives in our _Imports.razor page:

C#
@using Telerik.XamarinForms.Blazor.Primitives;
 

3. Adding RadButton control


<ContentView>
<StackLayout WidthRequest="200"
VerticalOptions="LayoutOptions.Center"

2402
Telerik UI for Xamarin

HorizontalOptions="LayoutOptions.CenterAndExpand">
<RadButton Text="Click me!"
BorderThickness="new Thickness(2)"
BorderColor="@Color.FromHex("4488F6")"
OnClick="@ButtonOnClick" />
</StackLayout>
</ContentView>

@code
{
private void ButtonOnClick()
{

}
}
 

Here is the result:

See Also
 Xamarin Mobile Blazor Bindings Overview

2403
Telerik UI for Xamarin

CheckBox for Xamarin Mobile Blazor


Bindings
Telerik CheckBox for Xamarin Mobile Blazor Bindings is a checkbox control which enables users to
make a choice between three mutually exclusive options (checked, unchecked and indeterminate
states). The user’s selection is indicated by a check mark, and when a user clicks the checkbox its
appearance and state change.

Figure 1: RadCheckBox Overview

Key features
Indeterminate state support
RadCheckBox provides an additional indeterminate state which indicates the control is neither
checked nor unchecked. You will need to set IsThreeState property to true:

<RadCheckBox IsThreeState="true"/>
 

and the result:

Color customization
RadCheckBox exposes a few useful Color properties for customizing its visual appearance. You
could set the color of the check mark as well as the control itself in each of the available states.

 Background/Border Colors
 CheckedColor: Defines the Color applied to the control when it is checked. This is both
the border and background color.

2404
Telerik UI for Xamarin

 UncheckedColor: Defines the Color applied to the control when it is unchecked. This is
the border color only, the background is transparent when unchecked.
 IndeterminateColor: Defines the Color applied to the control when it is in Indeterminate
state. This is both the border and background color.
 Symbol Colors
 CheckedSymbolColor: Defines the Color applied to the check symbol of the control when
it is in Checked state.
 IndeterminateSymbolColor: Defines the Color applied to the Indeterminate symbol of the
control.

Example

Here is a sample checkbox definition with the above properties applied:

<StackLayout>
<Label Text="CheckedColor" />
<RadCheckBox CheckedColor="Color.Aqua" />
<Label Text="CheckedSymbolColor" />
<RadCheckBox CheckedSymbolColor="Color.Black" />
<Label Text="IndeterminateColor and IndeterminateSymbolColor" />
<RadCheckBox IndeterminateColor="Color.Brown"
IndeterminateSymbolColor="Color.Coral"
IsThreeState="true"/>
<Label Text="UncheckedColor" />
<RadCheckBox UncheckedColor="Color.DarkBlue" />
</StackLayout>
 

and the result:

2405
Telerik UI for Xamarin

Stroke Width customization


The RadCheckBox control exposes a StrokeWidth property that specifies the width of the lines with
which the Checkbox element is drawn. It affects the border of the control as well as the check mark.

Here is an example how you can apply a StrokeWidth value:

<RadCheckBox StrokeWidth="5" />


 

and the result:

Different sizes

2406
Telerik UI for Xamarin

The width and height of the checkbox is controlled through the Length property and maintains a 1:1
aspect ratio.

Here is an example of setting the Length value:

<RadCheckBox StrokeWidth="5"
Length="40" />
 

and the result:

See Also
 Getting Started

2407
Telerik UI for Xamarin

Getting Started with CheckBox for Xamarin


Mobile Blazor Bindings
This article will guide you through the steps needed to add a basic RadCheckBox control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadCheckBox control

1. Setting up the app


Take a look at the Getting Started article how to setup the Telerik Blazor Mobile Bindings for Xamarin
project.

2. Adding the required Telerik references


You have two options:

 Add the Telerik.UI.for.Xamarin.Blazor Nuget package following the instructions from the
Telerik Nuget package server topic.
 Add the references to Telerik assemblies manually, check the list bellow with the required
assemblies for RadCheckBox component:

Platform Assemblies
Portable Telerik.XamarinForms.Blazor.Primitives.dll
Telerik.XamarinForms.Primitives.dll
Android Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Primitives.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Primitives.dll

3. Adding RadCheckBox control


RadCheckbox definition:

<ContentView>
<StackLayout>
<RadCheckBox IsChecked="@IsChecked"
IsCheckedChanged="@OnCheckedChanged" />
<Label Text="@IsCheckBoxChecked" />
</StackLayout>
</ContentView>

2408
Telerik UI for Xamarin

@code
{
public string IsCheckBoxChecked { get; set; }
public bool IsChecked { get; set; }

protected override void OnInitialized()


{
base.OnInitialized();

this.IsChecked = false;
this.IsCheckBoxChecked = this.IsChecked.ToString();
}

private void OnCheckedChanged(CheckBox.IsCheckedChangedEventArgs args)


{
this.IsCheckBoxChecked = args.NewValue.ToString();
}
}
 

Here is the result:

2409
Telerik UI for Xamarin

See Also
 Xamarin Mobile Blazor Bindings Overview

2410
Telerik UI for Xamarin

RadDataGrid for Xamarin Mobile Blazor


Bindings
Most of the data on the Internet is stored in tables within a database. DataGrid for Xamarin Mobile
Blazor Bindings provides the same abstraction over the data – it has Columns and Rows and the
intersection of a Row and a Column is called a Cell. When the data from a database is sent to the
client, it is usually converted to a Business object (or the so-called ViewModel) where each instance
represents a Table Row and each property of the object represents a Column within the original
table.

2411
Telerik UI for Xamarin

Key features
Below are describes the main features of the DataGrid control.

Different Column Types


RadDataGrid provides plenty of built-in columns such as Text, Boolean, Numeric, Picket, DateTime.

2412
Telerik UI for Xamarin

These pre-defined templates allow for handling different data types and user scenarios, each with its
specific editor.

Example
Here is an example with RadDataGrid Columns:

<Grid>
<Layout>
<RowDefinition GridUnitType="GridUnitType.Star" />
</Layout>
<Contents>
<GridCell>
<RadDataGrid ItemsSource="@Clubs"
AutoGenerateColumns="false">
<Columns>
<DataGridTextColumn PropertyName="Name"
HeaderText="Name">
<CellContentStyle>
<DataGridTextCellStyle TextColor="Color.Green"
FontSize="15"
SelectedTextColor="Color.Orange" />
</CellContentStyle>
</DataGridTextColumn>
<DataGridNumericalColumn PropertyName="StadiumCapacity"
HeaderText="Stadium Capacity"
CanUserFilter="false"/>
<DataGridBooleanColumn PropertyName="IsChampion"
HeaderText="Champion?"
CanUserEdit="false"/>
<DataGridDateColumn PropertyName="Established"
HeaderText="Date Established"
CanUserGroup="false"/>
<DataGridPickerColumn PropertyName="Country"
HeaderText="Country"
ItemsSourcePath="Countries" />
<DataGridTimeColumn PropertyName="Time"
HeaderText="Time Column"
CanUserSort="false"/>
</Columns>
</RadDataGrid>
</GridCell>
</Contents>
</Grid>

@code
{
public ObservableCollection<Club> Clubs { get; set; }

protected override void OnInitialized()


{
base.OnInitialized();

2413
Telerik UI for Xamarin

this.Clubs = new ObservableCollection<Club>


{
new Club("UK Liverpool ", new DateTime(1892, 1, 1), new DateTime(2018, 2, 22,
3, 28, 33), 45362, "England"),
new Club("Manchester Utd.", new DateTime(1878, 1, 1), new DateTime(2018, 1, 1,
2, 56, 44), 76212, "England") { IsChampion = true },
new Club("Chelsea", new DateTime(1905, 1, 1), new DateTime(2018, 6, 17, 6, 19,
59), 42055, "England"),
new Club("Barcelona", new DateTime(1899, 1, 1), new DateTime(2018, 7, 12, 12,
25, 31), 99354, "Spain")
};
}
}

and the result:

Editing

2414
Telerik UI for Xamarin

RadDataGrid provides a built-in editing functionality, which allows the app users to easily edit the
data presented in the grid. Depending on the column data type, a relevant editor allows end users to
edit content in a friendly environment.

You would need to define the UserEditMode property of the DataGrid control in order to enable the
editing feature.

UserEditMode property is type of Telerik.XamarinForms.DataGrid.DataGridUserEditMode


and accepts the following values:

 None - Editing is disabled (by default);


 Cell - Used to enable the editing option.

In addition, you could disable editing for concrete columns separately through the CanUserEdit
property of the DataGridColumn class.

Check the above Column example how the CanUserEdit property is set.

Sorting
RadDataGrid provides you with a built-in sorting functionality, which allows the user to easily order
the view of the data the control represents. Sorting the control is possible both through the UI.

In addition, you could disable sorting for concrete columns separately through the CanUserSort
property of the DataGridColumn class.

Check the above Column example how the CanUserSort property is set.

Filtering
You can filter the DataGrid using the Filterin UI. The Filtering UI is opened when tapping on the ...
(three dots - Options Button) positioned inside the DataGrid header.

You can set three different filter modes for the datagrid control using the UserFilterMode property.
The property is of type Telerik.XamarinForms.DataGrid.DataGridUserFilterMode. The
available options are: Auto, Enabled and Disabled.

In addition, you could disable editing for concrete columns separately through the CanUserFilter
property of the DataGridColumn class.

Check the above Column example how the CanUserFilter property is set.

Grouping
You can group the DataGrid using the Filterin UI. The Filtering UI is opened when tapping on the ...
(three dots - Options Button) positioned inside the DataGrid header.

2415
Telerik UI for Xamarin

You can set three different group modes for the datagrid control using the UserGroupMode property.
The property is of type Telerik.XamarinForms.DataGrid.DataGridUserGroupMode. The
available options are: Auto, Enabled and Disabled.

In addition, you could disable editing for concrete columns separately through the CanUserGroup
property of the DataGridColumn class.

Check out RadDataGrid Getting Started help article that shows how to use it in a basic scenario.
 

See Also
 Getting Started

2416
Telerik UI for Xamarin

Getting Started with DataGrid for Xamarin


Moile Blazor Bindings
This article will guide you through the steps needed to add a basic RadDataGrid control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadDataGrid control

1. Setting up the app


Take a look at the Getting Started article how to setup the Telerik Blazor Mobile Bindings for Xamarin
project.

2. Adding the required Telerik references


You have two options:

 Add the Telerik.UI.for.Xamarin.Blazor Nuget package following the instructions in Telerik


NuGet package server topic.
 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadDataGrid component:

Platform Assemblies
Portable Telerik.XamarinForms.Blazor.DataControls.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataGrid.dll
Telerik.XamarinForms.SkiaSharp.dll
Android Telerik.Xamarin.Android.Common.dll
Telerik.Xamarin.Android.Data.dll
Telerik.Xamarin.Android.Input.dll
Telerik.Xamarin.Android.List.dll
Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.DataGrid.dll
Telerik.XamarinForms.Input.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.SkiaSharp.dll
iOS Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataGrid.dll
Telerik.XamarinForms.SkiaSharp.dll
RadDataGrid is rendered via the SkiaSharp graphics library so you need to install also SkiaSharp

2417
Telerik UI for Xamarin

and SkiaSharp.Views.Forms in all projects of the Xamarin solution (portable, android, ios, etc).
 

3. Adding RadDataGrid control


Example
here is a sample DataGrid definition:

<Grid>
<Layout>
<RowDefinition GridUnitType="GridUnitType.Star" />
</Layout>
<Contents>
<GridCell>
<RadDataGrid ItemsSource="@ItemSource"
UserGroupMode="Telerik.XamarinForms.DataGrid.DataGridUserGroupMode.Auto"
UserEditMode="Telerik.XamarinForms.DataGrid.DataGridUserEditMode.Cell"
UserFilterMode="Telerik.XamarinForms.DataGrid.DataGridUserFilterMode.Auto"/>
</GridCell>
</Contents>
</Grid>

@code
{
public ObservableCollection<Data> ItemSource { get; set; }

protected override void OnInitialized()


{
base.OnInitialized();

this.ItemSource = new ObservableCollection<Data>


{
new Data { Country = "India", Capital = "New Delhi" },
new Data { Country = "South Africa", Capital = "Cape Town" },
new Data { Country = "Nigeria", Capital = "Abuja" },
new Data { Country = "Singapore", Capital = "Singapore" }
};
}
}
 

and the Data model used:

public class Data


{
public string Country { get; set; }

public string Capital { get; set; }


}
 

2418
Telerik UI for Xamarin

Here is the result:

See Also
 Xamarin Mobile Blazor Bindings Overview

2419
Telerik UI for Xamarin

Overview
Telerik Expander for Xamarin Mobile Blazor Bindings helps you save screen space by presenting
content in an expandable container that can be easily expanded/collapsed by tapping on the header
of the control.

Figure 1: Expander Overview

Key features
Collapsed/expanded States
RadExpander provides an expandable container which can host any content. You can show or hide
this content by interacting with the Header of the control. The default state of RadExpander is
collapsed.

You can use IsExpanded Boolean property to switch the current state of the control.

Expander Header
You can either apply HeaderText property or use the ExpanderHeader content control which
provides a set of useful properties for customizing the way the header looks. In addition, you can
place the Header at the top or at the bottom of the expandable container through HeaderLocation
property of type ExpanderHeaderLocation:

<RadExpander
HeaderLocation="Telerik.XamarinForms.Primitives.ExpanderHeaderLocation.Bottom">
<ExpanderHeader>
<Telerik.XamarinForms.Blazor.Primitives.Expander.ExpanderHeader.ExpanderHeader
BackgroundColor="Color.LightSalmon"
BorderColor="Color.Blue"
BorderThickness="2">
<Label Text="More Options" />

</Telerik.XamarinForms.Blazor.Primitives.Expander.ExpanderHeader.ExpanderHeader>
</ExpanderHeader>
<ExpanderContent>
<Telerik.XamarinForms.Blazor.Primitives.Expander.ExpanderContent>
<StackLayout Margin="new Thickness(10, 20, 10, 20)">

2420
Telerik UI for Xamarin

<StackLayout Orientation="StackOrientation.Horizontal"
Spacing="10">
<RadCheckBox />
<Label Text="Make my profile private" />
</StackLayout>
<StackLayout Orientation="StackOrientation.Horizontal"
Spacing="10">
<RadCheckBox />
<Label Text="Only show my posts to people who follow me" />
</StackLayout>
</StackLayout>
</Telerik.XamarinForms.Blazor.Primitives.Expander.ExpanderContent>
</ExpanderContent>
</RadExpander>
 

Animation while expanding/collapsing


To enable or disable the animation you need to use the IsAnimationEnabled property of
RadExpander. By default, the aimation is enabled.

You can also customize the duration and easing (acceleration over time) through
AnimationDuration(in ms) and AnimationEasing (of type Xamarin.Forms.Easing). properties.

Border Styling
RadExpander exposes BorderColor and BorderThickness properties which can help customize
the control visual appearance:

<RadExpander HeaderText="More options"


BorderColor="Color.LightBlue"
BorderThickness="3">
<ExpanderContent>
<Telerik.XamarinForms.Blazor.Primitives.Expander.ExpanderContent>
<StackLayout Margin="new Thickness(10, 20, 10, 20)">
<Label Text="You could apply BorderColor and BorderThickness properties of
RadExpander to make it consistent with the design of your app." />
</StackLayout>
</Telerik.XamarinForms.Blazor.Primitives.Expander.ExpanderContent>
</ExpanderContent>
</RadExpander>
 

2421
Telerik UI for Xamarin

See Also
 Getting Started

2422
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadExpander control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadExpander control

1. Setting up the app


Take a look at the Getting Started article how to setup the Telerik Blazor Mobile Bindings for Xamarin
project.

2. Adding the required Telerik references


You have two options:

 Add the Telerik.UI.for.Xamarin.Blazor Nuget package following the instructions in Telerik


NuGet package server topic.
 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadExpander component:

Platform Assemblies
Portable Telerik.XamarinForms.Blazor.Primitives.dll
Telerik.XamarinForms.Primitives.dll
Android Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Primitives.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Primitives.dll
After that we need to add the Telerik.XamarinForms.Blazor.Primitives in our _Imports.razor page:

C#
@using Telerik.XamarinForms.Blazor.Primitives;
 

3. Adding RadExpander control


<ContentView>
<RadExpander HeaderText="More options">
<ExpanderContent>
<Telerik.XamarinForms.Blazor.Primitives.Expander.ExpanderContent>
<StackLayout Margin="new Thickness(10, 20, 10, 20)">
<StackLayout Orientation="StackOrientation.Horizontal"

2423
Telerik UI for Xamarin

Spacing="10">
<RadCheckBox />
<Label Text="Make my profile private" />
</StackLayout>
<StackLayout Orientation="StackOrientation.Horizontal"
Spacing="10">
<RadCheckBox />
<Label Text="Only show my posts to people who follow me" />
</StackLayout>
</StackLayout>
</Telerik.XamarinForms.Blazor.Primitives.Expander.ExpanderContent>
</ExpanderContent>
</RadExpander>
</ContentView>
 

Here is the result:

See Also
 Xamarin Mobile Blazor Bindings Overview

2424
Telerik UI for Xamarin

Overview
Telerik ListView for Xamarin Mobile Blazor Bindings is a virtualized list component that presents lists
of data. It is quite useful in scenarios that require scrolling and manipulation of the items. The control
is easy to use and packed with everything you may need from a ListView component – data binding,
load on demand, filtering, grouping, sorting, customizable items, linear and grid layouts, item swipe
and reordering, various selection options and more.

Figure 1: ListView Overview

Key features
Selection
RadListView supports both single and multiple selection, additionally items can be selected on tap or
on hold gestures.

<RadListView ItemsSource="@Source"

SelectionMode="Telerik.XamarinForms.DataControls.ListView.SelectionMode.Multiple"

SelectionGesture="Telerik.XamarinForms.DataControls.ListView.SelectionGesture.Tap" />
 

2425
Telerik UI for Xamarin

Different layouts and orientation


You can choose between linear and grid layout as well as define the scroll direction of the layout.

<RadListView ItemsSource="@Source">
<LayoutDefinition>
<Telerik.XamarinForms.Blazor.DataControls.ListView.ListViewGridLayout
SpanCount="2"
ItemLength="40"
HorizontalItemSpacing="5"
VerticalItemSpacing="5" />
</LayoutDefinition>
</RadListView>
 

Reorder Items
You can allow the end-users to reorder ListView items using drag and drop through
IsItemsReorderEnabled property.

<RadListView ItemsSource="@Source"
IsItemsReorderEnabled="true" />
 

Load on demand

2426
Telerik UI for Xamarin

In addition to the built-in UI virtualization, the control supports load-on-demand. This optimizes the
initial loading of the app and the new items are loaded when requested - you can choose between
Automatic (items are loaded when user scrolls near the end of the listview) or Manual (a button is
rendered, when tapped, items a re loaded) load on demand mode:

<ContentView>
<RadListView ItemsSource="@Source"
IsLoadOnDemandEnabled="true"
LoadOnDemandMode="Telerik.XamarinForms.Common.LoadOnDemandMode.Manual"
OnLoadOnDemand="@LoadOndemandClicked"/>
</ContentView>

@code
{
public ObservableCollection<string> Source { get; set; }

protected override void OnInitialized()


{
base.OnInitialized();

this.Source = new ObservableCollection<string>()


{
"Tom",
"Anna",
"Peter",
"Teodor",
"Lorenzo",
"Andrea",
"Martin"
};
}

protected void LoadOndemandClicked()


{
for(int i=0; i<5; i++)
{
this.Source.Add(String.Format("New item {0}", i));
}
}
}
 

2427
Telerik UI for Xamarin

Grouping, sorting and filtering


You can easily visualize your items in groups, sorted and filtered in accordance with your criteria -
just need to add the needed property descriptor to the GroupDescriptors, SortDescriptors or
FilterDescriptors collections of the ListView, respectively.

Customizable Items
RadListView provides styling mechanism for customizing the look of its items. This mechanism
consists of the following properties of type ListViewItemStyle:

 ItemStyle
 SelectedItemStyle
 PressedItemStyle
 ReorderItemStyle

<RadListView ItemsSource="@Source">
<ItemStyle>
<Telerik.XamarinForms.Blazor.DataControls.ListView.ListViewItemStyle
BackgroundColor="Color.Aquamarine"
TextCellTextColor="Color.DarkBlue"
BorderColor="Color.Blue"
BorderWidth="2" />

2428
Telerik UI for Xamarin

</ItemStyle>
</RadListView>
 

See Also
 Getting Started

2429
Telerik UI for Xamarin

Getting Started
This article will guide you through the steps needed to add a basic RadListView control in your
application.

 Setting up the app


 Adding the required Telerik references
 Adding RadListView control

1. Setting up the app


Take a look at the Getting Started article how to setup the Telerik Blazor Mobile Bindings for Xamarin
project.

2. Adding the required Telerik references


You have two options:

 Add the Telerik.UI.for.Xamarin.Blazor Nuget package following the instructions in Telerik


NuGet package server topic.
 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadListView component:

Platform Assemblies
Portable Telerik.XamarinForms.Blazor.DataControls.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.SkiSharp.dll
Android Telerik.Xamarin.Android.Common.dll
Telerik.Xamarin.Android.Data.dll
Telerik.Xamarin.Android.Input.dll
Telerik.Xamarin.Android.List.dll
Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.SkiSharp.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.DataControls.dll
Telerik.XamarinForms.Primitives.dll
Telerik.XamarinForms.SkiSharp.dll
After that we need to add the Telerik.XamarinForms.Blazor.DataControls in our _Imports.razor
page:

2430
Telerik UI for Xamarin

C#
@using Telerik.XamarinForms.Blazor.DataControls;
 

3. Adding RadListView control


<ContentView>
<RadListView ItemsSource="@Source" />
</ContentView>

@code
{
public List<string> Source { get; set; }

protected override void OnInitialized()


{
base.OnInitialized();

this.Source = new List<string>()


{
"Tom",
"Anna",
"Peter",
"Teodor",
"Lorenzo",
"Andrea",
"Martin"
};
}
}
 

Here is the result:

See Also

2431
Telerik UI for Xamarin

 Xamarin Mobile Blazor Bindings Overview

2432
Telerik UI for Xamarin

SideDrawer for Xamarin Mobile Blazor


Bindings
RadSideDrawer for Xamarin Mobile Blazor Bindings is designed to enable users to visualize a
hidden view in their applications. That view can host navigation UI, common settings or any other UI
of your choice. It can be visualized using a flick gesture and can be shown from all four sides of the
screen.

Figure 1: RadSideDrawer Overview

Key features
Below you can find the SideDrawer keyfeatures described:

Drawer positions

2433
Telerik UI for Xamarin

The drawer can be shown from any of the four edges of the screen. You can define its position
through the DrawerLocation property. For more details on this read Properties topic.

RadSideDrawer control exposes the following properties:

 DrawerContent: Specifies the drawer (initially hidden) content.


 MainContent: Specifies the (initially visible) content of the component.
 IsOpen (bool): Specifies a value indicating if the drawer content is visible.
 DrawerLength (double): Defines how much the drawer content should be extended over the
main content in opened position.
 DrawerLocation (Telerik.XamarinForms.Primitives.SideDrawer.SideDrawerLocation):
Specifies the location from which the drawer will be opened. The following options are
available:
 Left
 Right
 Top
 Bottom
 AreGesturesEnabled (bool): Specifies ability for gestures to open and close the drawer.
 TouchTargetThreshold (double): Defines the touchable area (number of pixels from the
screen edges) that will allow to open the DrawerContent.

Effects and transitions


RadSideDrawer supports transition animations that are applied to the opening and closing view. We
provide several predefined animations that can be easily set or changed at runtime to meet our
customers’ requirements.

The desired transition can be set through DrawerTransitionType property of the SideDrawer.

 DrawerTransitionType is enumeration of type


Telerik.XamarinForms.Primitives.SideDrawerTransitionType and exposes the
following members:
 Push (the default one)
 Fade
 Reveal
 ReverseSlideOut
 ScaleUp
 SlideAlong
 SlideInOnTop
 Custom
 DrawerTransitionDuration (double): Defines the duration of the chosen transition.
 DrawerTransitionFadeOpacity (double): Defines the opacity of the fade layer of the
component. This controls the fade layer opacity on Android or the dim opacity on iOS.

Example
Here is an example how to set DrawerTransitionType property:

<RadSideDrawer DrawerLength="200"

2434
Telerik UI for Xamarin

DrawerTransitionType="Telerik.XamarinForms.Primitives.SideDrawerTransitionType.Push">
...........
</RadSideDrawer>
 

See Also
 Getting Started

2435
Telerik UI for Xamarin

Getting Started with SideDrawer for


Xamarin Mobile Blazor Bindings
This article will guide you through the steps needed to add a basic RadSideDrawer control in your
application.

1. Setting up the app


Take a look at the Getting Started article how to setup the Telerik Blazor Mobile Bindings for Xamarin
project.

2. Adding the required Telerik references


You have two options:

 Add the Telerik.UI.for.Xamarin.Blazor Nuget package following the instructions in Telerik


NuGet package server topic.
 Add the references to Telerik assemblies manually, check the list below with the required
assemblies for RadSideDrawer component:

Platform Assemblies
Portable Telerik.XamarinForms.Blazor.Primitives
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
Android Telerik.Xamarin.Android.Common.dll
Telerik.Xamarin.Android.Primitives.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll
iOS Telerik.Xamarin.iOS.dll
Telerik.XamarinForms.Common.dll
Telerik.XamarinForms.Primitives.dll

3. Adding RadSideDrawer control


If your app is setup, you are ready to add a RadSideDrawer control.

<ContentView>
<Grid>
<Layout>
<RowDefinition GridUnitType="GridUnitType.Auto" />
<RowDefinition GridUnitType="GridUnitType.Star" />
</Layout>
<Contents>

2436
Telerik UI for Xamarin

<GridCell>
<StackLayout Orientation="StackOrientation.Horizontal"
Spacing="10">
<RadButton WidthRequest="32"
HeightRequest="32"
BorderWidth="0"
CornerRadius="0"
BorderColor="Color.Transparent"
BackgroundColor="Color.Transparent"
BackgroundImage="@(new FileImageSource { File="HamburgerMenu.png" })"
OnClick="@ChangeDrawerState"/>
<Label Text="SideDrawer"
VerticalOptions="LayoutOptions.Center" />
</StackLayout>
</GridCell>
<GridCell Row="1">
<RadSideDrawer DrawerLength="200"
IsOpen="@IsDrawerOpen">
<MainContent>
<Telerik.XamarinForms.Blazor.Primitives.SideDrawer.MainContent>
<Label Text="Main content" />
</Telerik.XamarinForms.Blazor.Primitives.SideDrawer.MainContent>
</MainContent>
<DrawerContent>
<Telerik.XamarinForms.Blazor.Primitives.SideDrawer.DrawerContent>
<StackLayout>
<RadButton Text="Mail" />
<RadButton Text="Calendar" />
<RadButton Text="People" />
<RadButton Text="Tasks" />
</StackLayout>
</Telerik.XamarinForms.Blazor.Primitives.SideDrawer.DrawerContent>
</DrawerContent>
</RadSideDrawer>
</GridCell>
</Contents>
</Grid>
</ContentView>

@code
{
public bool IsDrawerOpen { get; set; }

protected override void OnInitialized()


{
base.OnInitialized();

this.IsDrawerOpen = false;
}

private void ChangeDrawerState()


{
this.IsDrawerOpen = !this.IsDrawerOpen;

2437
Telerik UI for Xamarin

}
}
 

Here is the result when you set IsOpen="True":

See Also
 Xamarin Mobile Blazor Bindings Overview

2438
Telerik UI for Xamarin

Localization and Globalization


Localization and Globalization is the process of designing and developing your application in such a
way that it adapts to different languages and culture configurations.

This topic provides an overview on how you could utilize localization and globalization feature of
Telerik UI for Xamarin components.

Globalization
Globalization refers to developing an application in such a way that it works with respect to the target
device culture. This includes numbers formatting which can vary between cultures, especially for
some specific symbols, such as decimal separators, currency and other, as well as date and time
formatting. Following is a list of Telerik Xamarin controls that support globalization:

 Calendar & Scheduling


 Chart
 DataForm
 DataGrid
 NumericInput
 Date Picker
 DateTime Picker
 Time Picker
 TimeSpan Picker

Localization
Localization refers to the translation of application resources into localized versions for the specific
languages that the application supports. Check below a list of Telerik Xamarin controls that support
localization:

 AutoCompleteView
 Calendar & Scheduling
 ConversationalUI
 DataForm
 DataGrid
 ImageEditor
 Date Picker
 DateTime Picker
 List Picker
 PdfViewer
 RichTextEditor
 Templated Picker
 Time Picker
 TimeSpan Picker

The localization mechanism in Telerik Xamarin controls is implemented through

2439
Telerik UI for Xamarin

TelerikLocalizationManager class and more specifically the TelerikLocalizationManager.Manager


static property. To enable localization to any of the listed above components you should choose
between the approaches below:

 Localization using Custom Localization Manager


 Localization using ResourceManager

In both cases you would need to provide a translation of all the resource keys used inside the
supported controls.

You can download the complete list with the resource keys used in all the supported components
from the SDKBrowser Examples repository on GitHub.
 

Localization using Custom Localization Manager


To apply localization to your controls just instantiate your custom TelerikLocalizationManager and
set it to the static property TelerikLocalizationManager.Manager, before the creation of the UI. Below
you could find an example with RadDataGrid control.

First, create a custom class that inherits from TelerikLocalizationManager and override the
GetString() method:

C#
public class CustomTelerikLocalizationManager : TelerikLocalizationManager
{
public override string GetString(string key)
{
if (key == "FilterText")
{
return "filtre";
}

if (key == "FilterUISectionText")
{
return "filtre par";
}

if (key == "Contains")
{
return "contient";
}

return base.GetString(key);
}
}
 

Set it as the TelerikLocalizationManager.Manager:

C#

2440
Telerik UI for Xamarin

TelerikLocalizationManager.Manager = new CustomTelerikLocalizationManager();

this.InitializeComponent();
 

You should set the custom manager before the InitializeComponent() method is invoked otherwise
the default values will be applied to the RadDataGrid.
 
Check below the appearance of the filtering component within the RadDataGrid after the custom
localization manager is applied.

Localization using ResourceManager


The second option for applying localization is through setting a custom ResourceManager.

In the same way as the built-in mechanism for localizing .NET applications uses RESX files and the
classes in the System.Resources and System.Globalization namespaces, Telerik Xamarin controls
rely on similar setup to achieve the functionality.

You should add different resource (.RESX) files according to the different languages/cultures which
you would like to use. Imagine that you want to translate your control, RadDataGrid for example, into
English and German. You will have to add two new resource files to your Xamarin.Forms project with
Embedded resource Build action:

 DataGridResource.resx - this resource file will store the English(default) resources for the
DataGrid control.
 DataGridResource.de.resx - this resource file will store the German resources for the
DataGrid control. It will be automatically used when the language of the target device is set

2441
Telerik UI for Xamarin

to German.

Next image shows an example of a custom resource file used for German:

In order to apply the localization from the DataGridResource resource files, you would need to set
the ResourceManager property of the TelerikLocalizationManager.Manager to the
DataGridResource.ResourceManager:

C#
TelerikLocalizationManager.Manager.ResourceManager = DataGridResource.ResourceManager;
this.InitializeComponent();
 

You should set the custom manager before the InitializeComponent() method is invoked otherwise
the default values will be applied to the RadDataGrid.
 
Check the appearance of the filtering control when the localization is applied:

Figure 3: Custom Resource File for German language

2442
Telerik UI for Xamarin

You can check working localization examples in the DataGrid/Localization folder within the SDK
Browser application.

You can directly explore the code in the SDKBrowser Examples repository on GitHub.

2443
Telerik UI for Xamarin

What is a Telerik Theme


A Telerik Theme is a set of resources which are designed to provide your application with a
consistent look and feel across all platforms. Setting a theme for your application is an easy and
straightforward process. Furthermore, you are free to customize the theme's resources so that a more
distinct appearance is achieved.

Blue Theme
As its name suggests, the main accent of the Blue Theme is the blue color. Respectively, the
additional brushes that are used are picked to nicely fit with the leading color. Figure 1 shows how
some of the controls look with the Theme set. The Default Theme Colors and their actual
appearance are present in the table below.

Figure 1: Telerik Blue Theme

2444
Telerik UI for Xamarin

2445
Telerik UI for Xamarin

Default Theme Colors


Main Colors

Color Hex Value Appearance


Basic Font Color #4A4949
AlternativeFont Color #919191
Accent Color 1 #3148CA
Background Color 1 #3D5AFE
Accent Color 2 #30BCFF
Background Color 2 #000000
Color of Grid #D9D9D9
Color of Menu Bar #F8F8F8

Complementary Colors

Complementary Color Hex Value Appearance


Complementary Color 1 #FF5225
Complementary Color 2 #FFC325
Complementary Color 3 #2EC262
Complementary Color 4 #FE3D5A
Complementary Color 5 #803DFE
Complementary Color 6 #3DBAFE

See Also
 How To Set a Theme
 How To Create a Custom Theme Based on a Telerik Theme

2446
Telerik UI for Xamarin

How to Set a Telerik Theme


There are a couple of steps you need to take in order to apply the theming on a specific control. You
need to:

 Merge the required ResourceDictionaries


 Set the StyleClass property of the control

Merge The Required ResourceDictionaries


In order to apply a Telerik Theme for a specific control, you need to merge the required
ResourceDictionaries in your application:

XAML
<Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"

xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"

xmlns:chart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinForms.Ch
art"

xmlns:primitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Telerik.Xamar
inForms.Primitives"

xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te
lerik.XamarinForms.DataControls"

xmlns:telerikCommon="clr-namespace:Telerik.XamarinForms.Common;assembly=Telerik.Xamari
nForms.Common"

xmlns:dataGrid="clr-namespace:Telerik.XamarinForms.DataGrid;assembly=Telerik.XamarinFo
rms.DataGrid"
x:Class="Examples.App">
<Application.Resources>

<!-- Application resource dictionary -->


<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary MergedWith="telerikCommon:BlueResources"/>
<ResourceDictionary MergedWith="telerikInput:TelerikThemeStyles"/>
<ResourceDictionary MergedWith="primitives:TelerikThemeStyles"/>
<ResourceDictionary MergedWith="chart:TelerikThemeStyles"/>
<ResourceDictionary MergedWith="telerikDataControls:TelerikThemeStyles" />
<ResourceDictionary MergedWith="dataGrid:TelerikThemeStyles"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

</Application.Resources>
</Application>

2447
Telerik UI for Xamarin

The above snippet shows how to include the dictionaries required for all the controls in the suite.
However, if you are not using the full set of controls, you can merge only these dictionaries that are
required by the specific element you need.

Set the StyleClass on Control Level


Once you have merged all the required dictionaries, you need to set the StyleClass property of the
control's instance whose theme you would like to modify. The example below shows how to achieve
this on a RadListView control:

XAML
<telerikDataControls:RadListView x:Name="list" StyleClass="TelerikTheme"/>
 

Figure 1: RadListView's appearance after setting the StyleClass

See Also
 Themes Overview
 How To Create a Custom Theme Based on a Telerik Theme

2448
Telerik UI for Xamarin

How to Create a Custom Theme Based on


a Telerik Theme
This article provides more information on the default resources structure and how to modify them
and create a custom theme which is based on the Telerik Theme.

Blue Theme Default Resources


The default resources are located in the Telerik.XamarinForms.Common assembly and you need to
merge them in your application's resources in order to apply the theme. Below is the definition of the
resources and respectively the default colors that are used for the different controls:

xml
<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Telerik.XamarinForms.Common.BlueResources">
<!-- AutoComplete -->
<Color x:Key="TelerikAutoCompleteSelectedTokenBackgroundColor">#3148CA</Color>
<Color x:Key="TelerikAutoCompleteSelectedTokenStrokeColor">#3148CA</Color>
<Color x:Key="TelerikAutoCompleteSelectedTokenTextColor">#FFFFFF</Color>
<Color x:Key="TelerikAutoCompleteSuggestionItemTextColor">#3148CA</Color>
<Color x:Key="TelerikAutoCompleteBorderColor">#D9D9D9</Color>
<Color x:Key="TelerikAutoCompleteSuggestionViewBackgroundColor">#F8F8F8</Color>
<Color x:Key="TelerikAutoCompleteTokenTextColor">#3148CA</Color>
<Color x:Key="TelerikAutoCompleteTokenStrokeColor">#3148CA</Color>
<Color x:Key="TelerikAutoCompleteTokenBackgroundColor">#F8F8F8</Color>

<!-- BusyIndicator -->


<Color x:Key="TelerikBusyIndicatorContent">#3148CA</Color>

<!-- Button -->


<Color x:Key="TelerikButtonBackgroundColor">#3148CA</Color>
<Color x:Key="TelerikButtonTextColor">White</Color>

<!-- Calendar -->


<Color x:Key="TelerikCalendarBasicFontColor">#4A4949</Color>
<Color x:Key="TelerikCalendarAlternativeFontColor">#919191</Color>
<Color x:Key="TelerikCalendarMenuBarColor">#F8F8F8</Color>
<Color x:Key="TelerikCalendarAccentColor1">#3148CA</Color>
<Color x:Key="TelerikCalendarAccentColor2">#30BCFF</Color>
<Color x:Key="TelerikCalendarBackgroundColor1">#3D5AFE</Color>
<Color x:Key="TelerikCalendarBackgroundColor2">#000000</Color>
<Color x:Key="TelerikCalendarBackgroundColor3">#FFFFFF</Color>

<!-- Chart -->


<Color x:Key="TelerikChartAxisColor">#919191</Color>
<Color x:Key="TelerikChartGridLinesColor">#D9D9D9</Color>

2449
Telerik UI for Xamarin

<!-- Chat -->


<Color x:Key="TelerikChatIncomingMessageTextColor">#333333</Color>
<Color x:Key="TelerikChatOutgoingMessageTextColor">#FFFFFF</Color>
<Color x:Key="TelerikChatIncomingMessageBackgroundColor">#FFFFFF</Color>
<Color x:Key="TelerikChatOutgoingMessageBackgroundColor">#3148CA</Color>
<Color x:Key="TelerikChatCardTitleTextColor">#3148CA</Color>
<Color x:Key="TelerikChatCardActionTextColor">#3148CA</Color>
<Color x:Key="TelerikChatTypingIndicatorDotsColor">#3148CA</Color>
<Color x:Key="TelerikChatPickerHeaderBackgroundColor">#F8F8F8</Color>
<Color x:Key="TelerikChatPickerHeaderTextColor">#3148CA</Color>
<Color x:Key="TelerikChatPickerOkButtonTextColor">#3148CA</Color>
<Color x:Key="TelerikChatPickerCancelButtonTextColor">#3148CA</Color>
<Color x:Key="TelerikChatPickerFooterBackgroundColor">#F8F8F8</Color>
<Color x:Key="TelerikChatItemPickerSelectedBackgroundColor">Transparent</Color>
<Color x:Key="TelerikChatItemPickerSelectedBorderColor">#3148CA</Color>
<Color x:Key="TelerikChatItemPickerSelectedTextColor">#3148CA</Color>

<!-- CheckBox -->


<Color x:Key="TelerikCheckBoxCheckedColor">#3148CA</Color>
<Color x:Key="TelerikCheckBoxCheckedSymbolColor">White</Color>
<Color x:Key="TelerikCheckBoxIndeterminateColor">#3148CA</Color>
<Color x:Key="TelerikCheckBoxIndeterminateSymbolColor">White</Color>
<Color x:Key="TelerikCheckBoxUncheckedColor">#919191</Color>

<!-- DataForm -->


<Color x:Key="TelerikDataFormEditorAccentColor">#3148CA</Color>
<Color x:Key="TelerikDataFormBackgroundColor">White</Color>
<Color x:Key="TelerikDataFormHeaderFontColor">#919191</Color>
<Color x:Key="TelerikDataFormEditorBorderColor">#D9D9D9</Color>

<!-- DataGrid -->


<Color x:Key="TelerikDataGridAccentColor">#3148CA</Color>

<!-- Entry -->


<OnPlatform x:TypeArguments="Color" x:Key="TelerikEntryTextColor">
<On Platform="iOS" Value="#020202" />
</OnPlatform>
<Color x:Key="TelerikEntryBorderColor">#3148CA</Color>

<!-- Expander -->


<Color x:Key="TelerikExpandCollapseIndicatorColor">#3148CA</Color>

<!-- ListView -->


<Color x:Key="TelerikListViewItemBorderColor">#D9D9D9</Color>
<Color x:Key="TelerikListViewSelectionColor">#3148CA</Color>
<Color x:Key="TelerikListViewBackgroundColor">White</Color>
<Color x:Key="TelerikListViewForegroundColor">#4A4949</Color>
<Color x:Key="TelerikListViewGroupHeaderBackgroundColor">#F8F8F8</Color>

<!-- MaskedInput -->


<Color x:Key="TelerikMaskedInputBorderColor">#3148CA</Color>
<Color x:Key="TelerikMaskedInputWatermarkColor">#3148CA</Color>
<Color x:Key="TelerikMaskedInputErrorColor">#D50002</Color>
<Color x:Key="TelerikMaskedInputDisplayedTextColor">#4A4949</Color>

2450
Telerik UI for Xamarin

<!-- NonVirtualizedItemsControl -->


<Color
x:Key="TelerikNonVirtualizedItemsControlSelectedBackgroundColor">Transparent</Color>
<Color
x:Key="TelerikNonVirtualizedItemsControlSelectedBorderColor">#3148CA</Color>
<Color x:Key="TelerikNonVirtualizedItemsControlSelectedTextColor">#3148CA</Color>

<!-- NumericInput -->


<Color x:Key="TelerikNumericInputButtonBorderColor">#3148CA</Color>
<Color x:Key="TelerikNumericInputButtonTextColor">#3148CA</Color>
<Color x:Key="TelerikNumericInputButtonBackgroundColor">Transparent</Color>
<Color x:Key="TelerikNumericInputEntryBorderColor">#3148CA</Color>
<OnPlatform x:TypeArguments="Color" x:Key="TelerikNumericInputEntryTextColor">
<On Platform="iOS" Value="#020202" />
</OnPlatform>

<!-- PdfViewer -->


<Color x:Key="TelerikPdfViewerToolbarItemTextColor">#3148CA</Color>

<!-- ImageEditor -->


<Color x:Key="TelerikImageEditorToolbarItemTextColor">#3148CA</Color>

<!-- RichTextEditor -->


<Color x:Key="TelerikRichTextEditorToolbarBackgroundColor">#F7F7F7</Color>
<Color x:Key="TelerikRichTextEditorToolbarItemTextColor">#3148CA</Color>
<Color
x:Key="TelerikRichTextEditorToolbarItemSelectedBackgroundColor">#3148CA</Color>
<Color
x:Key="TelerikRichTextEditorPickerToolbarItemPopupBackgroundColor">#F7F7F7</Color>
<Color
x:Key="TelerikRichTextEditorColorToolbarItemPopupBackgroundColor">#F7F7F7</Color>
<Color
x:Key="TelerikRichTextEditorHyperlinkPopupContentViewButtonTextColor">#3148CA</Color>

<!-- Rating -->


<Color x:Key="TelerikRatingControlAccentColor">#3148CA</Color>

<!-- SegmentedControl -->


<Color x:Key="TelerikSegmentControlAccentColor">#3148CA</Color>
<Color x:Key="TelerikSegmentControlMainColor">#FFFFFF</Color>
<Color x:Key="TelerikSegmentControlDisabledTextColor">#803148CA</Color>

<!-- SlideView -->


<Color x:Key="TelerikSlideViewIndicatorColor">#D9D9D9</Color>
<Color x:Key="TelerikSlideViewSelectedIndicatorColor">#3148CA</Color>
<Color x:Key="TelerikSlideViewSlideButtonsColor">#3148CA</Color>

<!-- TabView-->
<Color x:Key="TelerikTabViewHeaderItemSelectedColor">#3148CA</Color>

<!-- TimePicker -->


<Color x:Key="TelerikTimePickerSelectedBackgroundColor">Transparent</Color>
<Color x:Key="TelerikTimePickerSelectedBorderColor">#3148CA</Color>
<Color x:Key="TelerikTimePickerSelectedTextColor">#3148CA</Color>

2451
Telerik UI for Xamarin

<!-- Toolbar -->


<Color x:Key="TelerikBackToolbarItemTextColor">#3148CA</Color>
<Color x:Key="TelerikToolbarItemTextColor">#3148CA</Color>

<!-- TreeView -->


<Color x:Key="TelerikTreeViewCheckBoxCheckedColor">#3148CA</Color>
<Color x:Key="TelerikTreeViewCheckBoxCheckedSymbolColor">White</Color>
<Color x:Key="TelerikTreeViewCheckBoxIndeterminateColor">#3148CA</Color>
<Color x:Key="TelerikTreeViewCheckBoxIndeterminateSymbolColor">White</Color>
<Color x:Key="TelerikTreeViewCheckBoxUncheckedColor">#919191</Color>
<Color x:Key="TelerikTreeViewItemTextTextColor">Black</Color>
<Color x:Key="TelerikTreeViewExpandCollapseIndicatorTextColor">#3148CA</Color>

<!-- Pickers -->


<Color x:Key="TelerikPickerPopupButtonTextColor">#3148CA</Color>
<Color x:Key="TelerikPickerTabStripItemSelectedColor">#3148CA</Color>

<!-- ComboBox -->


<Color x:Key="TelerikComboBoxHightlightTextColor">#3148CA</Color>
<Color x:Key="TelerikComboBoxBorderColor">#3148CA</Color>
</ResourceDictionary>
 

Customizing the Colors


You can replace the values of the colors with custom ones. This way you can modify the overall
appearance which is applied for the different instances of the controls. In order to do so, you can
directly modify some of the default resources. The following example shows how to change the
appearance of all RadListView instances that use the theme:

XAML
<Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"

xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"

xmlns:telerikDataGrid="clr-namespace:Telerik.XamarinForms.DataGrid;assembly=Telerik.Xa
marinForms.DataGrid"

xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"

xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"

xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te
lerik.XamarinForms.DataControls"

xmlns:telerikConversationalUi="clr-namespace:Telerik.XamarinForms.ConversationalUI;ass
embly=Telerik.XamarinForms.ConversationalUI"

xmlns:portable="clr-namespace:DuaneThemeDemo.Portable;assembly=MyApplication.Portable"

2452
Telerik UI for Xamarin

xmlns:telerikCommon="clr-namespace:Telerik.XamarinForms.Common;assembly=Telerik.Xamari
nForms.Common"
x:Class="MyApplication.Portable.App">

<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary MergedWith="telerikCommon:BlueResources">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary>
<!-- Override default colors here. -->
<Color x:Key="TelerikCalendarBasicFontColor">Orange</Color>
<Color x:Key="TelerikBusyIndicatorContent">Yellow</Color>
</ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
<!-- Telerik themes go here. -->
<ResourceDictionary MergedWith="input:TelerikThemeStyles" />
<ResourceDictionary MergedWith="primitives:TelerikThemeStyles" />
<ResourceDictionary MergedWith="chart:TelerikThemeStyles" />
<ResourceDictionary MergedWith="dataControls:TelerikThemeStyles" />
<ResourceDictionary MergedWith="dataGrid:TelerikThemeStyles" />
<ResourceDictionary MergedWith="conversationalUi:TelerikThemeStyles" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
 

Separate ResourceDictionary file


Another possibility is to create your own ResourceDictionary and merge it instead of the default
telerikCommon:BlueResources one.

1. Add a new XAML ContentPage file to your application and delete all the boilerplate
ContentPage.Content code
2. Change the ContentPage type to ResourceDictionary type

xml
<!-- Change -->
<ContentPage ...>
</ContentPage>

<!-- to ResourceDictionary -->


<ResourceDictionary ...>
</ResourceDictionary>
 

3. Change the base type in the code behind from `ContentPage` to `ResourceDictionary`:
 

2453
Telerik UI for Xamarin

csharp
// Set base type to ResourceDictionary
public partial class MyTheme : ResourceDictionary
{
public MyTheme()
{
InitializeComponent();
}
}
 

4. Add the Telerik Blue theme resources


 

xml
<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MyApplication.MyTheme">
<!-- AutoComplete -->
<Color x:Key="TelerikAutoCompleteSelectedTokenBackgroundColor">#3148CA</Color>
<Color x:Key="TelerikAutoCompleteSelectedTokenStrokeColor">#3148CA</Color>
<Color x:Key="TelerikAutoCompleteSelectedTokenTextColor">#FFFFFF</Color>
<Color x:Key="TelerikAutoCompleteSuggestionItemTextColor">#3148CA</Color>
<Color x:Key="TelerikAutoCompleteBorderColor">#D9D9D9</Color>
<Color x:Key="TelerikAutoCompleteSuggestionViewBackgroundColor">#F8F8F8</Color>
<Color x:Key="TelerikAutoCompleteTokenTextColor">#3148CA</Color>
<Color x:Key="TelerikAutoCompleteTokenStrokeColor">#3148CA</Color>
<Color x:Key="TelerikAutoCompleteTokenBackgroundColor">#F8F8F8</Color>

<!-- BusyIndicator -->


<Color x:Key="TelerikBusyIndicatorContent">#3148CA</Color>

<!-- Button -->


<Color x:Key="TelerikButtonBackgroundColor">#3148CA</Color>
<Color x:Key="TelerikButtonTextColor">White</Color>

<!-- Calendar -->


<Color x:Key="TelerikCalendarBasicFontColor">#4A4949</Color>
<Color x:Key="TelerikCalendarAlternativeFontColor">#919191</Color>
<Color x:Key="TelerikCalendarMenuBarColor">#F8F8F8</Color>
<Color x:Key="TelerikCalendarAccentColor1">#3148CA</Color>
<Color x:Key="TelerikCalendarAccentColor2">#30BCFF</Color>
<Color x:Key="TelerikCalendarBackgroundColor1">#3D5AFE</Color>
<Color x:Key="TelerikCalendarBackgroundColor2">#000000</Color>
<Color x:Key="TelerikCalendarBackgroundColor3">#FFFFFF</Color>

<!-- Chart -->


<Color x:Key="TelerikChartAxisColor">#919191</Color>
<Color x:Key="TelerikChartGridLinesColor">#D9D9D9</Color>

<!-- Chat -->


<Color x:Key="TelerikChatIncomingMessageTextColor">#333333</Color>

2454
Telerik UI for Xamarin

<Color x:Key="TelerikChatOutgoingMessageTextColor">#FFFFFF</Color>
<Color x:Key="TelerikChatIncomingMessageBackgroundColor">#FFFFFF</Color>
<Color x:Key="TelerikChatOutgoingMessageBackgroundColor">#3148CA</Color>
<Color x:Key="TelerikChatCardTitleTextColor">#3148CA</Color>
<Color x:Key="TelerikChatCardActionTextColor">#3148CA</Color>
<Color x:Key="TelerikChatTypingIndicatorDotsColor">#3148CA</Color>
<Color x:Key="TelerikChatPickerHeaderBackgroundColor">#F8F8F8</Color>
<Color x:Key="TelerikChatPickerHeaderTextColor">#3148CA</Color>
<Color x:Key="TelerikChatPickerOkButtonTextColor">#3148CA</Color>
<Color x:Key="TelerikChatPickerCancelButtonTextColor">#3148CA</Color>
<Color x:Key="TelerikChatPickerFooterBackgroundColor">#F8F8F8</Color>
<Color x:Key="TelerikChatItemPickerSelectedBackgroundColor">Transparent</Color>
<Color x:Key="TelerikChatItemPickerSelectedBorderColor">#3148CA</Color>
<Color x:Key="TelerikChatItemPickerSelectedTextColor">#3148CA</Color>

<!-- CheckBox -->


<Color x:Key="TelerikCheckBoxCheckedColor">#3148CA</Color>
<Color x:Key="TelerikCheckBoxCheckedSymbolColor">White</Color>
<Color x:Key="TelerikCheckBoxIndeterminateColor">#3148CA</Color>
<Color x:Key="TelerikCheckBoxIndeterminateSymbolColor">White</Color>
<Color x:Key="TelerikCheckBoxUncheckedColor">#919191</Color>

<!-- DataForm -->


<Color x:Key="TelerikDataFormEditorAccentColor">#3148CA</Color>
<Color x:Key="TelerikDataFormBackgroundColor">White</Color>
<Color x:Key="TelerikDataFormHeaderFontColor">#919191</Color>
<Color x:Key="TelerikDataFormEditorBorderColor">#D9D9D9</Color>

<!-- DataGrid -->


<Color x:Key="TelerikDataGridAccentColor">#3148CA</Color>

<!-- Entry -->


<OnPlatform x:TypeArguments="Color"
x:Key="TelerikEntryTextColor">
<On Platform="iOS"
Value="#020202" />
</OnPlatform>
<Color x:Key="TelerikEntryBorderColor">#3148CA</Color>

<!-- Expander -->


<Color x:Key="TelerikExpandCollapseIndicatorColor">#3148CA</Color>

<!-- ListView -->


<Color x:Key="TelerikListViewItemBorderColor">#D9D9D9</Color>
<Color x:Key="TelerikListViewSelectionColor">#3148CA</Color>
<Color x:Key="TelerikListViewBackgroundColor">White</Color>
<Color x:Key="TelerikListViewForegroundColor">#4A4949</Color>
<Color x:Key="TelerikListViewGroupHeaderBackgroundColor">#F8F8F8</Color>

<!-- MaskedInput -->


<Color x:Key="TelerikMaskedInputBorderColor">#3148CA</Color>
<Color x:Key="TelerikMaskedInputWatermarkColor">#3148CA</Color>
<Color x:Key="TelerikMaskedInputErrorColor">#D50002</Color>
<Color x:Key="TelerikMaskedInputDisplayedTextColor">#4A4949</Color>

2455
Telerik UI for Xamarin

<!-- NonVirtualizedItemsControl -->


<Color
x:Key="TelerikNonVirtualizedItemsControlSelectedBackgroundColor">Transparent</Color>
<Color
x:Key="TelerikNonVirtualizedItemsControlSelectedBorderColor">#3148CA</Color>
<Color x:Key="TelerikNonVirtualizedItemsControlSelectedTextColor">#3148CA</Color>

<!-- NumericInput -->


<Color x:Key="TelerikNumericInputButtonBorderColor">#3148CA</Color>
<Color x:Key="TelerikNumericInputButtonTextColor">#3148CA</Color>
<Color x:Key="TelerikNumericInputButtonBackgroundColor">Transparent</Color>
<Color x:Key="TelerikNumericInputEntryBorderColor">#3148CA</Color>
<OnPlatform x:TypeArguments="Color"
x:Key="TelerikNumericInputEntryTextColor">
<On Platform="iOS"
Value="#020202" />
</OnPlatform>

<!-- Rating -->


<Color x:Key="TelerikRatingControlAccentColor">#3148CA</Color>

<!-- SegmentedControl -->


<Color x:Key="TelerikSegmentControlAccentColor">#3148CA</Color>
<Color x:Key="TelerikSegmentControlMainColor">#FFFFFF</Color>
<Color x:Key="TelerikSegmentControlDisabledTextColor">#803148CA</Color>

<!-- SlideView -->


<Color x:Key="TelerikSlideViewIndicatorColor">#D9D9D9</Color>
<Color x:Key="TelerikSlideViewSelectedIndicatorColor">#3148CA</Color>
<Color x:Key="TelerikSlideViewSlideButtonsColor">#3148CA</Color>

<!-- TabView-->
<Color x:Key="TelerikTabViewHeaderItemSelectedColor">#3148CA</Color>

<!-- TimePicker -->


<Color x:Key="TelerikTimePickerSelectedBackgroundColor">Transparent</Color>
<Color x:Key="TelerikTimePickerSelectedBorderColor">#3148CA</Color>
<Color x:Key="TelerikTimePickerSelectedTextColor">#3148CA</Color>

<!-- TreeView -->


<Color x:Key="TelerikTreeViewCheckBoxCheckedColor">#3148CA</Color>
<Color x:Key="TelerikTreeViewCheckBoxCheckedSymbolColor">White</Color>
<Color x:Key="TelerikTreeViewCheckBoxIndeterminateColor">#3148CA</Color>
<Color x:Key="TelerikTreeViewCheckBoxIndeterminateSymbolColor">White</Color>
<Color x:Key="TelerikTreeViewCheckBoxUncheckedColor">#919191</Color>
<Color x:Key="TelerikTreeViewItemTextTextColor">Black</Color>
<Color x:Key="TelerikTreeViewExpandCollapseIndicatorTextColor">#3148CA</Color>
</ResourceDictionary>
 

5. Customize those color values with the ones you prefer for your theme.
6. Open **App.xaml** and replace BlueResources with your newly created one.
 

2456
Telerik UI for Xamarin

See the comment in the following example. Notice that portable:MyTheme has replaced
telerikCommon:BlueResources in the MergedDictionaries list.

xml
<Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"

xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"

xmlns:telerikDataGrid="clr-namespace:Telerik.XamarinForms.DataGrid;assembly=Telerik.Xa
marinForms.DataGrid"

xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"

xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"

xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te
lerik.XamarinForms.DataControls"

xmlns:telerikConversationalUi="clr-namespace:Telerik.XamarinForms.ConversationalUI;ass
embly=Telerik.XamarinForms.ConversationalUI"

xmlns:portable="clr-namespace:DuaneThemeDemo.Portable;assembly=MyApplication.Portable"
x:Class="MyApplication.Portable.App">

<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<!-- Your custom ResourceDictionary, with all the custom styles and colors -->
<ResourceDictionary MergedWith="portable:MyTheme"/>

<!-- Telerik themes go here. -->


<ResourceDictionary MergedWith="input:TelerikThemeStyles" />
<ResourceDictionary MergedWith="primitives:TelerikThemeStyles" />
<ResourceDictionary MergedWith="chart:TelerikThemeStyles" />
<ResourceDictionary MergedWith="dataControls:TelerikThemeStyles" />
<ResourceDictionary MergedWith="dataGrid:TelerikThemeStyles" />
<ResourceDictionary MergedWith="conversationalUi:TelerikThemeStyles" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
 

7. Set StyleClass on Control Level


 

Once you have merged all the required dictionaries, you need to set the StyleClass property of the
control's instance whose theme you would like to modify. The example below shows how to achieve
this on a RadListView control:

2457
Telerik UI for Xamarin

XAML
<telerikDataControls:RadListView x:Name="list" StyleClass="TelerikTheme"/>
 

In case you need to modify the default resources of the TelerikTheme for the RadDataForm control,
please refer to the following article - DataForm: Modifying TelerikTheme resources
 
Figure 1 shows the appearance of the RadListView once the changes are applied:

See Also
 How To Set a Theme
 Themes Overview

2458
Telerik UI for Xamarin

Overview
Android 10 (API level 29) and iOS 13 introduce system-wide dark appearance for all user interface
elements, known as Dark theme for Android and Dark Mode for iOS. They have many benefits as to
allow users to toggle their interface and focus on the application’s content based on ambient lighting
conditions as well as to reduce power usage amount depending on the device's screen technology.

From the R1 2021 Official Release the Telerik UI for Xamarin controls have a support for Dark
Theme/Dark Mode on Android and on iOS.
 

Dark Theme for Android


In order to support Dark theme for Android, the application's theme must inherit from a DayNight
theme as explained here.

Example:

Set the app theme inside the Resources/values/styles.xml file located in the Android project.

xml
<style name="MainTheme" parent="Theme.AppCompat.DayNight">
 

Here is how some of the Telerik Xamarin controls look on Android with Darh Theme applied

ListView, DataForm and DataGrid:

2459
Telerik UI for Xamarin

Make sure to test your application carefully and thoroughly on both Light and Dark system
appearance.
 

Dark Mode for iOS


Telerik UI for Xamarin controls automatically react to system appearance changes.

Here is how some of the Telerik Xamarin controls look on iOS with Darh Mode applied:

DateTime Picker, Calendar and Chart controls:

2460
Telerik UI for Xamarin

Make sure to test your application carefully and thoroughly on both Light and Dark system
appearance.
 

App Theme Binding


If you want to make your Xamarin.Forms applications to respond to system theme changes, you
need to consume resources with the AppThemeBinding markup extension, and the
SetAppThemeColor and SetOnAppTheme extension methods.

Requrements:

 Xamarin.Forms 4.6.0.967 or greater.


 iOS 13 or greater.
 Android 10 (API 29) or greater.

For more details about this please review the following article from the Microsoft documentation:
Respond to system theme changes in Xamarin.Forms applications.
 

 Detecting the current system theme: This can be achieved by getting the value of the
Application.RequestedTheme property. Information about this option can be found here.
 Set the app theme

If you want to specify the theme which your Xamarin.Forms application will use, regardless
of which system theme is currently operational, set the Application.UserAppTheme
property (of type Xamarin.Forms OSAppTheme):

2461
Telerik UI for Xamarin

C#
Application.Current.UserAppTheme = OSAppTheme.Dark;
```
 

For more details on this check here.

 Theme Changes

If you want your Xamarin.Forms app to be notified when the system theme changes you
have to use the Application.RequestedThemeChanged even. For more information on
this check here.

Example
The Telerik UI for Xamarin Samples Application has a dark mode support on Android and on
iOS. You can change the app theme by clicking on a button.

2462
Telerik UI for Xamarin

See Also
 Telerik Font Icons
 Telerik Blue Theme

2463
Telerik UI for Xamarin

Telerik UI for Xamarin Font Icons


Telerik font icons is a collection of small vector graphics used across the components from Telerik UI
for Xamarin suite. Examples of using font icons include the expand and collapse indicators of
Accordion, Expander and TreeView controls, filter and sort indicators of DataGrid control, and other.

This article will give an overview on how you can utilize the Telerik font icons in your app.

 Include the required Telerik Font file


 Add the font file path
 Choose between the available Telerik icons

Include the required Telerik Font file


1. The Telerik Font Icons are located in the telerikfontexamples.ttf file. There are two options
you could use to get the .ttf file.
 Download the telerikfontexamples.ttf file from Telerik UI for Xamarin Samples App GitHub
repo.
 Get the font file from the installation folder of Telerik UI for Xamarin - here is the path to
the exact location: Telerik UI for Xamarin [version]\QSF\QSF.Android\Assets\Fonts
2. Include Telerik Font .ttf file into your application in the following locations:
 Android project: Create Fonts folder inside the Android Assets and add the .ttf file there.
 iOS project: Create Fonts folder inside the iOS Resources and add the .ttf file there.

You'd also need to modify the info.plist file inside the iOS project with adding the following
code:

xml
<key>UIAppFonts</key>
<array>
<string>Fonts/telerikfontexamples.ttf</string>
</array>
```
 

 UWP project: Create Fonts folder inside the UWP Assets and add the .ttf file there.

Add the font file path


As a final step you need to add the path to the Fonts inside the Resources of the App.xaml
file of the Xamarin.Forms project:

XAML
<Application.Resources>
<ResourceDictionary>
<OnPlatform x:TypeArguments="x:String" x:Key="IconsFont">

2464
Telerik UI for Xamarin

<On Platform="iOS">telerikfontexamples</On>
<On Platform="Android">Fonts/telerikfontexamples.ttf#telerikfontexamples</On>
<On
Platform="UWP">/Assets/Fonts/telerikfontexamples.ttf#telerikfontexamples</On>
</OnPlatform>
</ResourceDictionary>
</Application.Resources>
 

Choose between the available Telerik icons


You can choose any of the available Telerik Font icons:

Telerik Font
Icons
sort_descent &#xe800; star-empty &#xe801; filter &#xe802;
sort_ascent &#xe803; group &#xe804; star &#xe805;
right-dir &#xe806; dots_vert &#xe807; menu &#xe808;
check &#xe809; cancel &#xe80a; dot &#xe80b;
check &#xe80c; down-dir &#xe80d; left-open-big &#xe80e;
configure &#xe80f; search &#xe810; up-dir &#xe811;
pattern &#xe812; add &#xe813; right-dir-outli &#xe814;
nes
info &#xe815; down-dir-outl &#xe816; bin-solid &#xe817;
ines
edit &#xe818; copy &#xe819; arrow-up &#xe81a;
airplane &#xe81c; pdf &#xe81d; encoding &#xe81e;
length &#xe81f; arrow-right &#xe820; contacts &#xe821;
cog-outlines &#xe822; type &#xe823; location &#xe824;
link &#xe825; archive &#xe826; bin &#xe827;
draft &#xe828; folder-open &#xe829; folder &#xe82a;
group &#xe82b; item &#xe82c; sent &#xe82d;
spam &#xe82e; warning &#xe82f; lock &#xe830;
thickness &#xe831; car &#xe832; shopping-ba &#xe833;
g
coffee-cup &#xe834; get-money &#xe835; shopping-us &#xe836;
er
group_users &#xe837; dashboard &#xe838; location &#xe83d;

2465
Telerik UI for Xamarin

link &#xe83e; assets &#xe846; book &#xe847;


design &#xe848; graphics &#xe849; image &#xe84a;
font-size &#xe84b; template &#xe84c; wireframes &#xe84d;
distance &#xe84e; stopwatch &#xe84f; play &#xe850;
cancel &#xe851; picture &#xe852; text &#xe853;
code &#xe854; analysis &#xe855; network &#xe856;
network &#xe857; bar-chart &#xe858; sap &#xe859;
dba &#xe85a; home &#xe85b; temperature &#xe85c;
phone &#xe85d; electricity &#xe85e; wifi &#xe85f;
distance-hori &#xe860; calendar_da &#xe861; calendar_mu &#xe862;
zontal yview ltiday
calendar_we &#xe863; calendar_mo &#xe864; calendar_ye &#xe865;
ek nth ar
calendar &#xe866; calendar &#xe867; calendar &#xe868;
selection selection selection
single multiple range
gallery &#xe869; camera &#xe86a; crop_free &#xe86b;
crop_original &#xe86c; crop_rect &#xe86d; crop_circular &#xe86e;
badge &#xe86f; notes &#xe870; time &#xe871;
calendar_ag &#xe872; arrows &#xe873; video-camer &#xe87;
enda a
check &#xe876; cancel &#xe877; time &#xe878;
arrow-down &#xe879; flag &#xe87a; save &#xe87b;
share &#xe87c; menu-custo &#xe87d; heart-filled &#xe87e;
m
heart-empty &#xe87f; reorder &#xe881; arrow-box-lef &#xe882;
t
arrow-box-rig &#xe883; bell-empty &#xe901; chat &#xe903;
ht
phone &#xe904; menu &#xf008; link-external &#xf08e;
plus-squared &#xf0fe; angle-left &#xf104; angle-right &#xf105;
angle-up &#xf106; angle-down &#xf107; spinner &#xf110;
angle circled &#xf137; angle circled &#xf138; minus-squar &#xf146;
left right ed
minus &#xf147; plus squared &#xf196; emoji &#xe900;
squared

2466
Telerik UI for Xamarin

You need to set the Telerik Font icon code on the concrete property to visualize the icon.
 

Examples

Let's for example change the default icon of the RadDataGrid OptionsButton, used to display
the DataGrid Filtering UI with one of the above listed icons (configure icon). DataGrid provides
HeaderStyle property for its columns and the DataGridColumnHeaderStyle exposes
OptionsButtonText property responsible for the OptionsButton icon.

The configure icon's code ends with e80f; so this string should be applied to the
OptionsButtonText property:

XAML
<telerikGrid:DataGridTextColumn.HeaderStyle>
<telerikGrid:DataGridColumnHeaderStyle OptionsButtonText="&#xe80f;"/>
</telerikGrid:DataGridTextColumn.HeaderStyle>
 

Here is the result:

2467
Telerik UI for Xamarin

See Also
 How To Set a Theme
 Themes Overview

2468
Telerik UI for Xamarin

Azure Overview
 

Microsoft Azure is a cloud computing service created by Microsoft for building, testing, deploying,
and managing applications and services through a global network of Microsoft-managed data
centers. It provides software as a service (SaaS), platform as a service (PaaS) and infrastructure as
a service (IaaS) and supports many different programming languages, tools and frameworks,
including both Microsoft-specific and third-party software and systems. Microsoft Azure also provides
a variety of cognitive services which enable you to see, hear, speak, understand and interpret your
user needs through natural methods of communication.

You can create a free account and take advantage of a number of free services such as Cosmos DB,
Blob/File Storage, serverless functions and more and integrate them with the controls from the
Telerik UI for Xamarin suite. Here are some of the services that are available:

Here are the currently available topics:

2469
Telerik UI for Xamarin

 Getting Started
 Blob Storage
 Cognitive services
 Text Translation
 Text Analysis
 Connect to data in the cloud
 Cosmos DB
 SQL Database

2470
Telerik UI for Xamarin

Getting Started
 

This article will help you get started using Microsoft Azure. Here are the main steps that you need to
take:

1. Create a Microsoft Azure account


2. Choose the desired service

Create a Microsoft Azure Account


To create an account, go to the Microsoft Azure website and create a new account. The process is
straightforward and easy. You will be prompted for a credit card number despite that there is a free
option.

Choose the Desired Service


Here are the services that will be demonstrated in combination with the controls from the UI for WPF
suite in this section:

 Blob storage service demonstrated in the Blob Storage article.


 Text Translation service demonstrated in the Text Translation article.
 Text Analysis service demonstrated in the Image Analysis article.
 SQL Database service demonstrated in the SQL Database article.
 Cosmos DB service demonstrated in the Cosmos DB article.

See Also
 Blob Storage
 SQL Database
 Cosmos DB

2471
Telerik UI for Xamarin

RadListView with Azure SQL Database


 

This article demonstrates how to integrate an Azure's SQL Database and display the data using the
RadListView.

Set up the Database


You can set up the sample database by following the Create an Azure SQL database in the Azure
portal step-by-step guide.

Create the application


We are going to use a ASP.NET Web API project in combination with our Xamarin.Forms project. In
the web application, through EntityFramework's built-in functionalities we are going to connect to the
Azure SQL Database and create our models. Eventually, we are going to expose a specific table and
consume it by making a REST request within our Xamarin.Forms application.

You can take the following steps to add a web project to your solution:

1. Add new project to the solution and choose ASP.NET Web Application:

2472
Telerik UI for Xamarin

2. Choose Empty project template and the "Web API" option from the references list:

2473
Telerik UI for Xamarin

3. If you want, you can set up your SQL Server Management Studio so that it connects to the Azure
database as well.

Reverse-engineer the Database Using Entity Framework

2474
Telerik UI for Xamarin

1. Add a new item to your WEB Api project and choose ADO.NET Entity Data Model from the list of
available items.

2. Give it a suitable name and click Add. We are going to use CloudTestDatabaseEntities for the test
sample.

3. Choose EF Designer from database from the Choose Model Contents dialog.

2475
Telerik UI for Xamarin

4. Click on New Connection... and input the server name and credentials which you can obtain from
the Azure portal. Choose the SQL Server Authentication option to log on to the server.

5. Choose whether or not to include the sensitive data in the connection string, choose a name for it
and click Next.

6. Pick the database object you wish to include and click Finish.

2476
Telerik UI for Xamarin

You are now able to work with the entities you have chosen through the created DbContext -
CloudTestDatabaseEntities in our case.

Expose the Data


In order to expose some of the data from our database, we are going to create a new controller in
the web project.Right-click the Controllers folder, and add new empty "Web API 2 Controller". Name
your controller and add a method that returns the data you would like to expose. For example:

public class CustomersController : ApiController


{
public ObservableCollection<Customer> GetCustomers()
{
var viewmodel = new CustomersViewModel();
var customers = viewmodel.Customers;
return customers;

2477
Telerik UI for Xamarin

}
}
 

Where the CustomersViewModel is as follows:

public class CustomersViewModel


{
public ObservableCollection<Customer> Customers { get; set; } = new
ObservableCollection<Customer>();
CloudTestDatabaseEntities dbContext = new CloudTestDatabaseEntities();
public CustomersViewModel()
{
this.Customers = PopulateCustomers();
}

private ObservableCollection<Customer> PopulateCustomers()


{
ObservableCollection<Customer> customers = new
ObservableCollection<Customer>();

foreach (Customer customer in dbContext.Customers)


{
customers.Add(customer);
}
return customers;
}
}
 

You can now get this information through querying the server on which the web application is
deployed. For the purposes of this example, the application is hosted locally.

Consume the Data in Xamarin.Forms


We are going to use the HttpClient class from the System.Net.Http namespace in order make our
HTTP query and consume the data.

You can create a class that will hold static information such as the server address, username and
password if required, etc.

class Constants
{
public static string RestUrl = "http://localhost:51248/api/";
}
 

Here is the actual RestService class which is responsible for requesting the information and storing it
in the memory of our application:

class RestService : IRestService

2478
Telerik UI for Xamarin

{
HttpClient client;
public ObservableCollection<Customer> Customers { get; set; }

public async Task<ObservableCollection<Customer>> GetCustomersAsync()


{
Customers = new ObservableCollection<Customer>();
client = new HttpClient();
client.BaseAddress = new Uri(Constants.RestUrl);

try
{
var response = await client.GetAsync("Customers");
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
Customers =
JsonConvert.DeserializeObject<ObservableCollection<Customer>>(content);
}
}
catch (Exception ex)
{
Debug.WriteLine(@"ERROR {0}", ex.Message);
}

return Customers;
}
}
 

Where the IRestService interface is defined as:

public interface IRestService


{
Task<ObservableCollection<Customer>> GetCustomersAsync();
}
 

This RestService is used within a CustomersManager class:

public class CustomersManager


{
IRestService restService;
public CustomersManager(IRestService service)
{
restService = service;
}

public Task<ObservableCollection<Customer>> GetCustomersAsync()


{
return restService.GetCustomersAsync();
}
}

2479
Telerik UI for Xamarin

And the Customer class used within the Xamarin.Forms application:

public class Customer


{
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
}
 

So all is left in order to obtain the collection of customers is to instantiate the manager and set the
information it provides as the ItemsSource of the RadListView control defined in our application:

public static CustomersManager CustomersManager { get; private set; }


public App()
{
// The root page of your application
MainPage = new StartPage();
CustomersManager = new CustomersManager(new RestService());
}
 

And in the code-behind of the page that contains the RadListView control:

private async void PopulateListViewAsync()


{
var items = await App.CustomersManager.GetCustomersAsync();
(this.listView as RadListView).ItemsSource = items;
}
 

Here is how the RadListView is defined as well:

<telerikDataControls:RadListView x:Name="listView" Grid.Row="1">


<telerikDataControls:RadListView.ItemTemplate>
<DataTemplate>
<telerikListView:ListViewTemplateCell>
<telerikListView:ListViewTemplateCell.View>
<Grid>
<StackLayout Orientation="Horizontal">
<Label Margin="10" Text="{Binding FirstName}" />
<Label Margin="10" Text="{Binding LastName}" />
<Label Margin="10" Text="{Binding EmailAddress}"/>
</StackLayout>
</Grid>
</telerikListView:ListViewTemplateCell.View>
</telerikListView:ListViewTemplateCell>
</DataTemplate>
</telerikDataControls:RadListView.ItemTemplate>
</telerikDataControls:RadListView>

2480
Telerik UI for Xamarin

Here is the appearance of the RadListView control when run as UWP application:

See Also
 Cosmos DB
 Text Analysis
 Blob Storage

2481
Telerik UI for Xamarin

Integration between Cosmos DB and


RadListView
 

Azure Cosmos DB is a globally distributed, multi-model database service which enables you to
develop document, key-value, wide-column, and graph databases by using popular APIs and
programming models. This article will show you how to integrate the RadGridView control to work
with your remote database.

Set Up the Database


Let's start with setting up the Cosmos Db database. Microsoft Azure's documentation is pretty
detailed and shows how to achieve this step-by-step. You can review the following guide in order to
set up your database - Create a database account

Download the Default Demo Application


Once you have successfully created the database account, you can directly download a Xamarin
application which will be populated with the required information and you won't need to manually add
all the needed settings. Simply explore the sample project in order to find out how to set up your
actual application.

You should also Add a collection which is again explained in details in the step-by-step guide.

Modify the Default Xamarin Application


As you have noted if you have followed the guide provided by Microsoft, the example used there is
within a Web application. We have decided to use the functionality in a Xamarin one, so we have to
download a Xamarin test application. Here is where you can achieve this:

2482
Telerik UI for Xamarin

By default, the downloaded sample contains a ListView which represents all of the incomplete tasks
from the database. We are going to replace the default ListView element with a RadListView so we
can take advantage of its additional features and functionalities. So here is the XAML which we are
going to use:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:DocumentDBTodo"
x:Class="DocumentDBTodo.DocumentDBTodoPage"

xmlns:telerikListView="clr-namespace:Telerik.XamarinForms.DataControls.ListView;assemb
ly=Telerik.XamarinForms.DataControls"

xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te
lerik.XamarinForms.DataControls">
<Grid RowSpacing="0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<ActivityIndicator Grid.RowSpan="2"
HorizontalOptions="Center"
VerticalOptions="Center"
IsVisible="False"
IsEnabled="True"
x:Name="syncIndicator"/>
<StackLayout Grid.Row="0" BackgroundColor="#5ABAFF" Padding="10,30,10,5">
<Label TextColor="#555555" Text="Azure DocumentDB" />
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Entry x:Name="newItemName"
Placeholder="Item name" />
<StackLayout x:Name="buttonsPanel" Grid.Column="1" Orientation="Horizontal"
HorizontalOptions="StartAndExpand">
<Button Text="+"
MinimumHeightRequest="30"
Clicked="OnAdd" />
</StackLayout>
</Grid>
</StackLayout>
<telerikDataControls:RadListView x:Name="todoList"
IsPullToRefreshEnabled="True"
RefreshRequested="todoList_RefreshRequested"
IsItemSwipeEnabled="True"
SwipeOffset="120, 0, 0, 0"
SwipeThreshold="120"
Grid.Row="1">

<telerikDataControls:RadListView.ItemSwipeContentTemplate>
<DataTemplate>
<Grid Margin="0"

2483
Telerik UI for Xamarin

Padding="0"
ColumnSpacing="0"
RowSpacing="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Button Margin="0"
BackgroundColor="Red"
BorderRadius="0"
Clicked="OnComplete"
CommandParameter="{Binding .}"
Text="Complete"
WidthRequest="70" />
</Grid>
</DataTemplate>
</telerikDataControls:RadListView.ItemSwipeContentTemplate>

<telerikDataControls:RadListView.ItemTemplate>
<DataTemplate>
<telerikListView:ListViewTemplateCell>
<telerikListView:ListViewTemplateCell.View>
<Grid BackgroundColor="Orange">
<Label Margin="10" Text="{Binding Text}" TextColor="Gray" />
</Grid>
</telerikListView:ListViewTemplateCell.View>
</telerikListView:ListViewTemplateCell>
</DataTemplate>
</telerikDataControls:RadListView.ItemTemplate>
</telerikDataControls:RadListView>
</Grid>
</ContentPage>
 

The newItemName Entry is used for choosing a name for the item which we are going to add. By
clicking the Button we are going to add this item to our database:

async Task AddItem (TodoItem item)


{
await manager.InsertItemAsync (item);
todoList.ItemsSource = await manager.GetTodoItemsAsync ();
}
 

The TodoItem and TodoItemManager classes are kept the same as well. We are also going to reuse
the async methods for querying the database and adding new items to it. So basically, we just need
to make sure that the RadListView component gets the correct items. Here is the async method that
is responsible for this:

private async Task RefreshItems (bool showActivityIndicator)


{
using (var scope = new ActivityIndicatorScope (syncIndicator,
showActivityIndicator)) {

2484
Telerik UI for Xamarin

todoList.ItemsSource = await manager.GetTodoItemsAsync ();


}
}
 

And its actual implementation in the TodoItemManager class:

public async Task<List<TodoItem>> GetTodoItemsAsync ()


{
try {
// The query excludes completed TodoItems
var query = client.CreateDocumentQuery<TodoItem> (collectionLink, new
FeedOptions { MaxItemCount = -1 })
.Where (todoItem => todoItem.Complete == false)
.AsDocumentQuery ();

Items = new List<TodoItem> ();


while (query.HasMoreResults) {
Items.AddRange (await query.ExecuteNextAsync<TodoItem> ());
}

} catch (Exception e) {
Console.Error.WriteLine (@"ERROR {0}", e.Message);
return null;
}

return Items;
}
 

Note that the Microsoft.Azure.DocumentDB.Core package is installed for the project in order to use
this functionality
 
Here is the appearance of the RadListView in Android after we have added several items in our
database:

2485
Telerik UI for Xamarin

If you have a look at the Data Explorer in Azure's portal, you will notice that the items are correctly
added:

We have defined the RadListView so that an item is marked as complete by clicking the button within
its custom Swipe ItemTemplate:

2486
Telerik UI for Xamarin

After the updates, you can notice that the individual item marked as complete is updated as well:

You can investigate the other methods in the TodotItemManager and consider taking such approach
in your application as well.

See Also
 Blob Storage
 SQL Database
 Text Analysis

2487
Telerik UI for Xamarin

Blob Storage
 

Azure Blob storage is a service for storing large amounts of unstructured object data, such as text or
binary data, that can be accessed from anywhere in the world via HTTP or HTTPS. You can use
Blob storage to expose data publicly to the world, or to store application data privately. This article
will demonstrate how one can use this service from a Xamarin application and manage the uploaded
files.

Set up Storage Account


For the purposes of this article, you will have to create an Azure Blob Storage account. You can also
check the following blog post by Brandon Minnick which explains in details how to set up the service
and create a simple Xamarin.Forms application which uses the Azure Blob Storage - Add Cloud
Storage to Xamarin Apps with Azure Blob Storage.

For the purposes of this sample, we have created a container which contains several photos:

Create the Xamarin Application


We are going to create a simple Xamarin.Forms application which will contain a RadSlideView
control which will visualize the different photos stored in the Azure Blob Storage. Here is how the
simple page is defined:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:BlobStorageXamarin"

xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
x:Class="BlobStorageXamarin.MainPage">

<telerikPrimitives:RadSlideView x:Name="slideView"
ItemsSource="{Binding PhotoSource}">

2488
Telerik UI for Xamarin

<telerikPrimitives:RadSlideView.ItemTemplate>
<DataTemplate>
<ContentView>
<Grid Margin="20">
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Label Text="{Binding Title}"
TextColor="DarkOrange"
FontSize="25"
VerticalTextAlignment="Center"
HorizontalTextAlignment="Center"/>
<Image Source="{Binding Uri}"
Grid.Row="1"></Image>
</Grid>
</ContentView>
</DataTemplate>
</telerikPrimitives:RadSlideView.ItemTemplate>
</telerikPrimitives:RadSlideView>
</ContentPage>
 

Install the NuGet package


As a next step, open the NuGet Package Manager and install the WindowsAzure.Storage package.

Set up the BlobStorage Service


We are going to reuse the BlobStorageService class from the previously referenced blog post. Here
is its exact implementation:

public class BlobStorageService


{

readonly static CloudStorageAccount _cloudStorageAccount =


CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=telerikcloud;Acc
ountKey="your account key";EndpointSuffix=core.windows.net");

2489
Telerik UI for Xamarin

readonly static CloudBlobClient _blobClient =


_cloudStorageAccount.CreateCloudBlobClient();

public static async Task<List<T>> GetBlobs<T>(string containerName, string prefix


= "", int? maxresultsPerQuery = null, BlobListingDetails blobListingDetails =
BlobListingDetails.None) where T : ICloudBlob
{
var blobContainer = _blobClient.GetContainerReference(containerName);

var blobList = new List<T>();


BlobContinuationToken continuationToken = null;

try
{
do
{
var response = await blobContainer.ListBlobsSegmentedAsync(prefix, true,
blobListingDetails, maxresultsPerQuery, continuationToken, null, null);
continuationToken = response?.ContinuationToken;
foreach (var blob in response?.Results?.OfType<T>())
{
blobList.Add(blob);
}
} while (continuationToken != null);
}
catch (Exception e)
{
//Handle Exception
}
return blobList;
}

public static async Task<CloudBlockBlob> SaveBlockBlob(string containerName,


byte[] blob, string blobTitle)
{
var blobContainer = _blobClient.GetContainerReference(containerName);
var blockBlob = blobContainer.GetBlockBlobReference(blobTitle);
await blockBlob.UploadFromByteArrayAsync(blob, 0, blob.Length);
return blockBlob;
}
}
 

And the PhotoModel class which is a representation of each photo within the photos container:

public class PhotoModel


{
public System.Uri Uri { get; set; }
public string Title { get; set; }
}
 

Now that we have the core logic of extracting the photos from the container and loading them in the
application's memory, we can set the generated collection as an ItemsSource of the RadSlideView

2490
Telerik UI for Xamarin

control. We have done this in the code-behind of the page:

public partial class MainPage : ContentPage


{
public ObservableCollection<PhotoModel> PhotoSource { get; set; }
readonly ActivityIndicator _activityIndicator = new ActivityIndicator();
public MainPage()
{
InitializeComponent();
this.PhotoSource = new ObservableCollection<PhotoModel>();
this.slideView.BindingContext = this;
Title = "Image Page";
}

protected override async void OnAppearing()


{
base.OnAppearing();
_activityIndicator.IsRunning = true;

var blobList = await BlobStorageService.GetBlobs<CloudBlockBlob>("photos");

foreach (var blob in blobList)


{
var photo = new PhotoModel { Title = blob?.Name, Uri = blob?.Uri };
PhotoSource.Add(photo);
}

_activityIndicator.IsRunning = false;
_activityIndicator.IsVisible = false;
}
}
 

Here is the resulting view in Android:

2491
Telerik UI for Xamarin

See Also
 SQL Database
 Cosmos DB

2492
Telerik UI for Xamarin

Text Translation
 

This article will guide you through the process of integrating Azure's Translator Text API with the
controls from the Telerik UI for Xamarin suite.

Create a Bing Speech API Account


Before you start, you need to create a new Translation Text API account through the Azure portal.
This has been explained in great detail in this article.

Once you've created the account, you have to obtain the subscription keys that have been
generated for you. You will require them later on in order to make API calls from your application.

Create the Application


Once we have activated the service, we can proceed with creating a simple Xamarin.Forms
application. We are going to use the following view in order to utilize the translation service:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"

xmlns:telerikListView="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Teleri

2493
Telerik UI for Xamarin

k.XamarinForms.DataControls"

xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
x:Class="AzureXamarin.TranslatorAPI.TranslatorAPIpage">
<ContentPage.Content>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="200"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<StackLayout Grid.Row="1">
<Label Text="Translate To:"/>
<telerikInput:RadSegmentedControl x:Name="segmentedControl2" SelectedIndex="1">
<telerikInput:RadSegmentedControl.ItemsSource>
<x:Array Type="{x:Type x:String}">
<x:String>English</x:String>
<x:String>French</x:String>
<x:String>German</x:String>
</x:Array>
</telerikInput:RadSegmentedControl.ItemsSource>
</telerikInput:RadSegmentedControl>
</StackLayout>
</Grid>
<StackLayout Margin="0,50,0,0" Grid.Row="1">
<Label Text="Type in something in English: "></Label>
<telerikInput:RadEntry x:Name="entry"
WatermarkText="Text to be translated..."/>
<telerikInput:RadButton x:Name="btn"
BorderRadius="5"
BorderThickness="2"
BorderColor="DarkOrange"
Text="Translate Text"
Clicked="Btn_Clicked"/>
<Label x:Name="resultLabel"
TextColor="DarkRed"
BackgroundColor="LightBlue"
HeightRequest="50"/>
</StackLayout>
</Grid>
</ContentPage.Content>
</ContentPage>
 

Add the Azure Language NuGet Package


You now have to add the Microsoft.Azure.CognitiveServices.Language NuGet package.

2494
Telerik UI for Xamarin

Use the Text Translation API


Now that we have set up the application and have created the required UI, we need to send a REST
request to the Text Translation API. It should include the text(extracted from the RadEntry) and the
language in which the text should be translated(chosen through the RadSegmented control):

public partial class TranslatorAPIpage : ContentPage


{

static string key = "your unique key";


static string host = "https://api.microsofttranslator.com";
static string path = "/V2/Http.svc/Translate";

public TranslatorAPIpage ()
{
InitializeComponent ();
}

private void Btn_Clicked(object sender, EventArgs e)


{
TranslateTextAsync(this.resultLabel);
}

public async void TranslateTextAsync(Label label)


{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", key);

string translateToLanguage = (this.segmentedControl2.ItemsSource as


string[])[this.segmentedControl2.SelectedIndex];
string textToTranslate = this.entry.Text;

string languageCode = CheckLanguageCode(translateToLanguage);

if (!translateToLanguage.Equals(String.Empty))
{
string uri = host + path + "?to=" + languageCode + "&text=" +
System.Net.WebUtility.UrlEncode(textToTranslate);
HttpResponseMessage response = await client.GetAsync(uri);
string result = await response.Content.ReadAsStringAsync();

2495
Telerik UI for Xamarin

var content = XElement.Parse(result).Value;


label.Text = " " + content;
}
}

private string CheckLanguageCode(string translateToLanguage)


{
switch (translateToLanguage)
{
case "Spanish":
return "es-es";
case "French":
return "fr-fr";
case "German":
return "de-de";
default:
return "en-en";
}
}
}
 

Now that you have everything set correctly, try typing something in English and chose the language
to which it will be translated from the RadSedmented control's options. Here is the appearance of the
view:

2496
Telerik UI for Xamarin

See Also
 Text Analysis
 Blob Storage
 SQL Database
 Cosmos DB

2497
Telerik UI for Xamarin

Text Analysis
 

This article will guide you through the process of integrating Azure's Text Analytics API with the
controls from the Telerik UI for Xamarin suite. More specifically, we are going to use the RadButton,
RadEntry and RadHorizontalLinearGauge controls in a page which can be used to determine
whether the text which is entered is in English or not as well as analyze its sentiment. The more
positive the input message is - the closer the result will be to 100 on the Gauge scale.

Create a Text Analytics API Account


Before you start, you need to create a new Text Analytics API account through the Azure portal. This
has been explained in great detail in this article.

Once you've created the account, you have to obtain the subscription keys that have been
generated for you. You will require them later on in order to make API calls from your application.

Create the Application


Once you have activated the Text Analytics service, you can proceed with creating a new
Xamarin.Forms application. We are going to use the following page for the purposes of the example:

XML
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"

2498
Telerik UI for Xamarin

xmlns:local="clr-namespace:AzureXamarin"

xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"

xmlns:telerikGauges="clr-namespace:Telerik.XamarinForms.DataVisualization.Gauges;assem
bly=Telerik.XamarinForms.DataVisualization"

xmlns:telerikCommon="clr-namespace:Telerik.XamarinForms.Common;assembly=Telerik.Xamari
nForms.Common"
x:Class="AzureXamarin.MainPage">
<StackLayout Padding="20" Margin="0,40,0,0">
<telerikInput:RadEntry x:Name="entry"
WatermarkText="Text to analyze..."/>
<telerikInput:RadButton Text="Analyze"
BorderRadius="10"
BorderColor="Red"
BorderThickness="2"
x:Name="btn"/>
<telerikGauges:RadHorizontalGauge x:Name="gauge">
<telerikGauges:RadHorizontalGauge.Axis>
<telerikGauges:GaugeLinearAxis Maximum="100"
Minimum="0"
Step="20"/>
</telerikGauges:RadHorizontalGauge.Axis>
<telerikGauges:RadHorizontalGauge.Indicators>
<telerikGauges:GaugeShapeIndicator Value="{Binding Confidence}" />
</telerikGauges:RadHorizontalGauge.Indicators>
<telerikGauges:RadHorizontalGauge.Ranges>
<telerikGauges:GaugeRangesDefinition>
<telerikGauges:GaugeRange Color="Green"
From="0"
To="80" />
<telerikGauges:GaugeGradientRange From="80"
To="100">
<telerikCommon:RadGradientStop Offset="80"
Color="Yellow" />
<telerikCommon:RadGradientStop Offset="100"
Color="Red" />
</telerikGauges:GaugeGradientRange>
</telerikGauges:GaugeRangesDefinition>
</telerikGauges:RadHorizontalGauge.Ranges>
</telerikGauges:RadHorizontalGauge>
</StackLayout>
</ContentPage>
 

Add the Microsoft.Azure.CognitiveServices.Language


NuGet Package
You can now add the Microsoft.Azure.CognitiveServices.Language.TextAnalytics NuGet package
which provides access to the Microsoft Cognitive Services Language APIs.

2499
Telerik UI for Xamarin

At the time of writing this article, the package is in preview, be sure to check "Include prerelease" to
get a search result.
 

Using the Text Analytics API


The following code snippet shows the code-behind of the previously created page where the Text
Analytics API is used:

C#
public partial class MainPage : ContentPage, INotifyPropertyChanged
{

const string subscriptionKey = "your subscription key";


private ITextAnalyticsAPI client;
public MainPage()
{
InitializeComponent();
this.BindingContext = this;

client = new TextAnalyticsAPI();


client.AzureRegion = AzureRegions.Eastus2;
client.SubscriptionKey = subscriptionKey;

btn.Clicked += Btn_ClickedAsync;
}

private double confidence;

public double Confidence


{
get { return confidence; }
set
{
this.confidence = value;
this.NotifyPropertyChanged();
}
}

private async Task<double?> MakeAnalysisRequest(string text)


{
LanguageBatchResult languageResult = await client.DetectLanguageAsync(
new BatchInput(
new List<Input>()
{
new Input("1", text)
}));

var language = languageResult.Documents.First().DetectedLanguages.First();

2500
Telerik UI for Xamarin

SentimentBatchResult sentimentResult = await client.SentimentAsync(


new MultiLanguageBatchInput(new List<MultiLanguageInput>()
{
new MultiLanguageInput(language.Iso6391Name, "1", text)
}));

var sentiment = sentimentResult.Documents.First();

return (language.Score + sentiment.Score) / 2;


}

private async void Btn_ClickedAsync(object sender, EventArgs e)


{
var result = await MakeAnalysisRequest(entry.Text);
this.Confidence = (double)(result * 100);
}

public event PropertyChangedEventHandler PropertyChanged;

private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")


{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
 

Make sure you use the correct region for client.AzureRegion. You'll get an unauthorized exception
returned from the API if your service is not located in the defined region. You can find where your
service is located in the Overview blade:
 

Running the application and typing something positive in English should give you a confidence level
close to 100. Here is the actual result:

See Also

2501
Telerik UI for Xamarin

 Text Translation
 Blob Storage
 SQL Database
 Cosmos DB

2502
Telerik UI for Xamarin

AWS (Amazon Web Services)


Amazon Web Services is a cloud platform that provides a wide range of cloud services. You can
create a free account that is available for a year and will allow you to explore the provided services.
So do not hesitate to create a new account and explore the AWS and the examples from this
section.

Here are the currently available topics:

 Getting Started
 Storage (S3)

2503
Telerik UI for Xamarin

 Simple Email Service


 Connect to data in the cloud
 DynamoDB

Prerequisites
In order to build and run the examples from the articles you will need an active AWS account. Your
system should have .NET Framework 4 or later and Visual Studio 2010 or later. In addition, we use
the AWS SDK for .NET, which provides everything you need in order to build your application using
Visual Studio. You will need to set up a security profile for DynamoDB in Visual Studio.

The Getting Started article shows how you can setup your environment.

2504
Telerik UI for Xamarin

Getting Started
This article will help you to setup your environment and start using AWS. Here are the main steps
that you need to take:

1. Create an AWS account


2. Install the AWS SDK for .NET
3. Create a user
4. Enter the credentials in Visual Studio

Create an AWS account


To create an account go to the AWS website and follow the steps there. The process is
straightforward and easy. You will be prompted for a credit card number despite that there is a free
option. There is short automatic verification via phone as well. The whole process should not take
more than 15 minutes.

Install the AWS SDK


This is straightforward as well. Just download the installer and follow the instructions. Once this is
done open Visual Studio.

There are 2 versions of the SDK for VS2013/VS2015 and VS2017.


 
Now you should see the AWS start page:

2505
Telerik UI for Xamarin

Creating a user
In order to access the AWS services you need a user. The user management is actually a service.
So navigate to the Security, Identity & Compliance and click the IAM link.

Click add new user and follow the instructions on the screen. There are 4 steps:

1. Choose the name and access (programmatic and/or management console).


2. Choose permission policy - for the first user you can use any of the existing policies(the third
icon).
3. Just confirm by pressing Create User.
4. This is a summary page which allows you to download the user details in a csv file. Click
Download and save the file. You will import this in Visual Studio.

2506
Telerik UI for Xamarin

Enter credentials in Visual Studio


This is the final step. If you do not see the AWS start page (see the first image) go to View - AWS
Explorer. Click Add New User and import the csv file.

In order to see the codes of each region, please check out the Amazon API Gateway
 

2507
Telerik UI for Xamarin

Storage (S3)
The Amazon Simple Storage Service (Amazon S3) is a storage service that allows you to upload any
kind of data at any time, from anywhere. This article will demonstrate how one can use this service
from a Xamarin application. More specifically, the example shows how to upload an image from the
device's library to the Amazon S3 Storage client.

We are going to use the Media Plugin for Xamarin and Windows to easily access the device's libraries
on the different platforms. Please check the documentation of the plugin and perform the required
steps in the Important Permission Information section in order to use the functionality in the different
platforms.

Step 1: Create the XAML layout


We are going to use the following controls from the Telerik UI for Xamarin suite in order to create the
layout which will be a simple view regarding a user of our application - RadBorder, RadDataForm,
RadButton.

[XAML] Example 1: Defining the view

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:S3sample.Portable"

xmlns:input="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinForms.In
put"

xmlns:primitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Telerik.Xamar
inForms.Primitives"
x:Class="S3sample.Portable.StartPage">
<Grid>
<Grid.Resources>
<ResourceDictionary>
<local:ImageSourceConverter x:Key="ImageSourceConverter"/>
</ResourceDictionary>
</Grid.Resources>
<Grid.RowDefinitions>
<RowDefinition Height="200"/>
<RowDefinition />
<RowDefinition Height="50"/>
</Grid.RowDefinitions>
<primitives:RadBorder BackgroundColor="LightGreen">
<Image Source="{Binding User.ImageSource, Converter={StaticResource
ImageSourceConverter}}"
x:Name="userImage"/>
</primitives:RadBorder>
<input:RadDataForm x:Name="dataForm"
Grid.Row="1"/>
<input:RadButton x:Name="upload_button"
Clicked="btn_Clicked"

2508
Telerik UI for Xamarin

Text="Upload Picture"
Grid.Row="2"/>
</Grid>
</ContentPage>
 

The ImageSourceConverter is defined as follows:

public class ImageSourceConverter : IValueConverter


{
public object Convert(object value, Type targetType, object parameter, CultureInfo
culture)
{
if (value == null)
{
return string.Empty;
}

if (Device.RuntimePlatform == Device.UWP)
{
return "Assets/" + value;
}

if (Device.RuntimePlatform == Device.iOS)
{
return ((string)value).Replace(".png", string.Empty);
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter,
CultureInfo culture)
{
throw new NotImplementedException();
}
}
 

Step 2: Install the NuGet package


Open the NuGet Package Manager and install the AWSSDK.S3 package.

2509
Telerik UI for Xamarin

If you do not have an AWS account in Visual Studio, please check the Getting Started article.
 

Step 3: Create a new bucket


Before proceeding with the example you will have to create a new bucket using the AWS
Management Console. You can learn how to do that in the Creating a Bucket article.

Step 4: Define the ViewModel


The next step is to create the ViewModel. It will need an IAmazonS3 client object which will be used
for managing the data.

[C#] Example 2: Defining the ViewModel

internal class ViewModel : NotifyPropertyChangedBase


{
private User user;
public User User
{
get { return this.user; }
set
{
this.user = value;
this.OnPropertyChanged();
}
}

public ViewModel()
{
this.User = new User();
}
}

2510
Telerik UI for Xamarin

And here is how the User class is defined:

[C#] Example 3: Defining the User business object

public class User : NotifyPropertyChangedBase


{
string name = "David";
double weight = 75.5;
int height = 178;
int age = 27;
private string imageSource = "user_image.png";

[Ignore]
public string ImageSource
{
get
{
return this.imageSource;
}
set
{
this.imageSource = value;
OnPropertyChanged();
}
}

[DisplayOptions(Header = "Name")]
public string Name
{
get { return this.name; }
set
{
if (value != this.name)
{
this.name = value;
OnPropertyChanged();
}
}
}

[DisplayOptions(Header = "Age")]
public int Age
{
get { return this.age; }
set
{
if (value != this.age)
{
this.age = value;
OnPropertyChanged();
}

2511
Telerik UI for Xamarin

}
}

[DisplayOptions(Header = "Weight (kg)")]


public double Weight
{
get { return this.weight; }
set
{
if (value != this.weight)
{
this.weight = value;
OnPropertyChanged();
}
}
}

[DisplayOptions(Header = "Height (cm)")]


public int Height
{
get { return this.height; }
set
{
if (value != this.height)
{
this.height = value;
OnPropertyChanged();
}
}
}
}
 

Here is how the page looks at this point:

2512
Telerik UI for Xamarin

Now that we have defined the User model and the ViewModel for our application, let's proceed with
setting up the connection to the S3 Service as well as registering the editors for the RadDataForm
used to show the information for the user. Here is how to do this in the code-behind of the page:

public TransferUtility s3transferUtility;


IAmazonS3 s3client;
public StartPage()
{
InitializeComponent();
this.BindingContext = new ViewModel();
(this.dataForm as RadDataForm).Source = new User();
this.dataForm.RegisterEditor(nameof(User.Age), EditorType.IntegerEditor);
this.dataForm.RegisterEditor(nameof(User.Name), EditorType.TextEditor);
this.dataForm.RegisterEditor(nameof(User.Weight), EditorType.DecimalEditor);
this.dataForm.RegisterEditor(nameof(User.Height), EditorType.IntegerEditor);
setupAWSCredentials();
}

public void setupAWSCredentials()


{

this.s3client = new AmazonS3Client("your awsAccessKeyId", "your


awsSecretKeyId", RegionEndpoint.USEast1);
var config = new AmazonS3Config() { RegionEndpoint =
Amazon.RegionEndpoint.USEast1, Timeout = TimeSpan.FromSeconds(30), UseHttp = true };

AWSConfigsS3.UseSignatureVersion4 = true;
this.s3transferUtility = new TransferUtility(s3client);
}
 

2513
Telerik UI for Xamarin

We are going to set the following logic in the event handler of the RadButton in order to add the
functionality to change the profile picture of the User and upload this picture to the S3 storage:

private async void btn_Clicked(object sender, EventArgs e)


{
var media = CrossMedia.Current;
var file = await media.PickPhotoAsync();

try
{
TransferUtilityUploadRequest request =
new TransferUtilityUploadRequest
{
BucketName = "justmybucket",
FilePath = file.Path,
Key = string.Format("Login Picture"),
ContentType = "image/png"
};

//The cancellationToken is not used within this example, however you can pass
it to the UploadAsync consutructor as well
CancellationToken cancellationToken = new CancellationToken();

await this.s3transferUtility.UploadAsync(request).ContinueWith(((x) =>


{
Debug.WriteLine("Image Uploaded");
}));
}
catch (Exception)
{
throw;
}

userImage.Source = ImageSource.FromStream(() => {


var stream = file.GetStream();
file.Dispose();
return stream;
});
}
 

Clicking on the button will allow you to choose another picture from the device's storage which is set
as the picture of the user and uploaded to the bucket you have previously created.

See Also
 DynamoDB
 Getting started with Amazon S3 Storage
 Working with Amazon S3 Buckets

2514
Telerik UI for Xamarin

Simple Email Service


Amazon SES is an email service that provides you with a way to send and receive emails using your
own email addresses and domains.

This article will demonstrate how one can use this service from a Xamarin application and send an
email to a specific address.

Step 1: Create the Xamarin Application


Create a standard Xamarin application and add several RadMaskedInput, RadEntry and RadButton
elements to it. The RadMaskedInput elements will contain the sender and receiver emails. The
subject and the email content will be entered in RadEntry elements. The button will be responsible
for sending the email.

[XAML] Example 1: Defining the view

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:AmazonPortableSES.Portable"

xmlns:telerik="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinForms.
Input"

xmlns:extensions="clr-namespace:Telerik.XamarinForms.Input.MaskedInput;assembly=Teleri
k.XamarinForms.Input"
x:Class="AmazonPortableSES.Portable.StartPage">
<ContentPage.Resources>
<ResourceDictionary>
<local:ViewModel x:Key="viewModel"/>
</ResourceDictionary>
</ContentPage.Resources>
<Grid Margin="0,50,0,0">
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
<RowDefinition Height="*" />
<RowDefinition Height="50"/>
</Grid.RowDefinitions>

<telerik:RadMaskedInput InputValue="{Binding FromEmail, Source={StaticResource


viewModel}, Mode=OneWayToSource}"
MaskType="Regex"
InvalidInputErrorText="Invalid Email Address"
Mask="{x:Static extensions:MaskExtensions.Email}"
WatermarkText="From E-mail" />

<telerik:RadMaskedInput InputValue="{Binding ToEmail, Source={StaticResource


viewModel}, Mode=OneWayToSource}"

2515
Telerik UI for Xamarin

MaskType="Regex"
InvalidInputErrorText="Invalid Email Address"
Mask="{x:Static extensions:MaskExtensions.Email}"
WatermarkText="To E-mail"
Grid.Row="1"/>

<telerik:RadEntry Text="{Binding Subject, Source={StaticResource viewModel}}"


WatermarkText="Subject"
Grid.Row="2" />

<telerik:RadEntry Text="{Binding Content, Source={StaticResource viewModel}}"


WatermarkText="Email Content"
Grid.Row="3" />

<telerik:RadButton Command="{Binding SendEmailCommand, Source={StaticResource


viewModel}}" Text="Send Email" Grid.Row="4"/>
</Grid>
/ContentPage>
 

Step 2: Add the SES assemblies


Open the NuGet Package Manager and install the AWSSDK Simple Email package.

Step 3: Define the ViewModel


The Next step is to create the ViewModel. It will need an IAmazonSimpleEmailService instance which
will be used for sending the emails. We also need to implement the command that the RadButton is
bound to.

[C#] Example 2: Defining the ViewModel

2516
Telerik UI for Xamarin

public class ViewModel


{
public ViewModel()
{
this.SendEmailCommand = new Command(OnSendEmail);
}

public Command SendEmailCommand { get; set; }

public string FromEmail { get; set; }


public string ToEmail { get; set; }
public string Subject { get; set; }
public string Content { get; set; }

private async void OnSendEmail(object obj)


{
using (var client = new AmazonSimpleEmailServiceClient("your awsAccessKeyId",
"your awsSecretAccessKey", RegionEndpoint.USEast1))
{
var sendRequest = new SendEmailRequest
{
Source = FromEmail,
Destination = new Destination { ToAddresses = new List<string> { ToEmail } },
Message = new Message
{
Subject = new Content(this.Subject),
Body = new Body { Text = new Content(this.Content) }
}
};
try
{
Debug.WriteLine("Sending email using AWS SES...");
var response = await client.SendEmailAsync(sendRequest);
Debug.WriteLine("The email was sent successfully.");
}
catch (Exception ex)
{
Debug.WriteLine("The email was not sent.");
Debug.WriteLine("Error message: " + ex.Message);
}
}
}
}
 

Figure 1: Appearance of the application on all three platforms

2517
Telerik UI for Xamarin

Step 4: Add verified email addresses


Before using the application you must verify some email addresses. If you are using the test
environment both sender and receiver addresses must be verified. This should be done from the
AWS console. You can read the Verifying an Email Address Using the Amazon SES Console article in
order to learn how to do that.

Please note that the addresses are verified for each region and the regions in the console and the
application must be the same.
 
After the addresses are added you are ready to test your application.

See Also
 Simple Email Service - Overview
 DynamoDB

2518
Telerik UI for Xamarin

Dynamo DB
This article will show you how to access data stored in a DynamoDB table by connecting to the AWS
DynamoDB service and visualize the content within a Telerik RadListView element.

Please note that you can use the local version of DynamoDB to setup and test your application. This
article shows a real example where an actual DynamoDB web service is used.
 

Step 1: Create the Application


Create a new Xamarin.Forms application and add the required assemblies in order to use the
controls from the Telerik UI for Xamarin suite. For the purpose of the example, we are going to use
the RadListView control to show the different items available within our DynamoDb instance.

Here is how the XAML layout is defined in our sample application:

[XAML] Example 1: XAML layout

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"

xmlns:datacontrols="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Telerik.X
amarinForms.DataControls"

xmlns:telerikListView="clr-namespace:Telerik.XamarinForms.DataControls.ListView;assemb
ly=Telerik.XamarinForms.DataControls"
x:Class="DynamoDb.Portable.StartPage">
<datacontrols:RadListView x:Name="DataGrid"
ItemsSource="{Binding Customers}">
<datacontrols:RadListView.ItemTemplate>
<DataTemplate>
<telerikListView:ListViewTemplateCell>
<telerikListView:ListViewTemplateCell.View>
<Grid>
<StackLayout Orientation="Horizontal" Margin="10, 10, 10, 0">
<Label Text="{Binding Name}" FontSize="16" FontAttributes="Bold"
TextColor="DarkOrange" VerticalOptions="Center" />
<Label Text="{Binding Id}" FontSize="16" FontAttributes="Bold"
TextColor="Black" VerticalOptions="Center" />
</StackLayout>
<StackLayout Orientation="Horizontal" Grid.Row="1" Margin="10, 0, 10, 10">
<Label Text="State: " FontSize="13" FontAttributes="Italic" TextColor="Gray" />
<Label Text="{Binding State}" FontSize="13" FontAttributes="Italic"
TextColor="Gray" />
</StackLayout>
</Grid>
</telerikListView:ListViewTemplateCell.View>
</telerikListView:ListViewTemplateCell>
</DataTemplate>

2519
Telerik UI for Xamarin

</datacontrols:RadListView.ItemTemplate>
</datacontrols:RadListView>
</ContentPage>
 

Step 2: Install the NuGet package


In Visual Studio open the NuGet Package Manager and install the DynamoDB module.

Figure 1: Install the DynamoDB package

Another option is to to type the following command in the NuGet Package Manager Console: PM>
Install-Package AWSSDK.DynamoDBv2

If you do not have an AWS account in Visual Studio please check the Getting Started article.
 

Step 3: Create the ViewModel


As our database contains a list of customers, define a Customer class that will hold the data for a
single record.

[C#] Example 2: The Customer class

public class Customer


{
public int Id { get; set; }

public string Name { get; set; }

public int Employees { get; set; }

public string State { get; set; }


}

2520
Telerik UI for Xamarin

Now add a class called MainWindowViewModel to the example. It will handle all the functionality for
managing the DynamoDB database.

First of all, create the Customers collection which will hold the entries from the database and the
method that creates the Customers table.

[C#] Example 3: Create the Customers table

class MainWindowViewModel : NotifyPropertyChangedBase


{
private AmazonDynamoDBClient client;
private ObservableCollection<Customer> customers;
public MainWindowViewModel()
{
try
{
this.client = new AmazonDynamoDBClient("your awsAccessKeyId", "your
awsSecretAccessKey", RegionEndpoint.USEast1);
this.Customers = new ObservableCollection<Customer>();
this.CreateCustomersTable();
this.AddCustomers();
this.LoadData(null);
}
catch (Exception ex)
{
Debug.WriteLine("Error: failed to create a DynamoDB client; " + ex.Message);
}
}

public ObservableCollection<Customer> Customers


{
get { return this.customers; }
set
{
if (this.customers != value)
{
this.customers = value;
this.OnPropertyChanged("Customers");
}
}
}

private async void CreateCustomersTable()


{
List<string> currentTables = client.ListTablesAsync().Result.TableNames;

if (!currentTables.Contains("MyCustomers"))
{
CreateTableRequest createRequest = new CreateTableRequest
{
TableName = "MyCustomers",

2521
Telerik UI for Xamarin

AttributeDefinitions = new List<AttributeDefinition>()


{
new AttributeDefinition
{
AttributeName = "Id",
AttributeType = "N"
},
new AttributeDefinition
{
AttributeName = "Name",
AttributeType = "S"
}
},
KeySchema = new List<KeySchemaElement>()
{
new KeySchemaElement
{
AttributeName = "Id",
KeyType = "HASH"
},
new KeySchemaElement
{
AttributeName = "Name",
KeyType = "RANGE"
}
},
};

createRequest.ProvisionedThroughput = new ProvisionedThroughput(1, 1);

CreateTableResponse createResponse;
try
{
createResponse = await client.CreateTableAsync(createRequest);
}
catch (Exception ex)
{
return;
}
}
}
. . .
 

Now that the table is ready you can add some data by implementing the following method inside the
ViewModel.

[C#] Example 4: Add items to the table

private async void AddCustomers()


{
var table = Amazon.DynamoDBv2.DocumentModel.Table.LoadTable(client,
"MyCustomers");

2522
Telerik UI for Xamarin

var search = table.Scan(new Amazon.DynamoDBv2.DocumentModel.Expression());


if (search.Count == 0)
{
Document dataObj1 = new Document();
dataObj1["Name"] = "Telerik";
dataObj1["Id"] = 2;
dataObj1["Employees"] = 446;
dataObj1["State"] = "NY";
await table.PutItemAsync(dataObj1);

Document dataObj2 = new Document();


dataObj2["Name"] = "Progress";
dataObj2["Id"] = 13;
dataObj2["Employees"] = 1054;
dataObj2["State"] = "IL";
await table.PutItemAsync(dataObj2);

Document dataObj3 = new Document();


dataObj3["Name"] = "NativeScript Inc.";
dataObj3["Id"] = 31;
dataObj3["Employees"] = 109;
dataObj3["State"] = "WAS";
await table.PutItemAsync(dataObj3);
}
}
 

You can then invoke the AddCustomers method in the constructor of the VieWmodel:

[C#] Example 5: Invoke the AddCustomers method in the viewmodel's constructor

public MainWindowViewModel()
{
try
{
this.client = new AmazonDynamoDBClient("your awsAccessKeyId", "your
awsSecretKeyId", RegionEndpoint.USEast1);
this.Customers = new ObservableCollection<Customer>();
this.CreateCustomersTable();
this.AddCustomers();
this.LoadData(null);
}
catch (Exception ex)
{
Debug.WriteLine("Error: failed to create a DynamoDB client; " + ex.Message);
}
}
 

Now set the DataContext of the page where the RadListView element is hosted to be the
MainWindowViewModel so that the table is created and the entries are added.

[C#] Example 6: Initialize the MainWindowViewModel

2523
Telerik UI for Xamarin

public StartPage()
{
InitializeComponent();
this.BindingContext = new MainWindowViewModel();
}
 

If you run the code at this point you will be able to see the data in your AWS console.

Step 4: Get the Data from DynamoDb


Now you are ready to populate the RadListView control with the data by iterating over the records in
the database and adding items to the Customers collection.

[C#] Example 7: Load data from the database

// MainWindowViewModel.cs
private async void LoadData(object obj)
{
var table = Amazon.DynamoDBv2.DocumentModel.Table.LoadTable(client,
"MyCustomers");
var search = table.Scan(new Amazon.DynamoDBv2.DocumentModel.Expression());

var documentList = new List<Document>();


do
{
documentList.AddRange(await search.GetNextSetAsync());

} while (!search.IsDone);

var customers = new ObservableCollection<Customer>();


foreach (var doc in documentList)
{
var customer = new Customer();
foreach (var attribute in doc.GetAttributeNames())
{

2524
Telerik UI for Xamarin

var value = doc[attribute];


if (attribute == "Id")
{
customer.Id = Convert.ToInt32(value.AsPrimitive().Value);
}
else if (attribute == "Name")
{
customer.Name = value.AsPrimitive().Value.ToString();
}
else if (attribute == "Employees")
{
customer.Employees = Convert.ToInt32(value.AsPrimitive().Value);
}
else if (attribute == "State")
{
customer.State = value.AsPrimitive().Value.ToString();
}
}

customers.Add(customer);
}

this.Customers = customers;
}
 

If you now call the LoadData method in the constructor of the viewmodel, the grid will be populated
with the entries from the AddCustomers method.

Figure 2: The populated RadListView control

2525
Telerik UI for Xamarin

See Also
 Storage (S3)

2526
Telerik UI for Xamarin

Android Exception
"java.lang.OutOfMemoryError thrown"
What to do if Android project fails to build with the following error:

COMPILETODALVIK : UNEXPECTED TOP-LEVEL error :


Exception in thread "main"
Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in
thread "main"
 

After the release of Xamarin.Android.Support libraries version 23.0.1 from Xamarin, the above
exception is thrown when compiling projects with a number of references to third-party assemblies.
To remedy this you need to increase the maximum java heap size.

In Visual Studio:
 Right-click the .Droid project and select "Properties"
 Select "Android Options"
 Select "Advanced" tab
 Enter a value for "Java Max Heap Size" e.g. 1G

In Xamarin Studio:
 Right-click the .Droid project and select "Options"
 Select "Android Build" in "Build" node
 Select "Advanced" tab
 Enter a value for "Java Heap Size" e.g. 1G

2527
Telerik UI for Xamarin

Android: Error "Attribute "showTitle" Has


Already Been Defined"
If you come across this error which prevents your Android solution from building properly, it is most
probably caused by discrepancy between the targeted Android API and the installed Android SDK
tools/Android SDK build tools.

Usually such error appears when the app targets the latest version of Android, but the latest version
of the tools is not installed. Figure 1 shows how your Android SDK Manager should be set up to be
able to target the latest version of Android (the example refers to Android 7.1 Nougat):

Figure 1: Android Application settings:

Figure 2: Android SDK Manager installed tools

2528
Telerik UI for Xamarin

See Also
 Required Android Support Libraries
 System Requirements

2529
Telerik UI for Xamarin

Problem: Controls Are Not Appearing


Some of the Telerik UI for Xamarin controls, like RadListView, RadDataGrid and RadTreeView,
use UI Virtualization, or other optimization methods, that require the visual parent to provide vertical
or horizontal space for the control to fill into.

Too Little Space

When using a parent that does not provide space for the control to appear, the UI component may
not be visible at all or be partially cut off.

A couple of these layout controls are:

 StackLayout
 Grid RowDefinition Height="Auto"

Solution
To solve this, you can take one of two routes:

Option 1 - Use HeightRequest

Give the control a definitive HeightRequest value. For example:

xml
<telerikDataControls:RadListView HeightRequest="500" .../>
 

Option 2 - Different Layout Type

Choose a more suitable parent. One that provides definitive boundaries for the control to expand
into. The most common setup for this is a Grid and use the RowDefinition with a star-sized, or
numerically-sized Height.

xml
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>

<!-- This RadListView is in the star-sized row and will expand properly -->
<telerikDataControls:RadListView .../>

<Label Text="I'm in auto-sized row" Grid.Row="1" />


</Grid>
 

2530
Telerik UI for Xamarin

Additional Note: The Too Much Space Problem

Problems can arise in the opposite circumstance. If you use a parent layout control that lets the
children expand infinitely, the UI component has no boundaries and will render all of it's items to the
full height.

This causes significant problems for UI Virtualization because all of the items will render, which
present memory problems and UI performance suffers.

An example of this is the ScrollView. In this case, the control's gestures no longer work. For
example, the user is actually scrolling the ScrollView, not the RadListView.

The solution for this is the same as above.

2531
Telerik UI for Xamarin

iOS app has issues on device but runs fine


on simulator
There are several reported issues with iOS applications that run fine on simulator but behave weird
on device. Sometimes the app crashes or throws an exception, in other occasions some element
styles looks weird or some components are not responsive.

Usually the problems are fixed when you uncheck the Enable incremental builds option from
the iOS project settings.

On Visual Studio:

On Xamarin Studio:

2532
Telerik UI for Xamarin

More Resources
 iOS Build Mechanics - Learn more about the differences between Simulator and Device build
& deployment lifecycle (e.g. JIT vs AOT compilation), along with helpful tips and tricks, in the
documentation article.
 Linker Behavior - Learn more about the mtouch linker. The linker is used to remove features
(code) from referenced libraries that the application is not using. Your project's selected
linker behavior can have significant effect on the application. For example, if "SDK and User
Assemblies" linker option is selected, any UI for Xamarin controls that do not have a
reference will be stripped out during compilation. You can avoid this by enabling
XamlCompilation (aka XamlC) or giving the control an x:Name.

2533
Telerik UI for Xamarin

Theme issues on old Android versions


The AppCompat themes provide material design styles for some widgets used as building blocks for
our components. If the AppCompat theme is not set, some elements could have weird look on old
Android versions, e.g. white text on white background.

How to set AppCompat theme?

The AppCompat theme requires FormsAppCompatActivity, which is different from the default activity
created in Xamarin.Android project - the FormsApplicationActivity. Here is how the main activity
should look like with the AppCompat theme:

[Activity(Theme = "@style/Theme.AppCompat.NoActionBar", ...)]


public class MainActivity : FormsAppCompatActivity
{
...
}
 

Here are the available themes:

 Dark: Theme.AppCompat.NoActionBar
 Light:Theme.AppCompat.Light.NoActionBar

2534
Telerik UI for Xamarin

Type not found Exception


 

In some cases you might come across such exception that concerns a specific control from the
Telerik UI for Xamarin suite. For example, the following exception might be thrown if you add a
Gauge control in your XAML without setting its x:Name attribute:

Type telerikGauges:RadRadialGauge not found in


xmlns:clr-namespace:Telerik.XamarinForms.DataVisualization.Gauges;assembly=Telerik.XamarinF
orms.DataVisualization
 
There are a couple of approaches you can take in order to resolve the issue:

Add XamlCompilation attribute for the portable assembly


The following snippet shows how to add the XamlCompilation attribute in the page code-behind:

C#
using Xamarin.Forms.Xaml;

[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
namespace
SDKBrowser.Examples.CalendarControl.GettingStartedCategory.GettingStartedExample
{
public partial class CalendarGettingStartedXaml : ContentView
{
public CalendarGettingStartedXaml()
{
this.InitializeComponent();
}
}
}
 

Add x:Name for the control


Simply add an x:Name for the control, no matter what type it is. The example shows how to do it for
a RadCalendar:

XAML
<telerikInput:RadCalendar x:Name="calendar"/>
 

2535
Telerik UI for Xamarin

TypeLoadException
AccessibilityDelegateCompat with latest
versions of AndroidX
 

This exception occurs when using Telerik UI for Xamarin 2021.2.615.1 version and below. The issue
is fixed in Telerik UI for Xamarin version - 2021.2.728.1.
 
The workaround below must be used when Telerik UI for Xamarin 2021.2.615.1 version or below is
used.
 
If you recently came across any of these exceptions when upgrading your solution:

 Exception in ListView: System.TypeLoadException: 'VTable setup of type


Telerik.XamarinForms.DataControlsRenderer.Android.ListViewAccessibilityDelegateCompat
failed'
 Exception in NumericInput, DateTimePicker and TabView: System.TypeLoadException:
'Message=VTable setup of type
Telerik.XamarinForms.Common.Android.HelpTextAccessibilityDelegateCompat failed'
 Exception in TreeView:: System.TypeLoadException: 'VTable setup of type
Telerik.XamarinForms.DataControlsRenderer.Android.TreeViewAccessibilityDelegateCompa
t failed'

The exception is caused by namespace renaming in the latest Xamarin.AndroidX.Core package. The
issue is a typo, which Xamarin team has fixed, still this is a breaking change, as now the namespace
is different. You can check it in the Xamarin.Forms github repo.

As we are built against an earlier version of the Xamarin.AndroidX.Core nuget package, this
breaking change (namespace renaming) leads to us not being able to find all classes in that
namespace as they are now in different one, hence the exceptions.

The issue happens in Xamarin.AndroidX.Core package version 1.3.2.2 or higher. The error is also
reproducible if you use another Xamarin.AndroidX package which depends on
Xamarin.AndroidX.Core 1.3.2.2 version or higher, such as Xamarin.Google.Android.Material version
1.3.0.1.

Solution
Downgrade the Xamarin.AndroidX.Core package to version to 1.3.2.1.

Also, you may need to downgrade other packages like Xamarin.AndroidX.Media to 1.2.1.1;
Xamarin.Google.Android.Material to 1.2.1.1 , etc. as they depend on the Xamarin.AndroidX.Core
package.

2536
Telerik UI for Xamarin

Here is a list of packages that depend on AndroidX.Core:

 Xamarin.AndroidX.Browser -> Xamarin.AndroidX.Core


 Xamarin.AndroidX.Media-> Xamarin.AndroidX.Core
 Xamarin.AndroidX.MediaRouter -> Xamarin.AndroidX.Media -> Xamarin.AndroidX.Core
 Xamarin.Google.Android.Material-> Xamarin.AndroidX.Core
 Xamarin.AndroidX.RecyclerView -> Xamarin.AndroidX.Core
 Xamarin.AndroidX.RecyclerView.Selection -> Xamarin.AndroidX.Core
 Xamarin.AndroidX.Legacy.Support.V4 -> Xamarin.AndroidX.Core

If you have any of these packages installed on the Android project, downgrade their version.

You can safely use the latest release of Telerik UI for Xamarin as well as the latest version of
Xamarin.Forms, just downgrade the version of the AndroidX packages.
 
In addition, please check the linker settings option. You have to set the linker to "SDK Assemblies
Only".
 

2537

You might also like