Professional Documents
Culture Documents
DOCUMENTATION
Version: R1 2022 SP
Copyright © 2022, Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved.
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.
Data Controls
DataGrid
ListView
DataForm
Pdf Viewer
PdfViewer
Calendar & Scheduling
Calendar
3
Telerik UI for Xamarin
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
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
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
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.
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.
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.
7
Telerik UI for Xamarin
Once you have installed Telerik UI for Xamarin it's time to create your first application.
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.
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.
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:
See Also
System Requirements
Telerik NuGet Server
Required Android Support Libraries
Getting started on Mac
10
Telerik UI for Xamarin
11
Telerik UI for Xamarin
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; }
}
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>
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:
See Also
System Requirements
Telerik NuGet Server
14
Telerik UI for Xamarin
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.
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;
Selection Events
17
Telerik UI for Xamarin
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:
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:
See Also
First Steps
Progress Virtual Classroom
18
Telerik UI for Xamarin
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.
Complementary Colors
19
Telerik UI for Xamarin
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
Video Tutorials
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
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.
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.
22
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
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
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.
Once you have accessed the Extension Manager, the following dialog will appear and you
should look for the Install from file option.
24
Telerik UI for Xamarin
25
Telerik UI for Xamarin
If the add-in is successfully added to Visual Studio, you should see it in the IDE extensions
section.
26
Telerik UI for Xamarin
27
Telerik UI for Xamarin
2. Select the Telerik Forms App template which can be found in Other > Miscellaneous section.
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:
See Also
System Requirements
Telerik NuGet Server
Required Android Support Libraries
Getting started on Windows
29
Telerik UI for Xamarin
For more information about Toolbox for Mac check the TelerikXamarinForms Toolbox article.
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; }
}
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>
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:
See Also
System Requirements
Telerik NuGet Server
Getting started on Mac
32
Telerik UI for Xamarin
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.
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;
Selection Events
35
Telerik UI for Xamarin
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:
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
See Also
First Steps
Progress Virtual Classroom
37
Telerik UI for Xamarin
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.
Complementary Colors
38
Telerik UI for Xamarin
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
Video Tutorials
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
40
Telerik UI for Xamarin
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.
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
Here is how the Xamarin Samples application looks when Dark Mode is applied:
43
Telerik UI for Xamarin
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
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.
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).
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
48
Telerik UI for Xamarin
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.
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
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.
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
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.
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
See Also
System Requirements
Getting Started on Windows
Getting Started on Mac
52
Telerik UI for Xamarin
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.
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
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
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
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.
58
Telerik UI for Xamarin
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.
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.
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.
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.
60
Telerik UI for Xamarin
For more information go to Setup and Install Visual Studio for Mac topic.
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.
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
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:
4. The next page allows you to download the Automatic Installation msi file, DLLs and NuGet
Packages.
63
Telerik UI for Xamarin
Installation
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
Please, make sure you have already read the System Requirements article before you proceed.
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:
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
.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
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
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.
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
71
Telerik UI for Xamarin
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.
Result: all three versions (R2 2018, R3 2018 and R1 2019) are installed in parallel on the
machine.
Result: only the latest version (R2 2019 SP2) is installed on the machine.
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
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
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:
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:
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.
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
83
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.
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
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.
See Also
Installing VSExtensions
MSI installation
Project Wizard
85
Telerik UI for Xamarin
The Item Templates are installed through a Visual Studio extension file(vsix) which can be found in
the VSExtensions folder of your local installation.
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:
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.
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:
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.
90
Telerik UI for Xamarin
Singleline Items
In the SearchViewSingleLineItems template, only a single line of information regarding the specific
item is present.
91
Telerik UI for Xamarin
Twoline 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.
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.
94
Telerik UI for Xamarin
See Also
System Requirements
Getting Started on Windows
Getting Started on Mac
95
Telerik UI for Xamarin
Please, make sure you have already read the System Requirements article before you proceed.
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:
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.
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:
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.
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.
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
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.
Once you have accessed the Extension Manager, the following dialog will appear and you should
look for the Install from file option.
103
Telerik UI for Xamarin
104
Telerik UI for Xamarin
If the add-in is successfully added to Visual Studio, you should see it in the IDE extensions section.
105
Telerik UI for Xamarin
The Telerik Xamarin UI Application template can be found in Other > .NET section.
106
Telerik UI for Xamarin
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
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.
Figure 1 and Figure 2 shows where you can find the options in Visual Studio for Mac:
108
Telerik UI for Xamarin
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.
See Also
Project Wizard for Visual Studio for Mac
Telerik NuGet packages server
110
Telerik UI for Xamarin
The controls in the Telerik UI for Xamarin suite require specific AndroidX packages references inside
the Android project to render correctly on Android.
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
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
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
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.
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
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.
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.
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.
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§uper&P@§§word).
We strongly discourage entering your password into an online encoder utility, use Powershell
instead. Here's one example:
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
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.
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
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
Т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.
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.
127
Telerik UI for Xamarin
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:
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
3. If the upgrade is major (i.e. from R3 2018 to R1 2019), check the Release History.
130
Telerik UI for Xamarin
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:
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.
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
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.
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
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();
138
Telerik UI for Xamarin
accordion.Children.Add(ratingSection);
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;
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.
The option for collapsing all items is available with R1 2020 release of Telerik UI for Xamarin.
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.
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>
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
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
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;
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.
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
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..." };
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"
};
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
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”.
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"/>
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
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" />
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.
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;
}
160
Telerik UI for Xamarin
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
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;
}
163
Telerik UI for Xamarin
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"
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"
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:
Example
Add the telerikInput namespace:
XML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
XML
<telerikInput:RadAutoComplete x:Name="radAutoComplete"
FilteredItemsChanged="RadAutoComplete_OnFilteredItemsChanged"
SuggestionItemSelected="RadAutoComplete_OnSuggestionItemSelected" />
C#
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
168
Telerik UI for Xamarin
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.
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.
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
XAML
<telerikInput:RadAutoCompleteView x:Name="autoCompleteView" Watermark="Search here..."
/>
C#
var autoCompleteView = new RadAutoCompleteView { Watermark = "Search here..." };
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
173
Telerik UI for Xamarin
C#
using Telerik.XamarinForms.Input;
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"
};
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.
XAML
<telerikInput:RadAutoCompleteView x:Name="autoCompleteViewTokens"
ItemsSource="{Binding Source}"
TextSearchPath="Name"
BackgroundColor="White"
DisplayMode="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" />
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" />
XAML
<telerikInput:RadAutoCompleteView x:Name="autoCompleteViewSuggestionView"
ItemsSource="{Binding Source}"
TextSearchPath="Name"
ShowSuggestionView="True"
SuggestionViewHeight="100"
SuggestionViewBackgroundColor="LightBlue"/>
SuggestionView Position
178
Telerik UI for Xamarin
(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:
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; }
}
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
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"/>
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"/>
XAML
<telerikInput:RadAutoCompleteView x:Name="autoCompleteViewSuggestAppend"
SuggestMode="SuggestAppend"
ItemsSource="{Binding Source}"
TextSearchPath="Name"
Watermark="AutoCompleteView SuggestAppend"
SuggestionViewHeight="100"/>
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 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
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"),
};
}
}
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>
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
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.
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; }
}
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
XAML
<telerikInput:RadAutoCompleteView x:Name="autoCompleteView"
ImagePath="ImageSource"
ItemsSource="{Binding Source}"
TextSearchPath="Name"
Watermark="Show Suggestions on focus"/>
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:
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; }
}
C#
public class ViewModel
{
public ObservableCollection<Client> Source { get; set; }
public ViewModel()
{
189
Telerik UI for Xamarin
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);
}
}
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>
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
190
Telerik UI for Xamarin
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; }
}
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")
};
}
}
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>
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
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.
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:
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; }
}
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
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;
C#
private void AutoCompleteView_Focused(object sender, FocusEventArgs e)
{
this.autoCompleteView.ShowSuggestions();
}
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 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.
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;
}
197
Telerik UI for Xamarin
}
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")
};
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
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>
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
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.
// Remove commas from the source value before comparing with the search term
var googleSearchResultNoCommas = googleSearchResult.Replace(",", "");
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.
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; }
}
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
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>
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
C#
public partial class RemoteSearch : ContentView
{
private ViewModel viewModel;
private string currentText;
private bool isRemoteSearchRunning;
public RemoteSearch()
{
InitializeComponent();
204
Telerik UI for Xamarin
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:
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
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
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>
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.
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;
}
}
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="" 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>
C#
private void TapGestureRecognizer_Tapped(object sender, EventArgs e)
{
212
Telerik UI for Xamarin
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
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; }
}
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
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>
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
215
Telerik UI for Xamarin
See Also
Tokens Support
Data Binding
216
Telerik UI for Xamarin
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; }
}
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
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>
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"
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.
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; }
}
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
}
}
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
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"
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; }
}
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")
};
}
}
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
XAML
xmlns:autoCompleteView="clr-namespace:Telerik.XamarinForms.Input.AutoCompleteView;asse
mbly=Telerik.XamarinForms.Input"
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>
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.
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.
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
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();
XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
C#
using Telerik.XamarinForms.Primitives;
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
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.
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 BadgeViewContent()
{
InitializeComponent();
}
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
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.
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.
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).
236
Telerik UI for Xamarin
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
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
Badge Position
You can use the following properties to specify the position of the badge according to its content:
Badge Alignment
You can use the following properties to specify the alignment of the badge according to its content:
240
Telerik UI for Xamarin
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.
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>
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:
BadgeAnimationDuration(int): Specifies the duration for the badge animation in milliseconds. The
default value is 300.
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>
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.
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>
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
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:
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>
XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
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>
250
Telerik UI for Xamarin
In order to override the default control template you will need to set implicit style with
TargetType="telerikPrimitives:Badge"
Default ControlTemplate
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>
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>
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>
XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
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.
Badge Features
Badge has the following properties:
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>
XAML
<telerikPrimitives:Badge/>
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.
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
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.
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
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>
XAML
xmlns:telerikBarcode="clr-namespace:Telerik.XamarinForms.Barcode;assembly=Telerik.Xama
rinForms.Barcode"
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.
EAN13
EAN8
UPC-A
UPC-E
Code39
QRCode
PDF417
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>
XAML
xmlns:telerikBarcode="clr-namespace:Telerik.XamarinForms.Barcode;assembly=Telerik.Xama
rinForms.Barcode"
264
Telerik UI for Xamarin
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>
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.
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>
See Also
Supported Types
266
Telerik UI for Xamarin
Supported Types
There are two types of barcodes according to their dimensions:
Currently, RadBarcode supports QR Code, PDF417, SwissQR Code and DataMatrix 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
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.
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 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:
XAML
xmlns:telerikBarcode="clr-namespace:Telerik.XamarinForms.Barcode;assembly=Telerik.Xama
rinForms.Barcode"
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>
XAML
xmlns:telerikBarcode="clr-namespace:Telerik.XamarinForms.Barcode;assembly=Telerik.Xama
rinForms.Barcode"
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.
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.
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:
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
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.
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:
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.
XAML
xmlns:telerikBarcode="clr-namespace:Telerik.XamarinForms.Barcode;assembly=Telerik.Xama
rinForms.Barcode"
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>
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.
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.
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
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>
XAML
xmlns:telerikBarcode="clr-namespace:Telerik.XamarinForms.Barcode;assembly=Telerik.Xama
rinForms.Barcode"
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.
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.
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
293
Telerik UI for Xamarin
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>
XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
C#
using Telerik.XamarinForms.Primitives;
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.
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"
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>
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.
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.
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
To use the busy indicator you can include the following namespaces:
C#
using Telerik.XamarinForms.Primitives;
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
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.
AnimationContentWidthRequest
AnimationContentHeightRequest
AnimationColor
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>
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
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;
});
305
Telerik UI for Xamarin
Device.StartTimer(TimeSpan.FromMilliseconds(5000),
() =>
{
radBusyIndicator.IsBusy = false;
return false;
});
See Also
Project Wizard
Getting Started
306
Telerik UI for Xamarin
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>
XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
307
Telerik UI for Xamarin
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
See Also
Animations
309
Telerik UI for Xamarin
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; }
}
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);
}
310
Telerik UI for Xamarin
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>
C#
this.BindingContext = new ViewModel();
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.
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
XAML
<telerikInput:RadButton x:Name="button"
Text="Click me!"
BorderThickness="2"
BorderColor="#4488F6"
Clicked="button_Clicked"/>
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
C#
using Telerik.XamarinForms.Input;
C#
317
Telerik UI for Xamarin
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.
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.
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
The next snippet shows how you can apply the background image.
XAML
<telerikInput:RadButton x:Name="buttonBackground"
Text="Click me!"
BackgroundImage="button_backgroundImage.png" />
See Also
Circular Button
Button with disabled text color
320
Telerik UI for Xamarin
You could easily create circular buttons with RadButton by adjusting its Width, Height and
BorderRadius properties following the next instructions:
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" />
321
Telerik UI for Xamarin
See Also
Button Getting Started
322
Telerik UI for Xamarin
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.
C#
public class MyRadButton : RadButton
{
}
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
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)
{
}
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()
{
}
325
Telerik UI for Xamarin
}
}
Figure 1 shows the appearance of the disabled RadButton once the custom renderers have been
added to your application.
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.
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
XAML
<telerikInput:RadCalendar x:Name="calendar"/>
C#
var calendar = new RadCalendar();
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:
Day ViewMode
333
Telerik UI for Xamarin
Month ViewMode
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.
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
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.
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:
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>
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.
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>
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:
342
Telerik UI for Xamarin
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
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:
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
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.
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.
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>
XAML
<telerikInput:AgendaStickyHeaderStyle x:Key="MyStickyHeaderStyle"
TextColor="#EE6D4C"
FontAttributes="Bold"
FontSize="20"
HorizontalTextAlignment="Center"
DecorationColor="#EE6D4C"
DecorationHeight="5"/>
349
Telerik UI for Xamarin
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.
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;
}
return null;
}
351
Telerik UI for Xamarin
item.StartDate.Year)
{
return this.CurrentMonthWeeksStyle;
}
return null;
}
return null;
}
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>
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.
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);
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:
The table below lists the supported selection modes for each view mode:
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" />
358
Telerik UI for Xamarin
See Also
Date Properties
View Modes
Events
359
Telerik UI for Xamarin
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.
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; }
}
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>
361
Telerik UI for Xamarin
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
365
Telerik UI for Xamarin
The following example shows how to set AppointmentContentTemplate in DayView Mode using
DataTemplateSelector.
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; }
if (appointmentsTemplate.IsAllDay)
{
366
Telerik UI for Xamarin
return this.AllDay;
}
return this.NotAllDay;
}
}
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>
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>
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
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>
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 Example
First you need to set the ViewMode to Day:
C#
calendar.ViewMode = CalendarViewMode.Day;
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
C#
appointment.RecurrenceRule = new RecurrenceRule(pattern);
C#
appointment.RecurrenceRule.Exceptions.Add(new ExceptionOccurrence() { ExceptionDate =
date.AddDays(1) });
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.
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
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
WeekDays
Saturday
WeekendDays
EveryDay
Interval
If you want to set the number of days between each recurrence, you need to specify the
RecurrencePattern's Interval property.
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
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.
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
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.
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.
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.
The source string - the string which the recurrence pattern will be parsed from.
381
Telerik UI for Xamarin
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
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
Check below a quick example on how you could prevent creating an appointment before certain
time.
C#
calendar.TimeSlotTapped += CalendarTimeSlotTapped;
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");
}
}
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.
Commands
If you prefer the MVVM pattern, you can take advantage of the exposed commands which provide
the same functionality as the methods:
393
Telerik UI for Xamarin
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>
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
See Also
Appointments
View Modes
Calendar Selection
395
Telerik UI for Xamarin
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
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:
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}">
</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}"
</Grid>
</telerikPrimitives:RadBorder>
</Grid>
</ControlTemplate>
<Style TargetType="telerikInput:AddAppointmentView">
<Setter Property="SeparatorThickness" Value="2"/>
<Setter Property="ControlTemplate" Value="{StaticResource
AddAppointmentViewControlTemplate}"/>
</Style>
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"
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
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:
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>
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
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
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>
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
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.
Example:
XAML
<Style TargetType="telerikInput:DeleteAppointmentView">
<Setter Property="BackgroundColor" Value="Red"/>
</Style>
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
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.
Example
XAML
<Style TargetType="telerikInput:SaveRecurringAppointmentView">
<Setter Property="BackgroundColor" Value="Blue"/>
</Style>
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
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.
Example:
XAML
<Style TargetType="telerikInput:DeleteRecurringAppointmentView">
<Setter Property="BackgroundColor" Value="Red"/>
</Style>
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
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.
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>
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
See Also
417
Telerik UI for Xamarin
418
Telerik UI for Xamarin
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
420
Telerik UI for Xamarin
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
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
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
424
Telerik UI for Xamarin
Example
XAML
<Style TargetType="telerikInput:CustomRecurrenceView">
<Setter Property="TextColor" Value="Red"/>
<Setter Property="TitleTextColor" Value="Red"/>
<Setter Property="TitleFontSize" Value="20"/>
</Style>
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:
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.
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.
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");
}
427
Telerik UI for Xamarin
428
Telerik UI for Xamarin
See Also
View Modes
Day View
MultiDay View
Agenda View
Recurrence
Calendar Selection
429
Telerik UI for Xamarin
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.
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>();
430
Telerik UI for Xamarin
{
RecurrencePattern = dailyRecurrence
});
}
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>
C#
this.BindingContext = new ViewModel();
Here is the result after executing the example above on different platforms:
431
Telerik UI for Xamarin
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; }
return this.ShortBreakStyle;
}
432
Telerik UI for Xamarin
}
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>
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>
433
Telerik UI for Xamarin
For the example, create a custom slot that inherits from SpecialSlot class:
C#
public class BreakSlot : SpecialSlot
{
private string title;
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>();
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
});
}
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>
XAML
<DataTemplate x:Key="RestHoursTemplate">
<Label Text="{Binding Title}"
Margin="5"
TextColor="#29398D"
FontSize="10" />
</DataTemplate>
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.
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>
437
Telerik UI for Xamarin
XAML
<ResourceDictionary>
<telerikInput:CalendarSpecialSlotStyle x:Key="MyNonWorkingHoursStyle"
BackgroundColor="#FFE6D8" />
</ResourceDictionary>
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);
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
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.
441
Telerik UI for Xamarin
442
Telerik UI for Xamarin
443
Telerik UI for Xamarin
Calendar_AppointmentOKButton OK
Calendar_AppointmentCancelButton Cancel
444
Telerik UI for Xamarin
onth
Calendar_AppointmentRepeatOptionsEveryYe Every Year
ar
Calendar_AppointmentRepeatOptionsCustom Custom
445
Telerik UI for Xamarin
For detailed information on the view go to End Repeat Appointment View topic.
446
Telerik UI for Xamarin
447
Telerik UI for Xamarin
For detailed information on the view go to Save Recurring Appointment View topic.
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
Days/Months Names
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:
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.
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
See Also
Date Properties
View Modes
Appointments
453
Telerik UI for Xamarin
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:
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;
454
Telerik UI for Xamarin
455
Telerik UI for Xamarin
Example
This example demonstrates how you can customize the calendar grid lines.
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:
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
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:
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>
459
Telerik UI for Xamarin
C#
var calendar = new RadCalendar();
calendar.SetStyleForCell = this.EvaluateCellStyle;
calendar.GridLinesDisplayMode = DisplayMode.Show;
calendar.GridLinesColor = Color.Silver;
calendar.GridLinesWidth = 1;
C#
460
Telerik UI for Xamarin
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)
};
}
461
Telerik UI for Xamarin
if (dayCell.IsSelected)
{
defaultStyle.TextColor = selectedCellForegroundColor;
defaultStyle.BorderColor = Color.FromHex("FF0066CC");
}
return defaultStyle;
}
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
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
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,
};
467
Telerik UI for Xamarin
See Also
Appointments
468
Telerik UI for Xamarin
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)
{
}
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
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;
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);
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;
}
}
}
471
Telerik UI for Xamarin
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();
}
}
}
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);
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();
}
dayCell.Style.ShapeFill = null;
this.SetBordersColor(dayCell, borderColor);
this.SetBordersWidth(dayCell, 2);
}
dayCell.Style.ShapeFill = null;
this.SetBordersColor(dayCell, borderColor);
this.SetBordersWidth(dayCell, 2);
}
}
}
473
Telerik UI for Xamarin
cell.Style.TopBorderColor = uiColor;
cell.Style.LeftBorderColor = uiColor;
cell.Style.RightBorderColor = uiColor;
cell.Style.BottomBorderColor = uiColor;
}
}
474
Telerik UI for Xamarin
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>
476
Telerik UI for Xamarin
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.
XAML
<telerikInput:RadCalendar DisplayDate="2020,03,24">
<telerikInput:RadCalendar.Commands>
<commands:CalendarUserCommand Id="CellTap" Command="{Binding CellTapCommand}"/>
</telerikInput:RadCalendar.Commands>
</telerikInput:RadCalendar>
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"
C#
public partial class CellTap : ContentView
{
public CellTap()
{
InitializeComponent();
XAML
<telerikInput:RadCalendar ViewMode="Day"
DisplayDate="2020,03,24">
<telerikInput:RadCalendar.Commands>
<commands:CalendarUserCommand Id="TimeSlotTap"
Command="{Binding TimeSlotTapCommand}"/>
</telerikInput:RadCalendar.Commands>
</telerikInput:RadCalendar>
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"
C#
public partial class TimeSlotTap : ContentView
{
public TimeSlotTap()
{
InitializeComponent();
C#
using Telerik.XamarinForms.Input.Calendar.Commands;
481
Telerik UI for Xamarin
C#
public class AppointmentTapUserCommand : CalendarCommand
{
public AppointmentTapUserCommand()
{
Id = CommandId.AppointmentTap;
}
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>
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());
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
}
};
}
See Also
Events
Date Properties
View Modes
Appointments
483
Telerik UI for Xamarin
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
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
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:
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.
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
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()
};
491
Telerik UI for Xamarin
chart.Series.Add(series);
XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
C#
using Telerik.XamarinForms.Chart;
C#
public class CategoricalData
{
public object Category { get; set; }
C#
public class ViewModel
{
public ViewModel()
{
this.Data = GetCategoricalData();
}
492
Telerik UI for Xamarin
return data;
}
}
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:
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.
495
Telerik UI for Xamarin
1. Define RadCartesianChart:
XAML" class="hljs"><telerikChart:RadCartesianChart>
</telerikChart:RadCartesianChart>
<telerikChart:RadCartesianChart>
</telerikChart: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>
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>
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>
Where local is
XAML
xmlns:local="clr-namespace:[The namespace where the ViewModel class is
defined];assembly=[The assembly name]"
C#
public class CategoricalData
{
public object Category { get; set; }
497
Telerik UI for Xamarin
6. And ViewModel:
C#
public class CategoricalDataViewModel
{
public ObservableCollection<CategoricalData> Data { get; set; }
public CategoricalDataViewModel()
{
this.Data = GetCategoricalData();
}
Example
First, create the needed business object, for example:
C#
public class CategoricalData
{
public object Category { get; set; }
C#
public class CategoricalDataViewModel
{
public ObservableCollection<CategoricalData> Data { get; set; }
498
Telerik UI for Xamarin
public CategoricalDataViewModel()
{
this.Data = GetCategoricalData();
}
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");
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:
C#
public class CategoricalData
{
public object Category { get; set; }
C#
public class ViewModel
{
public ObservableCollection<CategoricalData> Data { get; set; }
public ViewModel()
{
this.Data = GetCategoricalData();
502
Telerik UI for Xamarin
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");
503
Telerik UI for Xamarin
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.
NumericalAxis
CategoricalAxis
DateTimeAxisContinuous
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
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";
}
}
}
XAML
<telerikChart:DateTimeContinuousAxis LabelFitMode="Rotate"
MajorStepUnit="Day">
<telerikChart:DateTimeContinuousAxis.LabelFormatter>
<local:DateLabelFormatter />
</telerikChart:DateTimeContinuousAxis.LabelFormatter>
</telerikChart:DateTimeContinuousAxis>
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:
C#
public class CategoricalData
{
public object Category { get; set; }
C#
public class CategoricalDataViewModel
{
509
Telerik UI for Xamarin
public CategoricalDataViewModel()
{
this.Data = GetCategoricalData();
}
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");
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:
C#
public class TemporalData
{
public DateTime Date { get; set; }
512
Telerik UI for Xamarin
}
C#
public class ViewModel
{
public ObservableCollection<TemporalData> Data { get; set; }
public ViewModel()
{
this.Data = GetDateTimeData(6);
}
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");
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
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.
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:
C#
public class TemporalData
{
public DateTime Date { get; set; }
C#
public class ViewModel
{
public ObservableCollection<TemporalData> Data { get; set; }
520
Telerik UI for Xamarin
public ViewModel()
{
this.Data = GetDateTimeData(6);
}
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");
You can find detailed information about the supported numeric formats here: Standard Numeric
522
Telerik UI for Xamarin
Format Strings.
Combining
The categorical series could be combined. Several combining strategies are supported. You can
take a look at the Grouping example.
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:
C#
public class CategoricalData
{
public object Category { get; set; }
C#
public class CategoricalViewModel
{
public ObservableCollection<CategoricalData> Data { get; set; }
public CategoricalViewModel()
{
this.Data = GetCategoricalData();
}
524
Telerik UI for Xamarin
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");
XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
C#
using Telerik.XamarinForms.Chart;
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
};
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:
C#
public class CategoricalData
{
public object Category { get; set; }
C#
public class CategoricalDataViewModel
{
public ObservableCollection<CategoricalData> Data { get; set; }
public CategoricalDataViewModel()
{
this.Data = 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
chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "Data");
XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
C#
using Telerik.XamarinForms.Chart;
A sample Bar Series example can be found in the Chart/Series folder of the SDK Samples Browser
application.
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");
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:
C#
public class CategoricalData
{
public object Category { get; set; }
C#
public class SeriesCategoricalViewModel
{
public ObservableCollection<CategoricalData> Data1 { get; set; }
public ObservableCollection<CategoricalData> Data2 { get; set; }
public SeriesCategoricalViewModel()
{
this.Data1 = GetCategoricalData1();
this.Data2 = GetCategoricalData2();
}
534
Telerik UI for Xamarin
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");
XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
C#
using Telerik.XamarinForms.Chart;
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:
Example
Here is an example how to create RadCartesianChart with ScatterArea Series:
C#
public class NumericalData
{
public double XData { get; set; }
public double YData { get; set; }
}
C#
public class NumericalViewModel
{
public ObservableCollection<NumericalData> Data { get; set; }
public NumericalViewModel()
{
this.Data = GetNumericData();
}
539
Telerik UI for Xamarin
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");
XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
C#
using Telerik.XamarinForms.Chart;
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:
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:
C#
public class NumericalData
{
public double XData { get; set; }
public double YData { get; set; }
}
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
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");
XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
C#
using Telerik.XamarinForms.Chart;
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>
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:
C#
public class NumericalData
{
public double XData { get; set; }
public double YData { get; set; }
}
C#
public class SeriesNumericalViewModel
{
public ObservableCollection<NumericalData> Data1 { get; set; }
public ObservableCollection<NumericalData> Data2 { get; set; }
public SeriesNumericalViewModel()
{
this.Data1 = GetNumericData1();
this.Data2 = GetNumericData2();
}
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");
XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
C#
using Telerik.XamarinForms.Chart;
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:
C#
public class NumericalData
{
public double XData { get; set; }
public double YData { get; set; }
}
C#
public class SeriesNumericalViewModel
{
public ObservableCollection<NumericalData> Data1 { get; set; }
public ObservableCollection<NumericalData> Data2 { get; set; }
public SeriesNumericalViewModel()
{
this.Data1 = GetNumericData1();
this.Data2 = GetNumericData2();
}
552
Telerik UI for Xamarin
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");
XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
C#
using Telerik.XamarinForms.Chart;
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:
C#
public class NumericalData
{
public double XData { get; set; }
public double YData { get; set; }
}
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");
XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
C#
using Telerik.XamarinForms.Chart;
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:
Example
Here is an example how to create RadCartesianChart with Spline Series:
C#
public class CategoricalData
{
public object Category { get; set; }
C#
public class CategoricalDataViewModel
{
public ObservableCollection<CategoricalData> Data { get; set; }
public CategoricalDataViewModel()
{
this.Data = GetCategoricalData();
}
559
Telerik UI for Xamarin
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");
XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
C#
using Telerik.XamarinForms.Chart;
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
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:
C#
public class CategoricalData
{
public object Category { get; set; }
C#
public class CategoricalViewModel
{
public ObservableCollection<CategoricalData> Data { get; set; }
public CategoricalViewModel()
{
this.Data = GetCategoricalData();
}
563
Telerik UI for Xamarin
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
chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "Data1");
chart.Series[1].SetBinding(ChartSeries.ItemsSourceProperty, "Data2");
XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
C#
using Telerik.XamarinForms.Chart;
Customization Example
C#
var series = new SplineAreaSeries
{
565
Telerik UI for Xamarin
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.
C#
public class CategoricalData
{
public object Category { get; set; }
C#
public class SeriesCategoricalViewModel
{
public ObservableCollection<CategoricalData> Data1 { get; set; }
public ObservableCollection<CategoricalData> Data2 { get; set; }
public SeriesCategoricalViewModel()
{
this.Data1 = GetCategoricalData1();
this.Data2 = GetCategoricalData2();
}
567
Telerik UI for Xamarin
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");
XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
C#
using Telerik.XamarinForms.Chart;
569
Telerik UI for Xamarin
A sample StackBarSeries example can be found in the Chart/Series folder of the SDK Samples
Browser application.
570
Telerik UI for Xamarin
A sample StackAreaSeries example can be found in the Chart/Series folder of the SDK Samples
Browser application.
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.
C#
public class CategoricalData
{
public object Category { get; set; }
C#
public class CategoricalDataViewModel
{
public ObservableCollection<CategoricalData> Data { get; set; }
public CategoricalDataViewModel()
{
this.Data = GetCategoricalData();
}
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");
XAML
574
Telerik UI for Xamarin
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
C#
using Telerik.XamarinForms.Chart;
A sample Horizontal Bar Series example can be found in the Chart/Series folder of the SDK Samples
Browser application.
C#
public class CategoricalData
{
public object Category { get; set; }
575
Telerik UI for Xamarin
}
C#
public class SeriesCategoricalViewModel
{
public ObservableCollection<CategoricalData> Data1 { get; set; }
public ObservableCollection<CategoricalData> Data2 { get; set; }
public SeriesCategoricalViewModel()
{
this.Data1 = GetCategoricalData1();
this.Data2 = GetCategoricalData2();
}
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
XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
C#
using Telerik.XamarinForms.Chart;
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
C#
public class CategoricalData
{
public object Category { 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();
}
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:
C#
public class CategoricalData
{
public object Category { get; set; }
C#
public class ViewModel
{
public ObservableCollection<CategoricalData> Data { get; set; }
public ViewModel()
{
this.Data = 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");
XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
583
Telerik UI for Xamarin
orms.Chart"
C#
using Telerik.XamarinForms.Chart;
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
chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "SeriesData");
XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
C#
public class OhlcDataPoint : NotifyPropertyChangedBase
{
private DateTime category;
private double open;
private double high;
private double low;
private double close;
586
Telerik UI for Xamarin
if (value != this.category)
{
this.category = value;
this.OnPropertyChanged();
}
}
}
587
Telerik UI for Xamarin
{
this.close = value;
this.OnPropertyChanged();
}
}
}
}
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");
XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
C#
public class OhlcDataPoint : NotifyPropertyChangedBase
{
private DateTime category;
private double open;
private double high;
private double low;
private double close;
590
Telerik UI for Xamarin
{
if (value != this.category)
{
this.category = value;
this.OnPropertyChanged();
}
}
}
591
Telerik UI for Xamarin
if (value != this.close)
{
this.close = value;
this.OnPropertyChanged();
}
}
}
}
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");
595
Telerik UI for Xamarin
XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
C#
public class OhlcDataPoint : NotifyPropertyChangedBase
{
private DateTime category;
private double open;
private double high;
private double low;
private double close;
596
Telerik UI for Xamarin
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
Methods
Events
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:
C#
public class CategoricalData
{
public object Category { get; set; }
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();
}
}
}
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
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
chart.Series[0].SetBinding(ChartSeries.ItemsSourceProperty, "Data1");
chart.Series[1].SetBinding(ChartSeries.ItemsSourceProperty, "Data2");
XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
C#
using Telerik.XamarinForms.Chart;
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:
C#
public class CategoricalData
{
public object Category { get; set; }
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
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");
XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
607
Telerik UI for Xamarin
C#
using Telerik.XamarinForms.Chart;
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:
C#
public class CategoricalData
{
public object Category { get; set; }
C#
public class ViewModel
{
public ObservableCollection<CategoricalData> Data { get; set; }
public ViewModel()
{
this.Data = 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");
XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
C#
using Telerik.XamarinForms.Chart;
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:
C#
public class TemporalData
{
public DateTime Date { get; set; }
C#
613
Telerik UI for Xamarin
public ViewModel()
{
this.Data = new ObservableCollection<TemporalData>(GetDateTimeData(200));
}
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
XAML
xmlns:telerikChart="clr-namespace:Telerik.XamarinForms.Chart;assembly=Telerik.XamarinF
orms.Chart"
C#
using Telerik.XamarinForms.Chart;
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.
CartesianGridLineAnnotation
The CartesianGridLineAnnotation represents a vertical or horizontal line that crosses the entire plot
area.
Features
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:
C#
public class CategoricalData
{
public object Category { get; set; }
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);
}
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");
619
Telerik UI for Xamarin
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:
C#
public class CategoricalData
{
620
Telerik UI for Xamarin
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;
}
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
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:
C#
public class CategoricalData
{
public object Category { get; set; }
624
Telerik UI for Xamarin
C#
public class ViewModel
{
public ObservableCollection<CategoricalData> Data { get; set; }
public ViewModel()
{
this.Data = GetCategoricalData();
}
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");
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.
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);
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:
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
};
630
Telerik UI for Xamarin
};
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 }
};
}
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
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:
C#
public class CategoricalData
{
public object Category { get; set; }
C#
public class ViewModel
{
public ViewModel()
{
this.Data1 = GetCategoricalData1();
this.Data2 = GetCategoricalData2();
this.Data3 = GetCategoricalData3();
}
635
Telerik UI for Xamarin
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"))
}
}
};
638
Telerik UI for Xamarin
See Also
Chart SelectionBehavior
Categorical Series Combine Mode
Chart Legend
639
Telerik UI for Xamarin
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))]
C#
[assembly: ExportRenderer(typeof(Telerik.XamarinForms.Chart.RadPieChart),
typeof(Telerik.XamarinForms.ChartRenderer.Android.PieChartRenderer))]
iOS Project
Register custom renderer for CartesianChart
C#
[assembly: ExportRenderer(typeof(Telerik.XamarinForms.Chart.RadCartesianChart),
typeof(Telerik.XamarinForms.ChartRenderer.iOS.CartesianChartRenderer))]
C#
640
Telerik UI for Xamarin
[assembly: ExportRenderer(typeof(Telerik.XamarinForms.Chart.RadPieChart),
typeof(Telerik.XamarinForms.ChartRenderer.iOS.PieChartRenderer))]
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))]
C#
[assembly:
Xamarin.Forms.Platform.UWP.ExportRenderer(typeof(Telerik.XamarinForms.Chart.RadPieChar
t), typeof(Telerik.XamarinForms.ChartRenderer.UWP.PieChartRenderer))]
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()
{
}
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()
{
}
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);
}
}
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.
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.
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
645
Telerik UI for Xamarin
XAML
<StackLayout Orientation="Horizontal">
<telerikPrimitives:RadCheckBox x:Name="checkbox" />
<Label Text="Agree to the Terms & 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"});
XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
C#
using Telerik.XamarinForms.Primitives;
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).
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" />
C#
public class ViewModel : NotifyPropertyChangedBase
{
private bool? isChecked;
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.
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.
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" />
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));
}
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" />
653
Telerik UI for Xamarin
XAML
<telerikPrimitives:RadCheckBox x:Name="checkbox" IsChecked="{x:Null}"
IndeterminateColor="Brown" IndeterminateSymbolColor="Coral" />
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
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
Single Selection
Multiple 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
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
XAML
<telerikInput:RadComboBox />
C#
var combobox = new RadComboBox();
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
C#
using Telerik.XamarinForms.Input;
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();
662
Telerik UI for Xamarin
XAML
<telerikInput:RadComboBox ItemsSource="{Binding Items}"
DisplayMemberPath="Population"/>
C#
var comboBox = new RadComboBox();
comboBox.ItemsSource = this.vm.Items;
comboBox.DisplayMemberPath = "Population";
C#
public class City
{
public string Name { get; set; }
public int Population { get; set; }
}
663
Telerik UI for Xamarin
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 },
};
}
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.
XAML
<telerikInput:RadComboBox Placeholder="Select City!"
ItemsSource="{Binding Items}"
DisplayMemberPath="Name"/>
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.
XAML
<telerikInput:RadComboBox IsClearButtonVisible="False"
666
Telerik UI for Xamarin
ItemsSource="{Binding Items}"
DisplayMemberPath="Population"
IsEditable="True"
SearchTextPath="Population"
Keyboard="Numeric"/>
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.
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.
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
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.
XAML
<telerikInput:RadComboBox ItemsSource="{Binding Items}"
DisplayMemberPath="Population"/>
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
C#
public class City
{
public string Name { get; set; }
public int Population { get; set; }
}
C#
public class ViewModel
{
public ViewModel()
{
this.Items = new ObservableCollection<City>
{
669
Telerik UI for Xamarin
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"
C#
public class City
{
public string Name { get; set; }
671
Telerik UI for Xamarin
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 },
};
}
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:
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"
C#
public class StoreAddress
{
public string City { get; set; }
public string Street { get; set; }
674
Telerik UI for Xamarin
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" });
}
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.
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>
677
Telerik UI for Xamarin
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
C#
public class City
{
public string Name { get; set; }
public int Population { get; set; }
}
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];
}
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();
}
}
}
679
Telerik UI for Xamarin
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>
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
C#
public class City
{
public string Name { get; set; }
public int Population { get; set; }
}
C#
680
Telerik UI for Xamarin
this.SelectedIndex = 1;
this.SelectedItem = this.Items[2];
}
this.selectedItems.Add(this.Items[0]);
this.selectedItems.Add(this.Items[1]);
this.OnPropertyChanged();
}
}
}
681
Telerik UI for Xamarin
}
set
{
if (this.selectedIndex != value)
{
this.selectedIndex = 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.
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>
C#
public class City
{
public string Name { get; set; }
public int Population { get; set; }
}
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];
}
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();
}
}
}
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.
Commands
ComboBox has two commands related to the Selection feature:
See Also
Key Features
Data Binding
Editing
Searching
Templates
685
Telerik UI for Xamarin
Events
ComboBox for Xamarin exposes the following events:
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:
SelectAll command can be used only when SelectionMode is Multiple. An exception will be
thrown, if the command is invoked in Single SelectionMode.
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
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
C#
public class City
{
public string Name { get; set; }
public int Population { get; set; }
}
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 },
};
}
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.
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>
691
Telerik UI for Xamarin
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
C#
public class StoreAddress
{
public string City { get; set; }
public string Street { get; set; }
public string Code { get; set; }
public string WorkHours { get; set; }
}
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" });
}
692
Telerik UI for Xamarin
if (this.searchMode != value)
{
this.searchMode = value;
this.OnPropertyChanged();
}
}
}
}
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.
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="" 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>
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
C#
public class City
{
public string Name { get; set; }
public int Population { get; set; }
}
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 },
};
}
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);
}
}
}
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
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}"/>
See Also
Key Features
Header and Footer
Searching
Single and Multiple Selection
Styling
697
Telerik UI for Xamarin
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>
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
698
Telerik UI for Xamarin
C#
public class City
{
public string Name { get; set; }
public int Population { get; set; }
}
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 },
};
}
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
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>
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
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>
C#
public class City
{
public string Name { get; set; }
public int Population { get; set; }
}
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
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
Example
Here are the steps needed to achieve the functionality describe above.
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>
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
C#
708
Telerik UI for Xamarin
In addition, there is a logic inside the ViewModel whether the selection is made internally of from the
UI - SelectAll option.
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 },
};
709
Telerik UI for Xamarin
{
this.selectedItems.CollectionChanged -= this.OnSelectedItemsCollectionChanged;
}
this.selectedItems = value;
if (this.selectedItems != null)
{
this.selectedItems.CollectionChanged += this.OnSelectedItemsCollectionChanged;
}
this.OnPropertyChanged();
}
}
}
this.OnPropertyChanged();
}
}
}
710
Telerik UI for Xamarin
{
this.SelectAllChecked = false;
}
else
{
this.SelectAllChecked = !this.selectAllChecked;
}
}
return;
}
if (action == NotifyCollectionChangedAction.Remove)
{
this.isInternalCheckChanged = true;
if (this.SelectedItems.Count == 0)
{
this.SelectAllChecked = false;
}
else
{
this.SelectAllChecked = null;
}
this.isInternalCheckChanged = false;
}
}
}
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
Here are the steps needed to achieve the functionality describe above.
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>
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];
}
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
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>
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>
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 },
};
718
Telerik UI for Xamarin
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
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
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;
}
C#
public class City
{
public string Name { get; set; }
public int Population { get; set; }
}
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
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.
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
XAML
<telerikConversationalUI:RadChat x:Name="chat" />
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
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();
((INotifyCollectionChanged)this.chat.Items).CollectionChanged +=
ChatItems_CollectionChanged; ;
}
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
}
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.
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.
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>
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.
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
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." });
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
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?"});
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.
Each of these pickers is part of the RadChatPicker control and is defined through the corresponding
PickerContext property, namely DatePickerContext, TimPickerContext, ItemPickerContext, etc,
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.
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);
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.
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)
};
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:
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);
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:
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 });
}
}
};
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;
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 });
}
}
};
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.
Depending on the information that is presented, the CardContext can be one of the following types:
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);
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;
}
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.
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
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;
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;
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>
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:
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>
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;
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?" });
});
});
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
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" };
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
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>
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>
760
Telerik UI for Xamarin
<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
<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; }
}
C#
public class ViewModel : NotifyPropertyChangedBase
{
private Author me;
public ViewModel()
{
string prefix = Device.RuntimePlatform == Device.UWP ? "Assets/" : null;
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 };
}
}
C#
public class CustomChatItemTemplateSelector : ChatItemTemplateSelector
{
public DataTemplate ImportantMessageTemplate { get; set; }
765
Telerik UI for Xamarin
}
XAML
<ResourceDictionary>
<local:SimpleChatItemConverter x:Key="SimpleChatItemConverter" />
<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>
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
XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
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:
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);
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);
}
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.
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
XAML
<telerikInput:RadDataForm x:Name="dataForm" />
C#
var dataForm = new RadDataForm();
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
C#
using Telerik.XamarinForms.Input;
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();
}
}
}
776
Telerik UI for Xamarin
XAML
<telerikInput:RadDataForm x:Name="dataForm">
<telerikInput:RadDataForm.Source>
<local:SourceItem />
</telerikInput:RadDataForm.Source>
</telerikInput:RadDataForm>
C#
var dataForm = new RadDataForm
{
Source = new SourceItem()
};
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
C#
using Telerik.XamarinForms.Input;
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
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:
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; }
C#
var dataForm = new RadDataForm
{
Source = new Customer()
};
779
Telerik UI for Xamarin
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.
C#
public class CustomMetadataProvider : PropertyMetadataProviderBase
{
private readonly List<IEntityProperty> entityProperties = new
List<IEntityProperty>();
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;
781
Telerik UI for Xamarin
{
get
{
return this.propertyName;
}
}
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:
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:
783
Telerik UI for Xamarin
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:
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
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
iOS
iOS DataFormRenderer available methods for override:
GetCustomEditorType
InitEditor
UpdateEditor
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);
}
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:
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.
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;
}
}
C#
public class LocationData
{
[DisplayOptions(Header = "Location")]
[DataSourceKey("LocationsSource")]
790
Telerik UI for Xamarin
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:
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";
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);
}
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; }
}
C#
var dataForm = new RadDataForm
{
Source = new Person()
};
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:
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";
}
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:
This attribute sets the Minimum, Maximum and Step properties of the created editor (e.g.
RadSlider).
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.
C#
public enum Occupation { Unspecified, Unemployed, Employed }
[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";
}
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.
Validation modes
The selected mode is applied through ValidationMode property of the DataForm control.
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();
}
}
}
802
Telerik UI for Xamarin
this.OnPropertyChanged();
}
}
}
}
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);
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.
Commit Modes
The selected mode is applied through CommitMode property of the DataForm control.
RadDataForm provides the following methods you can use in case of manual commit mode:
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.
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");
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.
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; }
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.
XAML
<telerikInput:RadDataForm x:Name="dataForm"
CommitMode="Manual"
EditorValueChanged="DataForm_EditorValueChanged" />
807
Telerik UI for Xamarin
C#
dataForm.Source = new Customer();
dataForm.RegisterEditor(nameof(Customer.Country), EditorType.PickerEditor);
dataForm.RegisterEditor(nameof(Customer.City), EditorType.PickerEditor);
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);
}
}
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");
}
}
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; }
809
Telerik UI for Xamarin
XAML
<telerikInput:RadDataForm x:Name="dataForm"
CommitMode="Manual"
EditorValueChanged="DataForm_EditorValueChanged" />
C#
dataForm.Source = new Customer();
dataForm.RegisterEditor(nameof(Customer.Country), EditorType.PickerEditor);
dataForm.RegisterEditor(nameof(Customer.City), EditorType.PickerEditor);
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;
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));
}
}
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
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.
C#
public class SourceItem
{
[DisplayOptions(Group = "Value", Header = "1:", Position = 2)]
public int Value { get; set; } = 2;
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()
};
813
Telerik UI for Xamarin
C#
public class SourceItem
{
[DisplayOptions(Group = "Value", Header = "1:", Position = 0, ColumnPosition = 0)]
public int Value { get; set; } = 0;
}
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
};
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;
}
}
C#
public class SourceItem
{
[DisplayOptions(Group = "Value", Header = "1:", Position = 2)]
public int Value { get; set; } = 2;
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()
};
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
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.
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:
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";
};
dataForm.EditorStyle = style;
dataForm.BackgroundColor = Color.FromHex("B7D8FF");
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.
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
};
824
Telerik UI for Xamarin
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;
C#
public class Customer
{
[DisplayOptions(Group = "Basic Info", Header = "First Name")]
public string FirstName { get; set; } = "John";
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
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" };
}
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);
}
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);
}
}
}
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
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; }
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);
}
Finally, replace the default DataFormRenderer with the new one in AppDelegate.cs:
XAML
[assembly: ExportRenderer(typeof(Telerik.XamarinForms.Input.RadDataForm),
typeof(EmailPasswordEditorsRenderer))]
See Also
Autocomplete editor in Android
Editors
831
Telerik UI for Xamarin
If you run your application in Android at this stage you will notice that not all elements are modified
as expected:
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="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.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.
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:
. . .
<style name="CustomCheckBoxEditorThemeBlue">
<item name="colorControlNormal">#FFA500</item>
<item name="colorControlActivated">#FFA500</item>
</style>
834
Telerik UI for Xamarin
</resources>
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
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.
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).
XAML
<telerikDataGrid:RadDataGrid x:Name="DataGrid"/>
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:
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.
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" }
};
C#
public class Data
{
public string Country { get; set; }
840
Telerik UI for Xamarin
Binding to a DataTable
C#
public class DataTableViewModel : NotifyPropertyChangedBase
{
private DataTable data;
public DataTableViewModel()
{
this.Data = this.GetData();
}
841
Telerik UI for Xamarin
country.Columns.Add("Population", typeof(int));
country.Columns.Add("Visited On", typeof(DateTime));
country.Columns.Add("IsVisited", typeof(bool));
return country;
}
}
1. DataGrid definition:
XAML
<telerikDataGrid:RadDataGrid ItemsSource="{Binding Data}">
<telerikDataGrid:RadDataGrid.BindingContext>
<local:DataTableViewModel/>
</telerikDataGrid:RadDataGrid.BindingContext>
</telerikDataGrid:RadDataGrid>
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:
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.
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
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:DataGridTimeColumn PropertyName="Time"
HeaderText="Time Column"/>
</telerikDataGrid:RadDataGrid.Columns>
</telerikDataGrid:RadDataGrid>
xml
xmlns:telerikDataGrid="clr-namespace:Telerik.XamarinForms.DataGrid;assembly=Telerik.Xa
marinForms.DataGrid"
845
Telerik UI for Xamarin
C#
public class ColumnsViewModel
{
private ObservableCollection<Club> clubs;
C#
public class Club : INotifyPropertyChanged
{
private string name;
private DateTime established;
private DateTime time;
private int stadiumCapacity;
private bool isChampion;
private string country;
846
Telerik UI for Xamarin
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.
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
Example
849
Telerik UI for Xamarin
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
Example
XAML
<telerikGrid:DataGridNumericalColumn PropertyName="StadiumCapacity"
HeaderText="Stadium Capacity"
852
Telerik UI for Xamarin
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
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
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
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
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.
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
this.Data = source;
}
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
CellContentTemplate and CellEditTemplate properties are part of the DataGrid features from R2
2020 Official Release.
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>
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"
C#
public class ColumnsViewModel
{
private ObservableCollection<Club> clubs;
866
Telerik UI for Xamarin
C#
public class Club : INotifyPropertyChanged
{
private string name;
private DateTime established;
private DateTime time;
private int stadiumCapacity;
private bool isChampion;
private string country;
867
Telerik UI for Xamarin
{
get { return this.country; }
set { this.UpdateValue(ref this.country, value); }
}
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.
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>
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"
C#
public class ColumnsViewModel
{
private ObservableCollection<Club> clubs;
C#
public class Club : INotifyPropertyChanged
{
private string name;
private DateTime established;
private DateTime time;
private int stadiumCapacity;
871
Telerik UI for Xamarin
872
Telerik UI for Xamarin
null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(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.
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" },
};
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>
```
xml
xmlns:telerikGrid="clr-namespace:Telerik.XamarinForms.DataGrid;assembly=Telerik.Xamari
nForms.DataGrid"
```
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
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.
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>
```
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>
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
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;
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;
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
}
}
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>
xml
xmlns:telerikGrid="clr-namespace:Telerik.XamarinForms.DataGrid;assembly=Telerik.Xamari
nForms.DataGrid"
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:
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:
883
Telerik UI for Xamarin
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:
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.
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.
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.
Example
In order to illustrate how these methods can be used, let's have the following example:
C#
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Department { get; set; }
}
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" },
};
}
885
Telerik UI for Xamarin
XAML
<telerikDataGrid:RadDataGrid x:Name="dataGrid"
ItemsSource="{Binding People}" />
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:
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]));
C#
this.dataGrid.SelectAll();
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.
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:
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:
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.
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:
XAML
xmlns:telerikCommon="clr-namespace:Telerik.XamarinForms.Common.Data;assembly=Telerik.X
amarinForms.Common"
C#
using Telerik.XamarinForms.Common.Data;
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
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" },
};
}
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>
C#
this.BindingContext = new ViewModel();
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:
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>
892
Telerik UI for Xamarin
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.
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];
}
}
C#
this.dataGrid.GroupDescriptors.Add(new DelegateGroupDescriptor() { KeyLookup = new
CustomIKeyLookup() });
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:
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.
This help topic will provide an overview of the methods and commands used to control the
expand/collapse state of the DataGrid groups.
C#
var dataView = this.dataGrid.GetDataView();
C#
//expand all
var dataView = this.dataGrid.GetDataView();
dataView.ExpandAll();
//collapse all
var dataView = this.dataGrid.GetDataView();
895
Telerik UI for Xamarin
dataView.CollapseAll();
C#
var dataView = this.dataGrid.GetDataView();
var rootGroups = dataView.GetGroups();
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
XAML
xmlns:common="clr-namespace:Telerik.XamarinForms.Common.Data;assembly=Telerik.XamarinF
orms.Common"
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.
XAML
<common:TextFilterDescriptor PropertyName="Country"
Operator="StartsWith"
IsCaseSensitive="False"
Value="En"/>
897
Telerik UI for Xamarin
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"/>
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"/>
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"/>
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>
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.
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;
}
}
}
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.
900
Telerik UI for Xamarin
Show/Hide OptionsButton
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
CanUserFilter (bool): Defines a value indicating whether the user can filter the column by
using the Filtering UI.
FilterControl Template
From R2 2020 DataGrid allows you to apply filtering to the datagrid column using the
FilterControlTemplate property.
903
Telerik UI for Xamarin
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; }
return textDescriptor;
}
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>
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));
}
C#
public class City
{
public City(string name, int population)
{
this.Name = name;
this.Population = population;
}
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>
XAML
xmlns:telerikDataGrid="clr-namespace:Telerik.XamarinForms.DataGrid;assembly=Telerik.Xa
marinForms.DataGrid"
C#
public class DataTableViewModel : NotifyPropertyChangedBase
{
private DataTable data;
public DataTableViewModel()
{
this.Data = this.GetData();
}
908
Telerik UI for Xamarin
return country;
}
}
A sample Bind to DataTable example can be found in the DataGrid/DataTable folder of the SDK
Samples Browser application.
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>
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.
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);
}
}
911
Telerik UI for Xamarin
C#
public class DataTableViewModel : NotifyPropertyChangedBase
{
private DataTable data;
public DataTableViewModel()
{
this.Data = this.GetData();
}
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:
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>
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"
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.
C#
public class CustomIKeyLookup : IKeyLookup
{
public object GetKey(object instance)
{
return (instance as Club).Name.Length;
}
}
C#
this.grid.SortDescriptors.Add(new DelegateSortDescriptor() { KeyLookup = new
CustomIKeyLookup()});
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.
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);
}
}
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.
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:
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:
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
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).
All three approaches for loading items on demand in ListView work with both Automatic and Manual
LoadOnDemandMode.
921
Telerik UI for Xamarin
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;
});
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
C#
this.BindingContext = new LoadOnDemandViewModel();
You can directly explore the code in the SDK Samples Browser repository on GitHub.
XAML
<telerikGrid:RadDataGrid x:Name="dataGrid"
LoadOnDemand="DataGrid_LoadOnDemand"
LoadOnDemandMode="Automatic"
LoadOnDemandBufferItemsCount="10" />
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;
C#
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
923
Telerik UI for Xamarin
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;
}
You can directly explore the code in the SDK Samples Browser repository on GitHub.
C#
public class CustomLoadMoreDataCommand : DataGridCommand
{
public CustomLoadMoreDataCommand()
{
this.Id = DataGridCommandId.LoadMoreData;
}
924
Telerik UI for Xamarin
((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();
}
}
C#
public class LoadMoreDataCommandViewModel
{
public LoadMoreDataCommandViewModel()
{
this.Items = new ObservableCollection<Person>();
925
Telerik UI for Xamarin
C#
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Gender Gender { get; set; }
}
XAML
<telerikGrid:RadDataGrid x:Name="dataGrid"
ItemsSource="{Binding Items}"
LoadOnDemandMode="Automatic"
LoadOnDemandBufferItemsCount="10">
<telerikGrid:RadDataGrid.Commands>
<local:CustomLoadMoreDataCommand />
</telerikGrid:RadDataGrid.Commands>
</telerikGrid:RadDataGrid>
C#
this.BindingContext = new LoadMoreDataCommandViewModel();
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.
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>
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}"/>
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
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"/>
XAML
<grid:RadDataGrid x:Name="dataGrid" ItemsSource="{Binding Items}"
LoadOnDemand="dataGrid_LoadOnDemand"
LoadOnDemandMode="Manual"
LoadOnDemandRowStyle="{StaticResource CustomDataGridLoadOnDemandRowStyle}"/>
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.
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>
XAML
<grid:RadDataGrid x:Name="dataGrid" ItemsSource="{Binding Items}"
LoadOnDemand="dataGrid_LoadOnDemand"
LoadOnDemandMode="Manual"
LoadOnDemandRowTemplate="{StaticResource CustomLoadOnDemandRowTemplate}"/>
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.
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;
}
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());
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:
The execution parameter of the Editing Commands is of type EditContext that exposes the following
properties:
First, create the needed business objects, for example type Data with the following properties:
C#
public class Data
{
public string Country { get; set; }
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;
}
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;
}
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());
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:
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.
set
{
this.country = value;
this.OnPropertyChanged("Country");
}
}
938
Telerik UI for Xamarin
HashSet<object> propertyErrors;
propertyErrors.Add(errorMessage);
this.OnErrorsChanged(propertyName);
}
else
{
if (!propertyErrors.Contains(errorMessage))
{
propertyErrors.Add(errorMessage);
this.OnErrorsChanged(propertyName);
}
}
}
939
Telerik UI for Xamarin
this.OnErrorsChanged(propertyName);
}
}
else
{
if (this.errors.Remove(propertyName))
{
this.OnErrorsChanged(propertyName);
}
}
}
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" }
};
}
940
Telerik UI for Xamarin
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;
}
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));
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:
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.
XAML
<telerikGrid:RadDataGrid.RowBackgroundStyle>
<telerikGrid:DataGridBorderStyle BackgroundColor="CadetBlue"
BorderColor="DarkOrchid"
BorderThickness="1"/>
</telerikGrid:RadDataGrid.RowBackgroundStyle>
XAML
<telerikGrid:RadDataGrid.AlternateRowBackgroundStyle>
<telerikGrid:DataGridBorderStyle BackgroundColor="LightBlue"
BorderThickness="1"
BorderColor="BlanchedAlmond"/>
</telerikGrid:RadDataGrid.AlternateRowBackgroundStyle>
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
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>
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.
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.
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
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:
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.
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.
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.
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>
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;
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
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);
}
}
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);
}
}
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
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();
}
return textDescriptor;
}
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;
}
this.Owner.CommandService.ExecuteDefaultCommand(DataGridCommandId.OptionsTap,
optionsTapContext);
}
}
Figure 2 shows the appearance of the control once the custom filtering control is set.
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.
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
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
XAML
<telerikInput:RadDatePicker />
C#
using Telerik.XamarinForms.Input;
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".
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:
Examples
SpinnerFormat="MMMM dd"
XAML
<telerikInput:RadDatePicker SpinnerFormat="MMMM dd" />
968
Telerik UI for Xamarin
SpinnerFormat="dd"
XAML
<telerikInput:RadDatePicker SpinnerFormat="dd" />
969
Telerik UI for Xamarin
SpinnerFormat="MMM yyyy"
XAML
<telerikInput:RadDatePicker SpinnerFormat="MMM yyyy" />
970
Telerik UI for Xamarin
SpinnerFormat="yyyy/dd/MMM"
XAML
<telerikInput:RadDatePicker SpinnerFormat="yyyy/dd/MMM" />
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"/>
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
Example
XAML
<telerikInput:RadDatePicker Date="2020,05,15"
SpinnerFormat="yyy-MMM"/>
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"/>
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.
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"/>
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
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>
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.
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>
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>
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
981
Telerik UI for Xamarin
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.
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.
XAML
<telerikInput:RadDatePicker Date="2020,05,15"
SpinnerFormat="yyy-MMM"/>
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>
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
Events
RadTime Picker exposes a SelectionChanged event which is raised when the user picks a time
value.
Example
XAML
<telerikInput:RadDatePicker SelectionChanged="RadDatePicker_SelectionChanged"/>
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.
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.
The Accept and Cancel commands can be applied using the SelectorSettings property of
986
Telerik UI for Xamarin
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);
}
987
Telerik UI for Xamarin
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:
PickerContentView class exposes the following properties for styling the DatePicker Border and
Background Color:
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:
The SelectorSetting also provides the following properties for popup customization:
989
Telerik UI for Xamarin
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"
XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
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.
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
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
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.
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
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
XAML
<telerikInput:RadDateTimePicker />
C#
using Telerik.XamarinForms.Input;
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
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.
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
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.
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>
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
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>
1005
Telerik UI for Xamarin
XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
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".
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:
Examples
SpinnerFormat="MMMM dd"
1008
Telerik UI for Xamarin
XAML
<telerikInput:RadDateTimePicker SpinnerFormat="MMMM dd" />
SpinnerFormat="dd"
XAML
<telerikInput:RadDateTimePicker SpinnerFormat="dd" />
1009
Telerik UI for Xamarin
SpinnerFormat="H:mm"
XAML
<telerikInput:RadDateTimePicker SpinnerFormat="H:mm" />
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"/>
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).
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"/>
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.
1013
Telerik UI for Xamarin
XAML
<telerikInput:RadDateTimePicker MinimumDate="2019,12,25"
MaximumDate="2020,02,14"
SpinnerFormat="d"/>
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:
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"/>
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:
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>
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>
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
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.
1020
Telerik UI for Xamarin
XAML
<telerikInput:RadDateTimePicker>
<telerikInput:RadDateTimePicker.SelectorSettings>
<telerikInput:PickerPopupSelectorSettings IsHeaderVisible="True"/>
</telerikInput:RadDateTimePicker.SelectorSettings>
</telerikInput:RadDateTimePicker>
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
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>
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"/>
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.
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.
The Accept and Cancel commands can be applied using the SelectorSettings property of
1025
Telerik UI for Xamarin
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);
}
1026
Telerik UI for Xamarin
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:
PickerContentView class exposes the following properties for styling the DateTimePicker Border and
Background Color:
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:
1028
Telerik UI for Xamarin
button style.
The SelectorSetting also provides the following properties for popup customization:
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"
XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
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
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.
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.
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
1036
Telerik UI for Xamarin
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();
1037
Telerik UI for Xamarin
dockLayout.Children.Add(bottomGrid);
XAML
xmlns:telerikCommon="clr-namespace:Telerik.XamarinForms.Common;assembly=Telerik.Xamari
nForms.Common"
C#
using Telerik.XamarinForms.Common;
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>
1040
Telerik UI for Xamarin
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>
1041
Telerik UI for Xamarin
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>
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.
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.
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
XAML
<telerikInput:RadEntry x:Name="entry" WatermarkText="Enter first name"/>
C#
var entry = new RadEntry();
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
C#
using Telerik.XamarinForms.Input;
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:
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.
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>
C#
private void FocusButtonClicked(object sender, System.EventArgs e)
{
selectEntry.Focus();
selectEntry.CursorPosition = 7;
selectEntry.SelectionLength = 9;
}
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>
C#
private void Entry_TextChanged(object sender, TextChangedEventArgs e)
{
this.textChangedLabel.Text = $"Text changed from {e.OldTextValue} to
{e.NewTextValue}";
}
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
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" />
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.
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.
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
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);
1059
Telerik UI for Xamarin
expander.Content = stackContainer;
XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
C#
using Telerik.XamarinForms.Primitives;
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>
1061
Telerik UI for Xamarin
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>
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="›"
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.
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.
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
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
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;
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.
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;
1072
Telerik UI for Xamarin
A sample Radial Gauge example can be found in the Gauge/GaugeTypes folder of the SDK Samples
Browser application.
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.
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;
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.
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;
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.
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
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
XAML
<telerikGauges:GaugeLinearAxis LabelPosition="Start"
Maximum="4"
Minimum="0"
Step="0.5"
TickPosition="Start" />
1086
Telerik UI for Xamarin
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.
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
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 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.
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
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" />
1095
Telerik UI for Xamarin
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>
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>
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.
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>
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.
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.
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).
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
grid.Children.Add(imageEditor, 0, 0);
grid.Children.Add(toolbar, 0, 1);
this.Content = grid;
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.
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.
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:
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>
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);
}
1112
Telerik UI for Xamarin
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);
}
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);
}
SDK Browser application contains a sample SaveImage example. You can find it in the
ImageEditor/Features folder.
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>
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>
XAML
xmlns:telerikImageEditor="clr-namespace:Telerik.XamarinForms.ImageEditor;assembly=Tele
rik.XamarinForms.ImageEditor"
See Also
Custom Toolbar
Effects
Image Transformations
Toolbar Styling
1116
Telerik UI for Xamarin
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 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
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>
XAML
1118
Telerik UI for Xamarin
xmlns:telerikImageEditor="clr-namespace:Telerik.XamarinForms.ImageEditor;assembly=Tele
rik.XamarinForms.ImageEditor"
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>
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>
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:
Crop Definitions
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
Crop Tool
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>
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
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>
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>
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:
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.
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:
1132
Telerik UI for Xamarin
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>
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}}" />
XAML
<Button Grid.Row="3" Grid.Column="2" Text="Rotate <" Command="{Binding
RotateLeftCommand, Source={x:Reference imageEditor}}" />
<Button Grid.Row="3" Grid.Column="3" Text="Rotate >" 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.
You could use the CommandToolbarItem when the ImageEditorToolbar AutoGenerateItems property
is set to "False".
Example
1135
Telerik UI for Xamarin
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");
See Also
Custom Toolbar
Effects
Image Transformations
Toolbar Styling
1136
Telerik UI for Xamarin
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:
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>
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>
XAML
xmlns:telerikImageEditor="clr-namespace:Telerik.XamarinForms.ImageEditor;assembly=Tele
rik.XamarinForms.ImageEditor"
1138
Telerik UI for Xamarin
See Also
Custom Toolbar
Effects
Image Transformations
1139
Telerik UI for Xamarin
The following properties could be used for styling each item from the RadImageEditorToolbar:
Example
Here is an example how to style the Custom RadImageEditorToolbar.
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>
XAML
xmlns:telerikImageEditor="clr-namespace:Telerik.XamarinForms.ImageEditor;assembly=Tele
rik.XamarinForms.ImageEditor"
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.
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
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
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"));
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"),
};
}
C#
public class Person
{
public Person(string name, string lastName)
{
this.Name = name;
this.LastName = lastName;
}
1148
Telerik UI for Xamarin
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
C#
using Telerik.XamarinForms.Input;
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
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
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
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>
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
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:
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>
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
C#
public class City
{
public string Name { get; set; }
public int Population { get; set; }
}
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 },
};
}
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
1161
Telerik UI for Xamarin
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
To learn in details about the localization process of Telerik UI for Xamarin components, please go
through the common Localization and Globalization topic.
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"),
};
}
C#
public class Person
{
public Person(string name, string lastName)
{
this.Name = name;
this.LastName = lastName;
}
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>
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"),
};
}
C#
public class Person
{
public Person(string name, string lastName)
{
this.Name = name;
this.LastName = lastName;
}
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.
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
a sample ViewModel:
C#
public class ViewModel
{
public ICommand Accept { get; set; }
public ICommand Cancel { get; set; }
1170
Telerik UI for Xamarin
C#
public class Person
{
public Person(string name, string lastName)
{
this.Name = name;
this.LastName = lastName;
}
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:
PickerContentView class exposes the following properties for styling the ListPicker Border and
Background Color:
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:
The SelectorSetting also provides the following properties for popup customization:
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"
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
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.
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
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>
C#
public class City
{
public string Name { get; set; }
public int Population { get; set; }
}
and a ViewModel:
C#
1176
Telerik UI for Xamarin
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.
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
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.
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
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();
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:
For additional information and solutions for these layouts, please check the Controls are not
Apppearing article.
C#
public class SourceItem
{
public SourceItem(string name)
{
this.Name = name;
}
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)));
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;
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
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; }
}
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"},
};
}
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 },
};
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;
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; }
}
1189
Telerik UI for Xamarin
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>
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#
public View GetCellContent()
{
1190
Telerik UI for Xamarin
content.Children.Add(main, 0, 0);
content.Children.Add(detail, 0, 1);
return content;
}
1191
Telerik UI for Xamarin
C#
var listView = new RadListView
{
ItemsSource = new ViewModel().Source,
ItemTemplate = new DataTemplate(() =>
{
return new ListViewTemplateCell
{
View = GetCellContent()
};
}),
};
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;
The first step is to declare a simple RadListView and set its ItemsSource property to point to the
1193
Telerik UI for Xamarin
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"}
};
}
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; }
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;
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" };
}
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");
}
}
}
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>
C#
1199
Telerik UI for Xamarin
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.
C#
public class City
{
public string Name { get; set; }
public string Country { get; set; }
}
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.
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="▸" Margin="8, 12, 0, 6" TextColor="DarkGray"
FontSize="Medium">
<Label.Triggers>
1202
Telerik UI for Xamarin
C#
listView.BindingContext = new ViewModel();
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
Let's use the same example from the previous section, just add DelegateGroupDescriptor through
code instead.
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();
listView.GroupDescriptors.Add(delegateDescriptor);
}
1204
Telerik UI for Xamarin
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;
1205
Telerik UI for Xamarin
Bindable GroupDescriptor
The GroupDescriptor collection now can be controlled by users using 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}">
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
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.
C#
var dataView = this.listView.GetDataView();
C#
//expand all
var dataView = this.listView.GetDataView();
dataView.ExpandAll();
//collapse all
var dataView = this.listView.GetDataView();
dataView.CollapseAll();
1209
Telerik UI for Xamarin
C#
var dataView = this.listView.GetDataView();
var rootGroups = dataView.GetGroups();
C#
var lastItem = (listView.ItemsSource as IEnumerable<City>).Last();
var dataView = this.listView.GetDataView();
dataView.CollapseItem(lastItem);
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.
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.
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
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="▸" Margin="{Binding Level, Converter={StaticResource
LevelToMarginConverter}}"
TextColor="DarkGray" FontSize="Medium">
<Label.Triggers>
<DataTrigger TargetType="Label" Binding="{Binding IsExpanded}" Value="True">
<Setter Property="Text" Value="▾" />
</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>
1214
Telerik UI for Xamarin
See Also
Grouping
Filtering
Sorting
1215
Telerik UI for Xamarin
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.
C#
public class Event : NotifyPropertyChangedBase
{
public string _content;
public string _day;
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:
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);
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="" 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>
C#
this.BindingContext = new ViewModel();
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:
Example
Here is an example that will guide you how to use SortDescriptor in ListView.
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>
C#
public Sorting()
{
InitializeComponent();
this.BindingContext = new ViewModel();
listView.SortDescriptors.Add(new
Telerik.XamarinForms.DataControls.ListView.PropertySortDescriptor { PropertyName =
"Age", SortOrder = SortOrder.Ascending });
}
C#
public class ViewModel
{
public ViewModel()
{
this.Items = GetData();
}
return items;
}
}
1221
Telerik UI for Xamarin
C#
public class Item
{
public string Name { get; set; }
public int Age { get; set; }
}
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.
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}">
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>
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
}
C#
public class ViewModel
{
public ViewModel()
{
this.Items = GetData();
}
return items;
}
}
C#
public class Item
{
public string Name { get; set; }
public int Age { get; set; }
}
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.
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>();
}
1227
Telerik UI for Xamarin
1228
Telerik UI for Xamarin
return results;
}
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"));
}
}
}
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>
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
Example
Here is an example how to add Header and Footer to the RadListView control.
C#
public class HeaderAndFooterViewModel
{
public HeaderAndFooterViewModel()
{
this.Items = GetItems(20);
}
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>
XAML
<telerikDataControls:RadListView x:Name="listView"
ItemsSource="{Binding Items}"
HeaderTemplate="{StaticResource HeaderTemplate}"
FooterTemplate="{StaticResource FooterTemplate}"/>
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:
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.
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;
}
});
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" />
XAML
xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te
1236
Telerik UI for Xamarin
lerik.XamarinForms.DataControls"
C#
this.BindingContext = new ListViewModel();
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.
1. Define ListView:
XAML
<telerikDataControls:RadListView x:Name="listView"
IsLoadOnDemandEnabled="True"
LoadOnDemand="ListView_LoadOnDemand"
LoadOnDemandMode="Automatic" />
XAML
xmlns:telerikDataControls="clr-namespace:Telerik.XamarinForms.DataControls;assembly=Te
lerik.XamarinForms.DataControls"
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
C#
private ObservableCollection<string> source;
private int lodCounter = 0;
this.listView.IsLoadOnDemandActive = false;
}
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.
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);
}
this.IsLoadingMoreItems = false;
}
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>
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"
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.
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>
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:
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.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);
}
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.
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.
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;
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.
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
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.
1250
Telerik UI for Xamarin
C#
public class Mail : NotifyPropertyChangedBase
{
bool isUnread;
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"},
};
}
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>
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();
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.
1254
Telerik UI for Xamarin
C#
public class Book
{
public string Title { get; set; }
public string Author { 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>
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.
Example
This example demonstrates how to enable the pull to refresh functionality.
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;
1258
Telerik UI for Xamarin
{
await Task.Delay(3000);
listView.ItemsSource = Enumerable.Range(this.count, 10);
this.count += 10;
listView.EndRefresh();
}
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
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.
Example
This example will demonstrate how to enable the items reorder functionality and style the list view
items.
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
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"
};
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
Group/Reorder events
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.
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.
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
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:
C#
public class ViewModel
{
public ViewModel()
{
1266
Telerik UI for Xamarin
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>
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:
Location
This enumeration contains the following members:
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)));
1269
Telerik UI for Xamarin
You can find a working demo labeled ItemStyles in the ListView/Styling folder of the SDK Samples
Browser application.
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>
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.
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)));
1273
Telerik UI for Xamarin
})
};
C#
public class SourceItem
{
public SourceItem(string name, int age)
{
this.Name = name;
this.Age = age;
}
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
};
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:
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; }
}
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
Set it as BindingContext:
C#
this.BindingContext = new ViewModel();
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>
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; }
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;
}
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>
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;
}
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.
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.
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).
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();
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:
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>
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.
1289
Telerik UI for Xamarin
RadMap exposes properties for applying min and max zoom values.
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:
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.
SetView(LocationRect locationRect) – Sets the provided location as the current view of the
map.
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:
The above used MapSource class provides a few useful static methods that will help load the
shapefile:
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.
LocationRect GetBestView() - Gets location rectangle which represents best view for the
layer.
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.
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.
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.
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.
XAML
<Button Text="Select France" Clicked="SelectFranceClicked" />
<Button Text="Deselect France" Clicked="DeselectFranceClicked" />
C#
private void SelectFranceClicked(object sender, EventArgs e)
{
var shape = this.GetItemFromCountryName("France");
if (shape != null)
{
this.mapShapeLayer.SelectedShapes.Add(shape);
}
}
1298
Telerik UI for Xamarin
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:
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>
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
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;
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.
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>
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
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>
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.
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.
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
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.
XAML
<telerikInput:RadMaskedInput x:Name="maskedInput"
WatermarkText="Watermark"
Mask="(CC) 00"
MaskType="Text"/>
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
C#
using Telerik.XamarinForms.Input;
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.
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>
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:
See Also
Getting Started
Events
Commands
1317
Telerik UI for Xamarin
Below you can find a list of the available Regex and their usage:
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,}))$"
XAML
<telerikInput:RadMaskedInput MaskType="Regex"
InvalidInputErrorText="Invalid E-Mail format!"
ErrorColor="Red"
Keyboard="Email"
WatermarkText="Enter E-mail"
Mask="{x:Static extensions:MaskExtensions.Email}"/>
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:
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.
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.
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.
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;
}
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());
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;
}
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());
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>
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
C#
this.input.ApplyMaskStarted += Input_BeforeTextMasked;
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>
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
C#
this.input.ApplyMaskFinished += Input_AfterTextMasked;
1327
Telerik UI for Xamarin
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
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 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.
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.
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
XAML
<telerikInput:RadNumericInput x:Name="numericInput" />
C#
var numericInput = new RadNumericInput();
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
C#
using Telerik.XamarinForms.Input;
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.
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"
XAML
<telerikInput:RadNumericInput x:Name="numericMinMax" Minimum="0" Maximum="15" />
XAML
<telerikInput:RadNumericInput x:Name="numericStep" Step="10" />
1337
Telerik UI for Xamarin
XAML
<telerikInput:RadNumericInput x:Name="numericBtnText" IncreaseButtonText=" >"
DecreaseButtonText=" <" />
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" />
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.
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:
Depending on the UICulture of the current thread, the result is the following:
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.
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));
}
}
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.
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.
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).
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 });
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"
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
});
mainGrid.Children.Add(arcPath);
XAML
xmlns:telerikCommon="clr-namespace:Telerik.XamarinForms.Common;assembly=Telerik.Xamari
nForms.Common"
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:
The scheme below shows how StartAngle and SweepAngle are applied to the ArcSegment:
1353
Telerik UI for Xamarin
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.
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.
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)));
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.
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
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.
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>
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>
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.
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.
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
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.
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.
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.
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"
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;
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.
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);
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
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.
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.
1371
Telerik UI for Xamarin
XAML
<telerikPdfViewer:RadPdfViewer x:Name="pdfViewer"
SourcePasswordNeeded="pdfViewer_SourcePasswordNeeded" />
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:
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>
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;
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>
XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
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.
ZoomInToolbarItem
ZoomOutToolbarItem
NavigateToNextPageToolbarItem
NavigateToPreviousPageToolbarItem
NavigateToPageToolbarItem
FitToWidthToolbarItem
ToggleLayoutModeToolbarItem
SearchToolbarItem
Example
Here is an example how to use the RadPdfViewer Toolbar:
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>
1376
Telerik UI for Xamarin
XAML
xmlns:telerikPdfViewer="clr-namespace:Telerik.XamarinForms.PdfViewer;assembly=Telerik.
XamarinForms.PdfViewer"
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.
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=""
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();
1378
Telerik UI for Xamarin
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);
}
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
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.
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>
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;
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.
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
XAML
<telerikPdfViewer:RadPdfViewer x:Name="pdfViewer"
LinkAnnotationTapped="LinkTapped" />
C#
private void LinkTapped(object sender,
Telerik.XamarinForms.PdfViewer.Annotations.LinkAnnotationTappedEventArgs e)
{
if(e.LinkAnnotation.Action is UriAction uriAction)
{
e.Handled = true;
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
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:
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.
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>
XAML
<ResourceDictionary>
<Style TargetType="telerikPdfViewer:SelectionMenu">
<Setter Property="Fill" Value="#32CD32" />
1390
Telerik UI for Xamarin
<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>
C#
public class ViewModel : NotifyPropertyChangedBase
{
public ViewModel()
{
this.GetSelectedTextCommand = new DisplaySelectedTextCommand();
}
1391
Telerik UI for Xamarin
lock (selection)
{
selection.Clear();
}
}
}
}
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:
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>
XAML
<Style x:Key="MyToastStyle" TargetType="telerikPdfViewer:SearchToast">
<Setter Property="Fill" Value="#FF7F7F" />
<Setter Property="TextColor" Value="White" />
</Style>
1396
Telerik UI for Xamarin
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:
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>
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.
XAML
1399
Telerik UI for Xamarin
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);
}
1400
Telerik UI for Xamarin
sb.Append("|");
}
return sb.ToString();
}
}
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);
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:
See Also
Localization and Globalization
Text Search
Source Exception Handling
1405
Telerik UI for Xamarin
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>
XAML
xmlns:telerikPdfViewer="clr-namespace:Telerik.XamarinForms.PdfViewer;assembly=Telerik.
XamarinForms.PdfViewer"
C#
private void PdfViewerSourceException(object sender, SourceExceptionEventArgs e)
{
var error = e.Exception.Message;
}
1406
Telerik UI for Xamarin
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.
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.
C#
Func<CancellationToken, Task<Stream>> streamFunc = ct => Task.Run(() =>
{
Assembly assembly = typeof(Commands).Assembly;
1408
Telerik UI for Xamarin
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>
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
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.
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
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.
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;
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;
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.
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.
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 & 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 & Conditions"/>
</StackLayout>
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;
}
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.
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>
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.
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",
};
1422
Telerik UI for Xamarin
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:
1423
Telerik UI for Xamarin
Fade
Zoom
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.
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.
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).
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;
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
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" />
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>
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:
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>
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.
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.
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
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>
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:
You should either use a Grid as a parent container or define explicitly the size of the RichTextEditor
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);
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.
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>";
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.
C#
Func<CancellationToken, Task<Stream>> streamFunc = ct => Task.Run(() =>
{
Assembly assembly = typeof(KeyFeatures).Assembly;
1441
Telerik UI for Xamarin
this.richTextEditor.Source = RichTextSource.FromStream(streamFunc);
C#
var htmlString = await this.richTextEditor.GetHtmlAsync();
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:
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.
You can also take advantage of the following API related to hyperlinks:
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
Subscribe to the event, set Handled property of the event args to True to prevent the default
message and add custom implementation.
XAML
<telerikRichTextEditor:RadRichTextEditor x:Name="richTextEditor"
OpenHyperlinkError="RichTextEditor_OpenHyperlinkError"
Grid.Row="1" />
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");
}
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" />
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
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
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.
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.
See Also
Key Features
Commands
1448
Telerik UI for Xamarin
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;
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:
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:
OpenHyperlink toolbar item opens a browser and navigates to the respective URL address.
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>
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
1455
Telerik UI for Xamarin
You can insert images from Uri, Data(byte []), Stream, File. The image source is of type
RichTextImageSource.
Also you have to point out the image format type. The supported image format types(of type
RichTextImageType) are:
Gif
Jpeg
Png
Svg
Webp
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.
XAML
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<telerikRichTextEditor:RadRichTextEditorToolbar x:Name="richTextToolbar"
RichTextEditor="{x:Reference richTextEditor}" />
1456
Telerik UI for Xamarin
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;
}
if (mediaFile != null)
{
var imageSource = RichTextImageSource.FromFile(mediaFile.Path);
eventArgs.Accept(imageSource);
return;
}
}
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;
}
}
C#
Func<CancellationToken, Task<Stream>> streamFunc = ct => Task.Run(() =>
{
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.
C#
Plugin.Media.CrossMedia.Current.Initialize();
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);
}
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
Insert Images
AddImageToolbarItem
1462
Telerik UI for Xamarin
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>
XAML
xmlns:telerikRichTextEditor="clr-namespace:Telerik.XamarinForms.RichTextEditor;assembl
y=Telerik.XamarinForms.RichTextEditor"
C#
private void InitializeImages()
{
var resourceNames = this.currentAssembly.GetManifestResourceNames();
var imageSources = new List<RichTextImageSource>();
imageSources.Add(imageSource);
}
}
this.imagePicker.ItemsSource = imageSources;
}
C#
InitializeImages();
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.
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.
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
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>
XAML
xmlns:telerikRichTextEditor="clr-namespace:Telerik.XamarinForms.RichTextEditor;assembl
y=Telerik.XamarinForms.RichTextEditor"
C#
public class ViewModel
{
public ViewModel()
{
this.CustomInfoCommand = new Command(this.CustomInfoCommandExecute);
}
C#
this.BindingContext = new ViewModel();
1470
Telerik UI for Xamarin
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.
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>
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
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.
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" />
1479
Telerik UI for Xamarin
See Also
RichTextEditor Toolbar Styling
Custom Toolbar
1480
Telerik UI for Xamarin
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;
BackButtonFontFamily
BackButtonTextColor
1481
Telerik UI for Xamarin
BackButtonText
Check below an example of toolbar item with nested items and BackButton:
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.
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.
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=""
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>
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=""/>
<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>
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"
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.
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.
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
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.
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" },
};
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
C#
using Telerik.XamarinForms.Input;
1488
Telerik UI for Xamarin
C#
RadSegmentedControl segmentControlImages = new RadSegmentedControl()
{
VerticalOptions = LayoutOptions.Start,
HeightRequest = 60,
ItemsSource = new List<FileImageSource>() { "available.png", "away.png",
"busy.png" },
};
1489
Telerik UI for Xamarin
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.
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;
}
1491
Telerik UI for Xamarin
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>
C#
this.segmentControl.BindingContext = new ViewModel();
See Also
Getting Started
1492
Telerik UI for Xamarin
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.
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);
1494
Telerik UI for Xamarin
See Also
Project Wizard
Getting Started
Customize Segment Colors
1495
Telerik UI for Xamarin
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);
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.
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
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.
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
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>
XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
C#
using Telerik.XamarinForms.Primitives;
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.
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>
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
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>
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:
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.
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.
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
1509
Telerik UI for Xamarin
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" });
XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
C#
using Telerik.XamarinForms.Primitives;
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:
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.
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>
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:
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.
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())
};
}
C#
[assembly: ExportRenderer(typeof(RadSideDrawer), typeof(CustomSideDrawerRenderer))]
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:
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.
C#
public class CustomDrawerCommand : SideDrawerCommandBase
{
public CustomDrawerCommand()
{
this.Id = SideDrawerCommandId.Closed;
}
1520
Telerik UI for Xamarin
{
// implement your custom logic here
}
}
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>
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.
C#
public class CustomCommand : ICommand
{
public event EventHandler CanExecuteChanged;
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>
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.
C#
public class ViewModel
{
public ViewModel()
{
this.Command = new CustomCommand();
}
C#
public class CustomCommand : ICommand
{
public event EventHandler CanExecuteChanged;
1522
Telerik UI for Xamarin
return true;
}
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>
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.
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).
XAML
<telerikInput:RadSignaturePad BorderThickness="1" BorderColor="LightGray"/>
C#
var signaturePad = new RadSignaturePad
{
BorderColor = Color.LightGray,
BorderThickness = new Thickness(1)
};
XAML
1526
Telerik UI for Xamarin
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
C#
using Telerik.XamarinForms.Input;
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:
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"/>
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:
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.
XAML
<telerikInput:RadSignaturePad x:Name="signaturePad"
BorderThickness="1"
BorderColor="LightGray"/>
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;
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"/>
XAML
1531
Telerik UI for Xamarin
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
C#
private void RadSignaturePad_StrokeStarted(object sender, EventArgs e)
{
this.timeStampLabel.Text = DateTime.Now.ToString();
this.logInfo.Text = "";
}
C#
private void RadSignaturePad_StrokeCompleted(object sender, EventArgs e)
{
this.timeStampLabel.Text = DateTime.Now.ToString();
}
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>
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.
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
XAML
<telerikPrimitives:RadSlideView x:Name="slideView" />
C#
var listView = new SlideView();
XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
C#
using Telerik.XamarinForms.Primitives;
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>
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
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.
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>
<telerikPrimitives:SlideViewLabel AutomationId="SlideViewLeftArrow"
VerticalOptions="Center"
IsVisible="{TemplateBinding ShowButtons}"
Text="‹"
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="›"
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>
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"
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
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.
XAML
<telerikPrimitives:RadSlideView x:Name="slideView"
IndicatorText="♦"
SelectedIndicatorText="♦"
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>
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.
1546
Telerik UI for Xamarin
The control allows you to define a spacing between each slide using the PageSpacingProperty(int).
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.
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.
C#
public class MyItem
{
public string Content { get; set; }
}
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" },
};
}
}
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>
C#
slideView.BindingContext = new ViewModel();
See Also
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; }
}
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
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>
C#
this.slideView.BindingContext = new ViewModel();
1552
Telerik UI for Xamarin
See Also
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.
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;
}
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.
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
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
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.
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:
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.
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.
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
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);
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.
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.
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.
1570
Telerik UI for Xamarin
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.
Example
1571
Telerik UI for Xamarin
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];
A sample Selection example can be found in the TabView/Features folder of the SDK Samples
Browser application.
See Also
TabViewItem
TabView HeaderItem
1572
Telerik UI for Xamarin
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>
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:
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:
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="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>
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
tabView.Items.Add(homeTab);
tabView.Items.Add(viewTab);
tabView.Items.Add(folderTab);
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.
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
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>
XAML
<telerikPrimitives:RadTabView x:Name="tabView"
HeaderPosition="Top">
<telerikPrimitives:RadTabView.Header>
<telerikPrimitives:TabViewHeader ItemSpacing="0"/>
</telerikPrimitives:RadTabView.Header>
</telerikPrimitives:RadTabView>
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>
XAML
<Style TargetType="telerikPrimitives:TabViewHeaderItem">
1587
Telerik UI for Xamarin
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)
};
}),
}
};
Additionally, you can work with the already assigned header instead of replacing it with a new one.
For example - tabView.Header.BackgroundColor = Color.Green.
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.
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
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
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;
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
C#
1595
Telerik UI for Xamarin
using Telerik.XamarinForms.Input;
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
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
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>
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>
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>
C#
public class Country : NotifyPropertyChangedBase
{
private string name;
public Country()
{
this.Cities = new ObservableCollection<City>();
}
1600
Telerik UI for Xamarin
{
if (value != this.name)
{
this.UpdateValue(ref this.name, value);
}
}
}
C#
public class City : NotifyPropertyChangedBase
{
private string name;
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
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" }
}
},
};
}
1604
Telerik UI for Xamarin
}
}
}
C#
this.BindingContext = new ViewModel();
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
1605
Telerik UI for Xamarin
See Also
Templates
Styling
1606
Telerik UI for Xamarin
Templates
Templated Picker for Xamarin provides the following template:
In addition to this you can define the following templates provided from the RadPickerBase class:
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>
C#
public class Country : NotifyPropertyChangedBase
{
private string name;
public Country()
{
this.Cities = new ObservableCollection<City>();
}
1608
Telerik UI for Xamarin
}
set
{
if (value != this.name)
{
this.UpdateValue(ref this.name, value);
}
}
}
C#
public class City : NotifyPropertyChangedBase
{
private string name;
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
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" }
}
},
};
}
1612
Telerik UI for Xamarin
{
this.UpdateValue(ref this.fromCountry, value);
}
}
}
C#
this.BindingContext = new ViewModel();
XAML
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinF
orms.Input"
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
To learn in details about the localization process of Telerik UI for Xamarin components, please go
through the common Localization and Globalization topic.
See Also
1615
Telerik UI for Xamarin
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();
}
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.
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);
}
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:
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:
The SelectorSetting also provides the following properties for popup customization:
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.
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>
C#
public class Country : NotifyPropertyChangedBase
{
private string name;
public Country()
{
this.Cities = new ObservableCollection<City>();
}
1627
Telerik UI for Xamarin
C#
public class City : NotifyPropertyChangedBase
{
private string name;
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
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" }
}
},
};
}
1631
Telerik UI for Xamarin
C#
this.BindingContext = new ViewModel();
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.
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.
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
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
XAML
<telerikInput:RadTimePicker />
C#
using Telerik.XamarinForms.Input;
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"/>
Example
XAML
<telerikInput:RadTimePicker Time="10:30:00"/>
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.
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".
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:
Example
SpinnerFormat="H:mm"
XAML
<telerikInput:RadTimePicker SpinnerFormat="H:mm" />
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:
The snippet below shows a sample RadTimePicker definition with the listed above template
properties applied:
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
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
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.
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.
XAML
<telerikInput:RadTimePicker Time="10:30:00"/>
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.
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>
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.
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
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>
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);
}
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:
In addition, RadTimePicker exposes properties for specifying its border style and background color,
namely:
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:
The SelectorSettings also provides the following properties for popup customization:
1658
Telerik UI for Xamarin
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"
XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
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.
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
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
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.
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
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
XAML
<telerikInput:RadTimeSpanPicker />
C#
using Telerik.XamarinForms.Input;
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".
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:
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"/>
Example
XAML
<telerikInput:RadTimeSpanPicker Time="5:10:30:00"/>
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.
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
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>
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>
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=""
FontFamily="{StaticResource IconsFontFamily}"
TextColor="White"
BackgroundColor="Transparent"
Command="{TemplateBinding CancelCommand}" />
<Button Text=""
FontFamily="{StaticResource IconsFontFamily}"
TextColor="White"
BackgroundColor="Transparent"
Command="{TemplateBinding AcceptCommand}" />
</StackLayout>
</ControlTemplate>
1679
Telerik UI for Xamarin
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
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.
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"/>
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>
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"/>
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.
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.
The Accept and Cancel commands can be applied using the SelectorSettings property of
1685
Telerik UI for Xamarin
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);
}
1686
Telerik UI for Xamarin
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:
In addition, RadTimeSpanPicker exposes properties for specifying its border style and background
color, namely:
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:
The SelectorSettings also provides the following properties for popup customization:
1688
Telerik UI for Xamarin
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"
XAML
xmlns:telerikPrimitives="clr-namespace:Telerik.XamarinForms.Primitives;assembly=Teleri
k.XamarinForms.Primitives"
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.
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
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
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
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.
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
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:
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>();
}
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;
XAML
<telerikDataControls:RadTreeView x:Name="treeView" ItemsSource="{Binding Source}">
<telerikDataControls:TreeViewDescriptor DisplayMemberPath="Name"
ItemsSourcePath="Children"
TargetType="{x:Type local:Item}" />
</telerikDataControls:RadTreeView>
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:
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.
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>
1704
Telerik UI for Xamarin
C#
private void CheckFirstItem()
{
var firstItem = (treeView.ItemsSource as IList<Item>)[0];
treeView.CheckItem(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;
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
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; }
}
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();
}
}
XAML
<ResourceDictionary>
<local:ImageSourceConverter x:Key="ImageSourceConverter" />
<telerikTreeView:LevelToMarginConverter x:Key="levelToMarginConverter" />
</ResourceDictionary>
XAML
xmlns:telerikTreeView="clr-namespace:Telerik.XamarinForms.DataControls.TreeView;assemb
ly=Telerik.XamarinForms.DataControls"
C#
this.BindingContext = new ViewModel();
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.
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>
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
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>
C#
this.BindingContext = new ViewModel();
XAML
xmlns:telerikTreeView="clr-namespace:Telerik.XamarinForms.DataControls.TreeView;assemb
ly=Telerik.XamarinForms.DataControls"
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();
}
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
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));
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>
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 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.
Location
This enumeration contains the following members:
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>
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
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:
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
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
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:
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.iOS and Xamarin.Android documentation pages.
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.
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.
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
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:
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.
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.
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....
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
1742
Telerik UI for Xamarin
included in the Telerik UI for Xamarin zip file provided for manual installation.
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
Customizable Tokens
Token Layout Modes
Suggest Modes
Suggestion Match Highlighting
Completion Modes
Display Modes
1744
Telerik UI for Xamarin
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);
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;
}
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
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
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
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
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
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.
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));
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;
if (list == null)
{
FeedAutoCompleteTask task = new FeedAutoCompleteTask(
finishedCallback, (string)autoCompleteText, this.autocomplete);
task.Execute();
}
}
}
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();
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
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;
if (list == null)
{
1760
Telerik UI for Xamarin
("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();
1761
Telerik UI for Xamarin
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;
}
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
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:
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());
1763
Telerik UI for Xamarin
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.
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.
1766
Telerik UI for Xamarin
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
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);
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.
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
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>
1769
Telerik UI for Xamarin
1770
Telerik UI for Xamarin
Visual Structure
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
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();
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;
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;
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;
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;
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;
1778
Telerik UI for Xamarin
Sample DisplayMode example with Agenda can be found in our Xamarin.Android Samples inside the
/Calendar/DisplayMode folder.
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
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;
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.Add(CalendarField.Date, 2);
long end = calendar.TimeInMillis;
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
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();
...
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.
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.
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.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:
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;
1787
Telerik UI for Xamarin
decorator.Scale = .65f;
decorator.ShapeScale = .75f;
decorator.Stroked = false;
calendarView.CellDecorator = 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;
calendarView.CellDecorator = decorator;
return calendarView;
}
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
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);
calendarView.EventAdapter.Events = events;
return calendarView;
1790
Telerik UI for Xamarin
C#
calendarView.SetOnCellClickListener(new CellClickListenerExample());
...
1791
Telerik UI for Xamarin
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.
1792
Telerik UI for Xamarin
Shape:
C#
calendarView.EventAdapter.Renderer.EventRenderMode = EventRenderMode.Shape;
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
{
1793
Telerik UI for Xamarin
int x = startX;
int y = startY;
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;
1794
Telerik UI for Xamarin
1795
Telerik UI for Xamarin
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.Add(CalendarField.Hour, 12);
long startTime = calendar.TimeInMillis;
calendar.Add(CalendarField.Hour, 2);
long endTime = calendar.TimeInMillis;
1796
Telerik UI for Xamarin
1797
Telerik UI for Xamarin
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
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;
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;
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.
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)
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;
if (view == null)
1803
Telerik UI for Xamarin
{
view = layoutInflater.Inflate(
Resource.Layout.custom_inline_event_layout, parent, false);
view.Tag = holder;
}
else {
holder = (ViewHolder)view.Tag;
}
return view;
}
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.
C#
calendarView.EventsManager ().SetOnItemClickListener (new MyClickListener());
1805
Telerik UI for Xamarin
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.
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;
return calendarView;
}
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;
1807
Telerik UI for Xamarin
EventReadAdapter.GetAllCalendarsAsync(Activity, new
CustomAsyncCallback(this.eventAdapter));
return calendarView;
}
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
C#
public class CustomEventReadAdapter : EventReadAdapter
{
public CustomEventReadAdapter(RadCalendarView owner) : base (owner){}
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
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.
Here are the methods for the CalendarDayCellFilter which allow you to filter the cells that use a
certain style:
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);
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:
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);
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.
C#
Calendar calendar = Calendar.GetInstance(Java.Util.TimeZone.Default);
calendarView.CustomizationRule = new CustomizationRuleExample ();
// ...
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
C#
Calendar calendar = Calendar.GetInstance(Java.Util.TimeZone.Default);
calendarView.DateToColor = new DateToColorExample ();
// ...
1815
Telerik UI for Xamarin
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
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
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:
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.
C#
RadCalendarView calendarView = new RadCalendarView (Activity);
calendarView.ChangeDisplayMode(CalendarDisplayMode.Year, true);
1821
Telerik UI for Xamarin
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
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).
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.
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.
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.
1827
Telerik UI for Xamarin
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);
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;
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 {
1829
Telerik UI for Xamarin
{
if(propertyName == "Month")
{
return ((MonthResult)(p0)).Month;
}
return ((MonthResult)(p0)).Result;
}
}
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();
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;
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
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
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
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
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:
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
// 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;
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.
1836
Telerik UI for Xamarin
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
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.
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.
C#
CartesianGridLineAnnotation annotation = new CartesianGridLineAnnotation(verticalAxis,
8);
chartView.Annotations.Add(annotation);
annotation.StrokeColor = Color.Green;
annotation.StrokeWidth = 4;
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);
1839
Telerik UI for Xamarin
The PlotBandAnnotation represents a vertical or horizontal area that crosses the entire plot area.
C#
CartesianPlotBandAnnotation annotation = new CartesianPlotBandAnnotation(verticalAxis,
6, 8);
chartView.Annotations.Add(annotation);
annotation.FillColor = Color.Green;
annotation.StrokeColor = Color.Cyan;
annotation.StrokeWidth = 4;
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.
C#
var annotationValue = 6;
var annotationCategory = "Feb";
var annotationContent = "TARGET";
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 CustomTextRenderer()
{
contentPaint.TextSize = 36;
contentPaint.Color = Color.Red;
contentPaint.SetTypeface(Typeface.Create("sans-serif-light",
TypefaceStyle.Normal));
}
if (content == null)
{
return;
}
canvas.DrawText(
text,
(float)layoutSlot.GetX() - (float)(layoutSlot.Width / 2.0),
(float)layoutSlot.Bottom - (float)layoutSlot.Height / 2,
contentPaint);
}
}
1843
Telerik UI for Xamarin
C#
var annotationValue = 6;
var annotationCategory = "Feb";
var annotationContent = "TARGET";
// Now you can set the ContentRenderer to a new instance of the custom text renderer
annotation.ContentRenderer = new CustomTextRenderer();
chartView.Annotations.Add(annotation);
1844
Telerik UI for Xamarin
csharp
using Android.Graphics;
using Com.Telerik.Android.Common.Math;
using Com.Telerik.Widget.Chart.Engine.Decorations.Annotations.Custom;
1845
Telerik UI for Xamarin
{
if (content == null)
{
return RadSize.Empty;
}
}
}
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();
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);
1847
Telerik UI for Xamarin
1848
Telerik UI for Xamarin
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
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;}
1850
Telerik UI for Xamarin
1851
Telerik UI for Xamarin
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:
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();
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)
{
}
1853
Telerik UI for Xamarin
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
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();
chartView.Series.Add(lineSeries);
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.
C#
horizontalAxis.MajorTickInterval = 2;
1857
Telerik UI for Xamarin
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;}
We will also need a list of items from the new type and initialize it with proper data:
C#
private Java.Util.ArrayList extendedMonthResults;
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)));
}
C#
InitCalendarData();
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.
1860
Telerik UI for Xamarin
1861
Telerik UI for Xamarin
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();
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;
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
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();
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
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();
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
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();
1870
Telerik UI for Xamarin
1871
Telerik UI for Xamarin
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);
1872
Telerik UI for Xamarin
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();
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.
C#
panZoomBehavior.ZoomStrategy = ChartZoomStrategy.Deferred;
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
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
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.
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
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
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.
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());
C#
class MySelectionChangedListener : Java.Lang.Object, IChartSelectionChangeListener
{
public void OnSelectionChanged(ChartSelectionContext p0)
{
DataPoint selectedPoint = p0.SelectedDataPoint();
if(selectedPoint == null) {
return;
}
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();
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
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
C#
public class MonthResult : Java.Lang.Object {
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 {
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 {
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:
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
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();
1891
Telerik UI for Xamarin
Customization
LineSeries extend CategoricalStrokedSeries which provide the following way to change their style:
1892
Telerik UI for Xamarin
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();
1893
Telerik UI for Xamarin
Customization
SplineSeries extend LineSeries, so they provide the same way to change their style — by using the
following properties:
1894
Telerik UI for Xamarin
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();
1895
Telerik UI for Xamarin
Customization
AreaSeries extend CategoricalStrokedSeries which provides the following way to change their style:
Additionally, AreaSeries can change the color of their fill with the FillColor property.
1896
Telerik UI for Xamarin
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();
1897
Telerik UI for Xamarin
Customization
SplineAreaSeries extend AreaSeries, so they provide the same way to change their style — by using
the following properties:
1898
Telerik UI for Xamarin
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();
1899
Telerik UI for Xamarin
C#
1900
Telerik UI for Xamarin
barSeries.AreBarsRounded = true;
barSeries.RoundBarsRadius = 10;
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
1902
Telerik UI for Xamarin
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();
...
// 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;
}
}
1904
Telerik UI for Xamarin
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;
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.
1907
Telerik UI for Xamarin
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();
1908
Telerik UI for Xamarin
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);
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
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();
1912
Telerik UI for Xamarin
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;
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
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);
series.Data = (Java.Lang.IIterable)this.GenerateOhlcData();
chartView.Series.Add(series);
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
data.Add(ohlc);
}
return data;
}
1918
Telerik UI for Xamarin
Customization
You can also customize the appearance of the financial series by using palettes.
1919
Telerik UI for Xamarin
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.
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 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.
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:
1922
Telerik UI for Xamarin
C#
RadCartesianChartView chart = new RadCartesianChartView(this);
chart.VerticalAxis = verticalAxis;
chart.HorizontalAxis = horizontalAxis;
chart.Series.Add(series);
chart.Series.Add(bollingerBands);
chart.Series.Add(movingAverage);
...
1923
Telerik UI for Xamarin
data.Add(ohlc);
}
return data;
}
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
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;
}
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
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.
1928
Telerik UI for Xamarin
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;
}
return data;
Now with the bubble data initialization in place we can create our chart.
1929
Telerik UI for Xamarin
C#
RadCartesianChartView chartView = new RadCartesianChartView(this);
// 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);
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;
1931
Telerik UI for Xamarin
Supported Series
RadCartesianChartView can visualize the following types of series:
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.
1933
Telerik UI for Xamarin
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.
C#
private Java.Util.ArrayList monthResults;
1934
Telerik UI for Xamarin
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();
1935
Telerik UI for Xamarin
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:
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.
C#
class CustomLabelRenderer : BaseLabelRenderer {
1936
Telerik UI for Xamarin
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;
}
CategoricalDataPoint dataPoint =
relatedLabelNode.JavaCast<CategoricalDataPoint>();
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);
}
}
1938
Telerik UI for Xamarin
1939
Telerik UI for Xamarin
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";
linearLayout.AddView(legendView);
linearLayout.AddView(chartView);
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;
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;
C#
private void LegendViewOnLegendItemSelected(object sender, LegendSelectionEventArgs e)
{
var title = (e.P0 as LegendItem)?.Title;
}
1942
Telerik UI for Xamarin
1943
Telerik UI for Xamarin
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);
C#
public class Person : Java.Lang.Object
{
[DataFormProperty(Label = "Age", Index = 1)]
public int Age
{
get;
set;
}
1944
Telerik UI for Xamarin
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.
{
"name": "John Doe",
"age": 21,
"email": "john.doe@example.com"
1945
Telerik UI for Xamarin
}
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
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:
C#
dataForm.Adapter.SetEditorProvider(new EditorProviderImpl(dataForm));
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
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
C#
dataForm.GetExistingEditorForProperty("Age").Property().Converter =
new IntegerToStringConverter();
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());
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.
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.
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;
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
1953
Telerik UI for Xamarin
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;
}
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;
C#
1955
Telerik UI for Xamarin
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);
}
return feedData;
}
}
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
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
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) :
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
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;
}
1961
Telerik UI for Xamarin
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.
{
"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
{
"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.
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);
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
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;
1964
Telerik UI for Xamarin
dataForm.EditorsHeaderLayout = Resource.Layout.editors_header_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
}
}
1966
Telerik UI for Xamarin
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.
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:
ValidBackgroundDrawable
ValidDrawable
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
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.
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.
C#
editorGroup.LayoutManager = new DataFormPlaceholderLayoutManager();
1969
Telerik UI for Xamarin
C#
groupLayoutManager.CreateGroup = new CreateGroupImpl();
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;
}
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);
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
C#
groupLayoutManager.SortGroups = new SortGroupsImpl();
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
C#
// The context argument of the manager is the app context/activity.
dataForm.LayoutManager = new DataFormLinearLayoutManager(context);
C#
linearLayoutManager.Orientation = (int)Android.Widget.Orientation.Horizontal;
Finally, DataFormLinearLayoutManager can be initialized with a special linear layout inflated from
XML.
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
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
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
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;
}
return person1.name.CompareTo(person2.name);
}
}
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());
}
}
1976
Telerik UI for Xamarin
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.
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 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
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
1981
Telerik UI for Xamarin
Xamarin.AndroidX.AppCompat
Xamarin.AndroidX.RecyclerView
<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);
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
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.
1983
Telerik UI for Xamarin
C#
public class CityAdapter : Com.Telerik.Widget.List.ListViewAdapter
{
public CityAdapter(IList items) : base(items)
{
}
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
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);
C#
DeckOfCardsLayoutManager deckOfCardsLayoutManager =
1987
Telerik UI for Xamarin
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;
1988
Telerik UI for Xamarin
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;
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;
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.
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);
1995
Telerik UI for Xamarin
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) {
}
1996
Telerik UI for Xamarin
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;
}
}
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);
}
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>
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
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;
}
}
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
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;
listView.SetItemAnimator(itemAnimatorSet);
2002
Telerik UI for Xamarin
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.
<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:
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)).
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)
{
}
}
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
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
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.
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
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>
C#
public class SelectionListener : Java.Lang.Object,
SelectionBehavior.ISelectionChangedListener {
2011
Telerik UI for Xamarin
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
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
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;
}
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
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
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
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
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 {
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
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);
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
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;
this.listView =
(RadListView)rootView.FindViewById(Resource.Id.listView).JavaCast<RadListView>();
2023
Telerik UI for Xamarin
dataSource.Add(message);
this.listView.SetAdapter(new ListViewSwipeActionsAdapter(dataSource));
sap.AddListener(this);
this.listView.AddBehavior(sap);
return rootView;
}
There are four callbacks exposed by the SwipeActionsListener that are called depending on the
state of the SwipeActionsBehavior:
2024
Telerik UI for Xamarin
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
{
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;
}
}
}
What these overrides do is return a container for the swipe actions and bind it to the corresponding
data item.
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
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.
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;
}
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)
{
}
## 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;
}
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;
}
}
}
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
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
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.
C#
public class CollapseListener : Java.Lang.Object,
CollapsibleGroupsBehavior.ICollapseGroupListener {
Context context;
2034
Telerik UI for Xamarin
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
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
C#
RadNumberPicker picker = new RadNumberPicker(context);
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.
C#
picker.AddPropertyChangedListener(new MyPropertyChangedListener());
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.
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:
2038
Telerik UI for Xamarin
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
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
C#
RadTabView tabView = new RadTabView(this.Context);
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
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;
C#
tabView.TabStrip.Layout.MaxVisibleTabs = 5;
2043
Telerik UI for Xamarin
C#
public bool OnSelectingTab(Tab tabToSelect)
{
return false;
}
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
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
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
Telerik.Xamarin.Android.Common.dll
Telerik.Xamarin.Android.Primitives.dll
<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">
</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
2048
Telerik UI for Xamarin
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);
// There are also MainContent and DrawerContent properties that accept a View
directly.
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
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()).
C#
public class DrawerListener : Java.Lang.Object, IDrawerChangeListener
{
public void OnDrawerClosed (RadSideDrawer p0)
{
2053
Telerik UI for Xamarin
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 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
2056
Telerik UI for Xamarin
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)
};
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
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)
};
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
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;
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.
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;
}
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));
C#
gauge.Title.Text = "celsius";
gauge.Subtitle.Text = "fahrenheit";
gauge.TitleVerticalOffset = 90;
2064
Telerik UI for Xamarin
2065
Telerik UI for Xamarin
C#
needle.Animated = true;
needle.AnimationDuration = 500;
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.
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.
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
System Requirements
To build for Xamarin.iOS, the following are required:
For specific version requirements, refer to the latest Xamarin.iOS release notes.
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....
2070
Telerik UI for Xamarin
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
Key Features:
2072
Telerik UI for Xamarin
Demos for Alert control can be found in our Native Xamarin.iOS examples.
2073
Telerik UI for Xamarin
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?";
C#
alert.AddActionWithTitle("Egg", (TKAlert al, TKAlertAction action) => {
TextLabel.Text = "It was the egg!";
return true;
});
2074
Telerik UI for Xamarin
C#
alert.Show (true);
Getting Started Alert example can be found in our Native Xamarin.iOS examples.
2075
Telerik UI for Xamarin
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:
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
ShowAnimation
DismissAnimation
BackgroundStyle
You can switch between two customizable background styles - Blur and Dim.
Blur
2077
Telerik UI for Xamarin
None
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:
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
Demos for Alert Customization can be found in our Native Xamarin.iOS examples.
2079
Telerik UI for Xamarin
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
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
Setting up TKAutoCompleteTextView
Now that our project is created and the TelerikUI.framework is added, we can start referencing and
using the TelerikUI types:
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)
{
}
2085
Telerik UI for Xamarin
};
}
}
C#
this.dataSource = new TKDataSource(sampleArrayOfStrings);
this.dataSource.Settings.AutoComplete.CreateToken((index, item) => new
TKAutoCompleteToken((NSString) item));
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;
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;
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;
C#
using Foundation;
using System;
using UIKit;
using TelerikUI;
2088
Telerik UI for Xamarin
this.AutomaticallyAdjustsScrollViewInsets = false;
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
2090
Telerik UI for Xamarin
2091
Telerik UI for Xamarin
C#
this.Autocomplete.SuggestMode = TKAutoCompleteSuggestMode.Suggest;
2092
Telerik UI for Xamarin
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
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
2096
Telerik UI for Xamarin
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
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.
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;
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;
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
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
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);
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.
C#
public class CalendarDocsWithSimpleEvent : XamarinExampleViewController
{
CalendarDelegate calendarDelegate;
List<TKCalendarEvent> events;
2101
Telerik UI for Xamarin
set;
}
// calendarDelegate.events = this.events;
calendarView.Delegate = calendarDelegate;
calendarView.ReloadData();
}
2102
Telerik UI for Xamarin
{
CalendarDocsWithSimpleEvent main;
public List<TKCalendarEvent> events;
public CalendarDataSource(CalendarDocsWithSimpleEvent main)
{
this.main = main;
}
}
C#
this.CalendarView.ViewMode = TKCalendarViewMode.Year;
2103
Telerik UI for Xamarin
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.
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);
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
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
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
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;
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
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
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
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.
Day View
2110
Telerik UI for Xamarin
C#
this.CalendarView.ViewMode = TKCalendarViewMode.Day;
MultiDay View
2111
Telerik UI for Xamarin
C#
this.CalendarView.ViewMode = TKCalendarViewMode.MultiDay;
Agenda View
2112
Telerik UI for Xamarin
C#
this.CalendarView.ViewMode = TKCalendarViewMode.Agenda;
2113
Telerik UI for Xamarin
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.
2114
Telerik UI for Xamarin
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.
2115
Telerik UI for Xamarin
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.
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
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;
2118
Telerik UI for Xamarin
C#
presenter.TransitionIsVertical = true;
Finally the transition duration can be customized by setting the TransitionDuration property:
C#
presenter.TransitionDuration = 2;
2119
Telerik UI for Xamarin
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 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
The selection mode in TKCalendar can be altered by using the SelectionMode property. The
available options are:
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
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.
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));
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
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
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
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;
}
C#
public class DocsCustomCell : TKCalendarDayCell
{
public DocsCustomCell ()
{
}
2127
Telerik UI for Xamarin
Examples
Sample Customization TKCalendar example can be found in our native Xamarin.iOS
Examples/Calendar folder.
2128
Telerik UI for Xamarin
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
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;
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
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.
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);
2133
Telerik UI for Xamarin
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.
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])));
}
Line and area series also allow stacking by using the StackInfo 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.
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);
}
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
2137
Telerik UI for Xamarin
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.
Here is a sample subclass of TKChartViewController which will provide TKChart with data points
for one TKChartLineSeries:
C#
public class ChartDocsPopulatingWithData : UIViewController
{
public ChartDocsPopulatingWithData ()
{
}
2138
Telerik UI for Xamarin
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.
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])));
}
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;
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
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:
C#
chart.Legend.Style.Fill = new TKSolidFill(UIColor.LightGray);
chart.Legend.Style.Stroke = new TKStroke(UIColor.DarkGray);
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
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);
}
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.
}
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
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;
2149
Telerik UI for Xamarin
C#
var gridStyle = chart.GridStyle;
gridStyle.VerticalLinesHidden = true;
gridStyle.VerticalFill = null;
gridStyle.VerticalAlternateFill = null;
2150
Telerik UI for Xamarin
C#
var gridStyle = chart.GridStyle;
gridStyle.VerticalFill = null;
gridStyle.VerticalAlternateFill = null;
gridStyle.VerticalLinesHidden = true;
2151
Telerik UI for Xamarin
C#
var gridStyle = chart.GridStyle;
gridStyle.HorizontalFill = null;
gridStyle.HorizontalAlternateFill = null;
gridStyle.HorizontalLinesHidden = true;
2152
Telerik UI for Xamarin
Combining it together
C#
var gridStyle = chart.GridStyle;
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.
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.VerticalFill = null;
gridStyle.VerticalAlternateFill = null;
gridStyle.VerticalLinesHidden = true;
gridStyle.ZPosition = TKChartGridZPosition.AboveSeries;
2156
Telerik UI for Xamarin
2157
Telerik UI for Xamarin
TKChartGridLineAnnotation
TKChartBandAnnotation
TKChartCrossLineAnnotation
TKChartBalloonAnnotation
TKChartLayerAnnotation
TKChartViewAnnotation
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.
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.
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);
2161
Telerik UI for Xamarin
The AttributedText property can be used to present formatted text with NSAttributedString.
2162
Telerik UI for Xamarin
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
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.
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
C#
var fill = new TKSolidFill (UIColor.Red, 5.0f);
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;
2167
Telerik UI for Xamarin
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
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);
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
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.
C#
var stroke = new TKStroke (UIColor.Blue);
C#
var stroke = new TKStroke (UIColor.Blue, 1.0f);
stroke.CornerRadius = 5.0f;
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
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;
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;
2175
Telerik UI for Xamarin
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();
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;
series.Style.PaletteMode = TKChartSeriesStylePaletteMode.UseItemIndex;
chart.AddSeries (series);
2177
Telerik UI for Xamarin
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;
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
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:
2180
Telerik UI for Xamarin
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.
@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
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:
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:
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
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
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.
C#
public override CAAnimation AnimationForSeries (TKChart chart, TKChartSeries series,
TKChartSeriesRenderState state, CGRect rect)
{
double duration = 0;
List<CAAnimation> animations = new List<CAAnimation> ();
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);
}
}
}
return group;
}
C#
public override CAAnimation AnimationForSeries (TKChart chart, TKChartSeries series,
2190
Telerik UI for Xamarin
duration = a.Duration;
}
CAAnimationGroup g = new CAAnimationGroup();
g.Duration = duration;
g.Animations = animations.ToArray();
return g;
}
2191
Telerik UI for Xamarin
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];
animator.AddBehavior(dynamic);
animator.AddBehavior(gravity);
animator.AddBehavior(collision);
2192
Telerik UI for Xamarin
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.
C#
chart.XAxis.Style.LabelStyle.Font = UIFont.SystemFontOfSize (18);
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.
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.
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);
2194
Telerik UI for Xamarin
C#
chart.XAxis.Style.LineStroke = new TKStroke (UIColor.Black);
2195
Telerik UI for Xamarin
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;
C#
2198
Telerik UI for Xamarin
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
2200
Telerik UI for Xamarin
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
2201
Telerik UI for Xamarin
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)));
}
You can specify the axis range by setting the minimum and maximum indexes of categories.
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
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
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
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
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;
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
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
2213
Telerik UI for Xamarin
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)
{
}
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)
{
}
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;
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
C#
barSeries.Style.PointLabelStyle.TextHidden = false;
barSeries.Style.PointLabelStyle.LabelOffset = new UIOffset (15, 0);
2219
Telerik UI for Xamarin
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;
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));
}
2221
Telerik UI for Xamarin
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 };
2222
Telerik UI for Xamarin
C#
var stackInfo = new TKChartStackInfo (new NSNumber (1), TKChartStackMode.Stack);
chart.BeginUpdates ();
chart.AddSeries (seriesForIncome);
chart.AddSeries (seriesForExpenses);
chart.EndUpdates ();
2223
Telerik UI for Xamarin
2224
Telerik UI for Xamarin
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
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)));
}
2226
Telerik UI for Xamarin
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> ();
2227
Telerik UI for Xamarin
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
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
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
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
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> ();
2235
Telerik UI for Xamarin
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
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)));
}
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 };
chart.BeginUpdates();
chart.AddSeries(series1);
chart.AddSeries(series2);
chart.EndUpdates();
2239
Telerik UI for Xamarin
C#
var stackInfo = new TKChartStackInfo(new NSNumber(1), TKChartStackMode.Stack);
chart.BeginUpdates();
chart.AddSeries(series1);
chart.AddSeries(series2);
chart.EndUpdates();
2240
Telerik UI for Xamarin
C#
var stackInfo = new TKChartStackInfo(new NSNumber(1), TKChartStackMode.Stack100);
chart.BeginUpdates();
chart.AddSeries(series1);
chart.AddSeries(series2);
chart.EndUpdates();
2241
Telerik UI for Xamarin
C#
var series = new TKChartBarSeries (pointsWithCategoriesAndValues.ToArray());
series.Style.Palette = new TKChartPalette ();
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
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)));
}
series.MaxColumnWidth = 50;
series.MinColumnWidth = 20;
chart.AddSeries(series);
2245
Telerik UI for Xamarin
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)));
}
2246
Telerik UI for Xamarin
C#
var stackInfo = new TKChartStackInfo (new NSNumber (1), TKChartStackMode.Stack);
chart.BeginUpdates ();
chart.AddSeries (seriesForIncome);
chart.AddSeries (seriesForExpenses);
chart.EndUpdates ();
2247
Telerik UI for Xamarin
2248
Telerik UI for Xamarin
You can change the fill and stroke in the following manner:
C#
series.Style.Palette = new TKChartPalette ();
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
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")));
chart.AddSeries(series);
chart.Legend.Hidden = false;
chart.Legend.Style.Position = TKChartLegendPosition.Right;
2252
Telerik UI for Xamarin
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
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
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 };
2256
Telerik UI for Xamarin
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
C#
var seriesForProfit = new TKChartLineSeries (profitData.ToArray());
seriesForProfit.DisplayNilValuesAsGaps = true;
2258
Telerik UI for Xamarin
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"));
chart.AddSeries (series);
chart.Legend.Hidden = false;
chart.Legend.Style.Position = TKChartLegendPosition.Right;
The LabelDisplayMode property controls whether to show labels inside or outside the pie series.
The possible choices are:
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;
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
C#
List<TKChartDataPoint> list = new List<TKChartDataPoint> ();
for (int j = 0; j < 20; j++) {
C#
var series = new TKChartScatterSeries (scatterPoints.ToArray());
2262
Telerik UI for Xamarin
C#
var series = new TKChartScatterSeries (scatterPoints.ToArray());
series.Selection = TKChartSeriesSelection.DataPoint;
series.MarginForHitDetection = 30.0f;
chart.AddSeries (series);
2263
Telerik UI for Xamarin
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
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
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)
};
2266
Telerik UI for Xamarin
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
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)
};
2270
Telerik UI for Xamarin
chart.AddSeries(series2);
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
Editors
TextField
Switch
Stepper
Slider
Segmented control
DatePicker
PickerView
Options
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
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.
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;
}
}
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);
}
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)
{
}
// Perform any additional setup after loading the view, typically from a nib.
this.DataForm.WeakDataSource = new TKDataFormEntityDataSource(new
PersonalInfo());
}
}
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.
C#
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
// Perform any additional setup after loading the view, typically from a nib.
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);
}
The images below show the result after applying the snippet:
2280
Telerik UI for Xamarin
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
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 };
C#
public override bool ValidateProperty (TKDataForm dataForm, TKEntityProperty property,
TKDataFormEditor editor)
{
}
C#
var hasValidationErrors = dataForm.HasValidationErrors();
2282
Telerik UI for Xamarin
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));
}
}
2283
Telerik UI for Xamarin
2284
Telerik UI for Xamarin
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
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.
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" });
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;
}
}
}
2287
Telerik UI for Xamarin
2288
Telerik UI for Xamarin
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.
sorting
filtering
grouping
For your convenience TLKDataSource provides three different APIs for data shaping operations.
Presenting data
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
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;
});
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!
2293
Telerik UI for Xamarin
C#
[Register("DataSourceGettingStarted")]
public class DataSourceGettingStarted: XamarinExampleViewController
{
TLKDataSource dataSource;
// 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;
});
2294
Telerik UI for Xamarin
Console.WriteLine("{0}", ((NSNumber)item).NIntValue);
}
});
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
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 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;
}
2298
Telerik UI for Xamarin
dataSource.ItemSource = newItems;
chart.DataSource = dataSource;
2299
Telerik UI for Xamarin
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;
});
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 ()
{
}
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;
2301
Telerik UI for Xamarin
dataSource.DisplayKey = "Name";
dataSource.ValueKey = "Value";
dataSource.ItemSource = array;
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
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;
}
2303
Telerik UI for Xamarin
chart.DataSource = dataSource;
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
Examples with Gauge control can be found in our Native Xamarin.iOS examples.
2306
Telerik UI for Xamarin
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;
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
2310
Telerik UI for Xamarin
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
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);
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);
TKGaugeScale has various properties for customizing its ticks and labels.
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);
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
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
Cells Swipe
Cells Reordering
Pull-to-refresh
Load-on-demand
Different Layout Modes
Single/Multiple Selection
Grouping
2317
Telerik UI for Xamarin
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);
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
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 ()
{
}
dataSource.ItemSource = simpleArrayOfStrings;
2322
Telerik UI for Xamarin
listView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth |
UIViewAutoresizing.FlexibleHeight;
listView.WeakDataSource = dataSource;
this.View.AddSubview(listView);
listView.AllowsMultipleSelection = true;
listView.AllowsCellReorder = true;
}
}
C#
public class ListViewDocsSetupDataSource : XamarinExampleViewController
{
public NSArray sampleArrayOfStrings;
public ListViewDocsSetupDataSource ()
{
}
2323
Telerik UI for Xamarin
this.View.AddSubview (listView);
2324
Telerik UI for Xamarin
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"));
2325
Telerik UI for Xamarin
delegate methods
Here is the code:
C#
public class ListViewDocsGroupsDelegate : XamarinExampleViewController
{
public NSMutableArray groups;
public ListViewDocsGroupsDelegate ()
{
}
this.View.AddSubview (listView);
}
}
2326
Telerik UI for Xamarin
2327
Telerik UI for Xamarin
Single selection
Multiple 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.
2328
Telerik UI for Xamarin
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
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;
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.
2330
Telerik UI for Xamarin
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;
}
}
2331
Telerik UI for Xamarin
By default TKListView uses Linear layout but you can easily change that with the layout property.
The layouts that are implemented are:
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
2336
Telerik UI for Xamarin
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:
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;
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
C#
this.listView.AllowsCellReorder = true;
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;
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
C#
2343
Telerik UI for Xamarin
this.listView.AllowsCellSwipe = true;
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);
2344
Telerik UI for Xamarin
ShouldSwipeCell
DidSwipeCell
DidFinishSwipeCell
C#
class ListViewDelegate: TKListViewDelegate
{
ListViewSwipe owner;
A sample ListView Cell Swipe example can be found in our Native Xamarin.iOS examples.
2345
Telerik UI for Xamarin
Enabling pull-to-refresh
Use the AllowsPullToRefresh property to enable the feature.
C#
listView.AllowsPullToRefresh = true;
2346
Telerik UI for Xamarin
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
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;
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;
}
return cell;
}
ListView Load On Demand example can be found in our Native Xamarin.iOS examples.
2349
Telerik UI for Xamarin
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.
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.
2351
Telerik UI for Xamarin
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
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
this.View.BackgroundColor = UIColor.Gray;
[Export ("ShowSideDrawer")]
public void ShowSideDrawer ()
{
this.SideDrawer.Show ();
}
}
C#
[Register("SideDrawerGettingStarted")]
public class SideDrawerGettingStarted : XamarinExampleViewController
{
private TKSideDrawerSection primarySection;
private TKSideDrawerSection labelsSection;
SideDrawerDelegate sideDrawerDelegate;
2354
Telerik UI for Xamarin
set;
}
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;
}
[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
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;
2366
Telerik UI for Xamarin
C#
MyTransition transition = new MyTransition (sideDrawer);
sideDrawer.TransitionManager = transition;
C#
public class MyTransition : TKSideDrawerTransition
{
private CGPoint sideDrawerIdentityCenter;
private CGPoint hostviewIdentityCenter;
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);
});
}
2367
Telerik UI for Xamarin
{
if (showing) {
this.SideDrawer.Hidden = false;
this.SideDrawer.Superview.BringSubviewToFront (this.SideDrawer.Hostview);
this.SideDrawer.Hostview.UserInteractionEnabled = false;
}
}
SideDrawer Custom Transition example can be found in our Native Xamarin.iOS examples.
2368
Telerik UI for Xamarin
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.
2369
Telerik UI for Xamarin
2370
Telerik UI for Xamarin
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
Example
C#
sideDrawer.Style.HeaderHeight = 44;
Shadow
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
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
2374
Telerik UI for Xamarin
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
C#
[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
// class-level declarations
return true;
}
//..
}
C#
public class SideDrawerGettingStarted : UIViewController
{
TKSideDrawer SideDrawer;
2376
Telerik UI for Xamarin
this.View.BackgroundColor = UIColor.Gray;
[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.
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:
2378
Telerik UI for Xamarin
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
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.
2381
Telerik UI for Xamarin
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.
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.
<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
<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.
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;
2386
Telerik UI for Xamarin
@code
{
public List<string> AcvItemSource { get; set; }
See Also
Xamarin Mobile Blazor Bindings Overview
2387
Telerik UI for Xamarin
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>
See Also
Getting Started
2389
Telerik UI for Xamarin
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;
2390
Telerik UI for Xamarin
See Also
Xamarin Mobile Blazor Bindings Overview
2391
Telerik UI for Xamarin
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"/>
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>
2394
Telerik UI for Xamarin
<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>
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.
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).
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>
2398
Telerik UI for Xamarin
See Also
2399
Telerik UI for Xamarin
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.
2400
Telerik UI for Xamarin
Setting Background Image: You can customize the appearance of RadButton by applying am
image as its background.
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
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;
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()
{
}
}
See Also
Xamarin Mobile Blazor Bindings Overview
2403
Telerik UI for Xamarin
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"/>
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
<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>
2405
Telerik UI for Xamarin
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.
<RadCheckBox StrokeWidth="5"
Length="40" />
See Also
Getting Started
2407
Telerik UI for Xamarin
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
<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; }
this.IsChecked = false;
this.IsCheckBoxChecked = this.IsChecked.ToString();
}
2409
Telerik UI for Xamarin
See Also
Xamarin Mobile Blazor Bindings Overview
2410
Telerik UI for Xamarin
2411
Telerik UI for Xamarin
Key features
Below are describes the main features of the DataGrid control.
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; }
2413
Telerik UI for Xamarin
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.
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
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).
<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; }
2418
Telerik UI for Xamarin
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.
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>
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:
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.
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;
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>
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.
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
<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; }
2427
Telerik UI for Xamarin
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.
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;
@code
{
public List<string> Source { get; set; }
See Also
2431
Telerik UI for Xamarin
2432
Telerik UI for Xamarin
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.
The desired transition can be set through DrawerTransitionType property of the SideDrawer.
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
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
<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; }
this.IsDrawerOpen = false;
}
2437
Telerik UI for Xamarin
}
}
See Also
Xamarin Mobile Blazor Bindings Overview
2438
Telerik UI for Xamarin
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:
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
2439
Telerik UI for Xamarin
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.
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);
}
}
C#
2440
Telerik UI for Xamarin
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.
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:
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
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.
2444
Telerik UI for Xamarin
2445
Telerik UI for Xamarin
Complementary Colors
See Also
How To Set a Theme
How To Create a Custom Theme Based on a Telerik Theme
2446
Telerik UI for Xamarin
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.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.
XAML
<telerikDataControls:RadListView x:Name="list" StyleClass="TelerikTheme"/>
See Also
Themes Overview
How To Create a Custom Theme Based on a Telerik Theme
2448
Telerik UI for Xamarin
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>
2449
Telerik UI for Xamarin
2450
Telerik UI for Xamarin
<!-- TabView-->
<Color x:Key="TelerikTabViewHeaderItemSelectedColor">#3148CA</Color>
2451
Telerik UI for Xamarin
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>
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>
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();
}
}
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>
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>
2455
Telerik UI for Xamarin
<!-- TabView-->
<Color x:Key="TelerikTabViewHeaderItemSelectedColor">#3148CA</Color>
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"/>
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.
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
2459
Telerik UI for Xamarin
Make sure to test your application carefully and thoroughly on both Light and Dark system
appearance.
Here is how some of the Telerik Xamarin controls look on iOS with Darh Mode applied:
2460
Telerik UI for Xamarin
Make sure to test your application carefully and thoroughly on both Light and Dark system
appearance.
Requrements:
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;
```
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
This article will give an overview on how you can utilize the Telerik font icons in your app.
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.
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>
Telerik Font
Icons
sort_descent  star-empty  filter 
sort_ascent  group  star 
right-dir  dots_vert  menu 
check  cancel  dot 
check  down-dir  left-open-big 
configure  search  up-dir 
pattern  add  right-dir-outli 
nes
info  down-dir-outl  bin-solid 
ines
edit  copy  arrow-up 
airplane  pdf  encoding 
length  arrow-right  contacts 
cog-outlines  type  location 
link  archive  bin 
draft  folder-open  folder 
group  item  sent 
spam  warning  lock 
thickness  car  shopping-ba 
g
coffee-cup  get-money  shopping-us 
er
group_users  dashboard  location 
2465
Telerik UI for Xamarin
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=""/>
</telerikGrid:DataGridTextColumn.HeaderStyle>
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:
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:
See Also
Blob Storage
SQL Database
Cosmos DB
2471
Telerik UI for Xamarin
This article demonstrates how to integrate an Azure's SQL Database and display the data using the
RadListView.
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.
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.
2477
Telerik UI for Xamarin
}
}
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.
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:
2478
Telerik UI for Xamarin
{
HttpClient client;
public ObservableCollection<Customer> Customers { get; set; }
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;
}
}
2479
Telerik UI for Xamarin
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:
And in the code-behind of the page that contains the RadListView control:
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
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.
You should also Add a collection which is again explained in details in the step-by-step guide.
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:
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:
2484
Telerik UI for Xamarin
} 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.
For the purposes of this sample, we have created a container which contains several photos:
<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>
2489
Telerik UI for Xamarin
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;
}
And the PhotoModel class which is a representation of each photo within the photos container:
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
_activityIndicator.IsRunning = false;
_activityIndicator.IsVisible = false;
}
}
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.
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.
<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>
2494
Telerik UI for Xamarin
public TranslatorAPIpage ()
{
InitializeComponent ();
}
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
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.
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.
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>
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.
C#
public partial class MainPage : ContentPage, INotifyPropertyChanged
{
btn.Clicked += Btn_ClickedAsync;
}
2500
Telerik UI for Xamarin
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
Getting Started
Storage (S3)
2503
Telerik UI for Xamarin
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:
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:
2506
Telerik UI for Xamarin
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.
<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>
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();
}
}
2509
Telerik UI for Xamarin
If you do not have an AWS account in Visual Studio, please check the Getting Started article.
public ViewModel()
{
this.User = new User();
}
}
2510
Telerik UI for Xamarin
[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
}
}
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:
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:
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();
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
This article will demonstrate how one can use this service from a Xamarin application and send an
email to a specific address.
<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>
2515
Telerik UI for Xamarin
MaskType="Regex"
InvalidInputErrorText="Invalid Email Address"
Mask="{x:Static extensions:MaskExtensions.Email}"
WatermarkText="To E-mail"
Grid.Row="1"/>
2516
Telerik UI for Xamarin
2517
Telerik UI for Xamarin
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.
<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>
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.
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.
if (!currentTables.Contains("MyCustomers"))
{
CreateTableRequest createRequest = new CreateTableRequest
{
TableName = "MyCustomers",
2521
Telerik UI for Xamarin
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.
2522
Telerik UI for Xamarin
You can then invoke the AddCustomers method in the constructor of the VieWmodel:
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.
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.
// 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());
} while (!search.IsDone);
2524
Telerik UI for Xamarin
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.
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:
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
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):
2528
Telerik UI for Xamarin
See Also
Required Android Support Libraries
System Requirements
2529
Telerik UI for Xamarin
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.
StackLayout
Grid RowDefinition Height="Auto"
Solution
To solve this, you can take one of two routes:
xml
<telerikDataControls:RadListView HeightRequest="500" .../>
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 .../>
2530
Telerik UI for Xamarin
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.
2531
Telerik UI for Xamarin
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
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:
Dark: Theme.AppCompat.NoActionBar
Light:Theme.AppCompat.Light.NoActionBar
2534
Telerik UI for Xamarin
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:
C#
using Xamarin.Forms.Xaml;
[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
namespace
SDKBrowser.Examples.CalendarControl.GettingStartedCategory.GettingStartedExample
{
public partial class CalendarGettingStartedXaml : ContentView
{
public CalendarGettingStartedXaml()
{
this.InitializeComponent();
}
}
}
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:
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
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