PROWAREtech

articles » archived » xamarin » tutorial » page-03

Xamarin: Tutorial - Page 03

A guide for new Xamarin developers.

User Interface Objects a.k.a Widgets/Controls

There are too many classes with way too many properties and methods to experiment with them all here. Take advantage of Intellisense and experiment with the settings of these classes.

This tutorial has already covered Label and Button. Most of the following widgets/controls have Unfocus() and Focus() methods. Most have Opacity, IsFocused, IsEnabled and IsVisible properties which are type bool. Also, most have HorizontalOptions and VerticalOptions properties. (see related code)

Label

Label examples have already been seen. Label has the following additional properties: Font FontAttributes FontFamily FontSize FormattedText Text TextColor VerticalTextAlignment XAlign YAlign. It has no events.

<Label HorizontalTextAlignment="Center" />

Button

Button examples have already been seen. Button has the following additional properties: BorderColor BorderRadius BorderWidth Command CommandParameter ContentLayout Font FontAttributes FontFamily FontSize Image Text TextColor. Command and CommandParameter have to do with MVVM binding, which is covered later. Button has one additional event: Clicked.

<Button Text="Tap Me!" />

Entry

Entry uses the virtual keyboard and it is for entering a single line of text. There are seven keyboards as shown in the code below. The iOS emulator may not show the keyboard. The additional properties are: Text, TextColor, Placeholder, PlaceholderColor, IsPassword, FontAttributes, FontFamily, FontSize and HorizontalTextAlignment; and the additional events are: Completed and TextChanged.

<Entry Keyboard="Default" Placeholder="enter name" />

Editor

Editor also uses the virtual keyboard and is for entering multiple lines of text. There is only one keyboard: Text. The additional properties are: FontAttributes, FontFamily, FontSize, Text and TextColor; and the additional events are: Completed and TextChanged.

<Editor TextColor="Black" />

SearchBar is like Entry. It is for searching an application. The additional properties are: CancelButtonColor FontAttributes FontFamily FontSize HorizontalTextAlignment Placeholder PlaceholderColor SearchCommand SearchCommandParameter Text TextColor; and the additional events are: Completed and TextChanged.

<SearchBar TextColor="Gray" Placeholder="query..." />

Slider

Slider returns a double data type between zero and one by default but this can me changed with the Minimum and Maximum attributes. The max must be more than the min so set the max before the min.

<Slider Maximum="200" Minimum="100" />

Stepper

Stepper also returns a double data type between zero and one by default but this can me changed with the Minimum and Maximum attributes. The max must be more than the min so set the max before the min. Use the Increment property to change the default increment value of one.

<Stepper Maximum="25" Minimum="1" Increment="0.5" />

Switch

Switch returns a bool (true or false).

<Switch />

DatePicker

DatePicker is used for getting the date from the user. The properties are: Date Format MaximumDate MinimumDate TextColor and the event fired when a user selects a date is DateSelected

<DatePicker Date="1/1/2018" />

TimePicker

TimePicker is used to getting the time from the user. The properties are Format TextColor Time without any events.

<TimePicker Time="10:00" />

ActivityIndicator

ActivityIndicator shows the user that the application is busy or working. It has an IsRunning property.

<ActivityIndicator IsRunning="True" />

Example Code

The following code uses most of the widgets/controls.

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
		xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
		xmlns:local="clr-namespace:HelloXamarinForms"
		x:Class="HelloXamarinForms.MainPageXaml">

	<ScrollView>
		<StackLayout>

			<Label x:Name="lbl" HorizontalTextAlignment="Center" />

			<Entry Keyboard="Default"
					 Placeholder="Default"
					TextChanged="OnEntryTextChanged"
					Completed="OnEntryCompleted" />

			<Entry Keyboard="Text"
					 Placeholder="Text"
					TextChanged="OnEntryTextChanged"
					Completed="OnEntryCompleted" />

			<Entry Keyboard="Chat"
					 Placeholder="Chat"
					TextChanged="OnEntryTextChanged"
					Completed="OnEntryCompleted" />

			<Entry Keyboard="Url"
					 Placeholder="Url"
					TextChanged="OnEntryTextChanged"
					Completed="OnEntryCompleted" />

			<Entry Keyboard="Email"
					 Placeholder="Email"
					TextChanged="OnEntryTextChanged"
					Completed="OnEntryCompleted" />

			<Entry Keyboard="Telephone"
					 Placeholder="Telephone"
					TextChanged="OnEntryTextChanged"
					Completed="OnEntryCompleted" />

			<Entry Keyboard="Numeric"
					 Placeholder="Numeric"
					TextChanged="OnEntryTextChanged"
					Completed="OnEntryCompleted" />

			<Editor TextChanged="OnEditorTextChanged"
					Completed="OnEditorCompleted" />

			<SearchBar TextChanged="OnSearchBarTextChanged"
						 SearchButtonPressed="OnSearchBarButtonPressed" />

			<Slider Maximum="200"
					Minimum="100"
					ValueChanged="OnSliderValueChanged" />

			<Stepper Maximum="25"
					 Minimum="1"
					 Increment="0.5"
					 ValueChanged="OnStepperValueChanged" />

			<Switch Toggled="OnSwitchToggled" />

			<DatePicker DateSelected="OnDatePickerDateSelected" />

			<TimePicker />

			<ActivityIndicator IsRunning="True" />
			
		</StackLayout>
	</ScrollView>

</ContentPage>
using Xamarin.Forms;

namespace HelloXamarinForms
{
	public partial class MainPageXaml : ContentPage
	{
		public MainPageXaml()
		{
			InitializeComponent();
		}

		void OnEntryTextChanged(object sender, TextChangedEventArgs e)
		{
			lbl.Text = e.NewTextValue;
		}

		void OnEntryCompleted(object sender, System.EventArgs e)
		{
			DisplayAlert("Entry", ((Entry)sender).Text, "OK");
		}

		void OnEditorTextChanged(object sender, TextChangedEventArgs e)
		{
			lbl.Text = e.NewTextValue;
		}

		void OnEditorCompleted(object sender, System.EventArgs e)
		{
			DisplayAlert("Editor", ((Editor)sender).Text, "OK");
		}

		void OnSearchBarTextChanged(object sender, TextChangedEventArgs e)
		{
			lbl.Text = e.NewTextValue;
		}

		void OnSearchBarButtonPressed(object sender, System.EventArgs e)
		{
			// do something
		}

		void OnSliderValueChanged(object sender, ValueChangedEventArgs e)
		{
			lbl.Text = string.Format("Slider: {0:F2}", e.NewValue);
		}

		void OnStepperValueChanged(object sender, ValueChangedEventArgs e)
		{
			lbl.Text = "Stepper: " + e.NewValue.ToString();
		}

		void OnSwitchToggled(object sender, ToggledEventArgs e)
		{
			lbl.Text = "Switch: " + e.Value.ToString();
		}

		void OnDatePickerDateSelected(object sender, DateChangedEventArgs e)
		{
			lbl.Text = e.NewDate.ToString();
		}
	}
}

Frame

Frame is a basic rectangle renderer. It draw a rectangular border around something.

A basic Frame example.

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
		xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
		xmlns:local="clr-namespace:HelloXamarinForms"
		x:Class="HelloXamarinForms.MainPageXaml"
		BackgroundColor="White">

	<Frame OutlineColor="Red" HorizontalOptions="Center" VerticalOptions="Center">
		<Label Text="This text is framed" FontSize="Large" TextColor="Black" />
	</Frame>

</ContentPage>

BoxView

Like Frame, BoxView is a basic rectangle renderer. It is a filled rectangle while.

BoxView has already been seen. Another basic BoxView example.

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
		xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
		xmlns:local="clr-namespace:HelloXamarinForms"
		x:Class="HelloXamarinForms.MainPageXaml"
		BackgroundColor="White">

		<BoxView Color="Blue" Opacity="0.5" />

</ContentPage>

Picker

Picker is a way to provide the user with up to 10 or maybe 20 strings to choose from. It has the properties SelectedIndex TextColor Title and the one event SelectedIndexChanged. The SelectedIndex property must have the item available to select otherwise it will crash the app. It does not sort its string values for the user. The TableView article has an example of using Picker with data binding.

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
		xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
		xmlns:local="clr-namespace:HelloXamarinForms"
		x:Class="HelloXamarinForms.MainPageXaml">

	<ContentPage.Padding>
		<OnPlatform x:TypeArguments="Thickness" iOS="10, 20, 10, 0" Android="10, 0" />
	</ContentPage.Padding>

	<StackLayout>
		<Label x:Name="lbl" />
		<Picker Title="Usernames" SelectedIndexChanged="OnSelectedIndexChanged">
			<Picker.Items>
				<x:String>Xavier</x:String>
				<x:String>Aaron</x:String>
				<x:String>David</x:String>
				<x:String>Jill</x:String>
				<x:String>Andrew</x:String>
				<x:String>John</x:String>
				<x:String>James</x:String>
				<x:String>William</x:String>
				<x:String>Julie</x:String>
			</Picker.Items>
			<Picker.SelectedIndex>
				7
			</Picker.SelectedIndex>
		</Picker>
	</StackLayout>

</ContentPage>
using Xamarin.Forms;

namespace HelloXamarinForms
{
	public partial class MainPageXaml : ContentPage
	{
		public MainPageXaml()
		{
			InitializeComponent();
		}

		void OnSelectedIndexChanged(object sender, System.EventArgs e)
		{
			Picker p = (Picker)sender;
			int idx = p.SelectedIndex;

			if (idx < 0)
				return;

			lbl.Text = p.Items[idx];
		}
	}
}

Items can be added programmtically, too. Then the data can be sorted at the same time.

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
		xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
		xmlns:local="clr-namespace:HelloXamarinForms"
		x:Class="HelloXamarinForms.MainPageXaml">

	<ContentPage.Padding>
		<OnPlatform x:TypeArguments="Thickness" iOS="10, 20, 10, 0" Android="10, 0" />
	</ContentPage.Padding>

	<StackLayout>
		<Label x:Name="lbl" />
		<Picker x:Name="pick" Title="Usernames" SelectedIndexChanged="OnSelectedIndexChanged">
		</Picker>
	</StackLayout>

</ContentPage>
using Xamarin.Forms;

namespace HelloXamarinForms
{
	public partial class MainPageXaml : ContentPage
	{
		public MainPageXaml()
		{
			InitializeComponent();

			string[] usernames = { "Xavier", "Aaron", "David",
									 "Jill", "Andrew", "John",
									 "James", "William", "Julie" };

			System.Array.Sort(usernames);
			
			foreach(string s in usernames)
			{
				pick.Items.Add(s);
			}
		}

		void OnSelectedIndexChanged(object sender, System.EventArgs e)
		{
			int idx = pick.SelectedIndex;

			if (idx < 0)
				return;

			lbl.Text = pick.Items[idx];
		}
	}
}

ListView

ListView deserves its own article. It displays data to the user in a vertical list.

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
		xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
		xmlns:local="clr-namespace:HelloXamarinForms"
		x:Class="HelloXamarinForms.MainPageXaml">

	<ContentPage.Padding>
		<OnPlatform x:TypeArguments="Thickness" iOS="10, 20, 10, 0" Android="10, 0" />
	</ContentPage.Padding>

	<ListView x:Name="listView" />

</ContentPage>

Changing the usernames array will not automatically update the screen. The solution to this problem is the ObservableCollection class which is covered later in this tutorial.

using Xamarin.Forms;

namespace HelloXamarinForms
{
	public partial class MainPageXaml : ContentPage
	{
		public MainPageXaml()
		{
			InitializeComponent();

			string[] usernames = { "Xavier", "Aaron", "David",
									 "Jill", "Andrew", "John",
									 "James", "William", "Julie" };

			System.Array.Sort(usernames);

			listView.ItemsSource = usernames;
		}
	}
}

TableView

TableView deserves its own article. It is a convenient way to organize and arrange information.

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
		xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
		xmlns:local="clr-namespace:HelloXamarinForms"
		x:Class="HelloXamarinForms.MainPageXaml">

	<ContentPage.Padding>
		<OnPlatform x:TypeArguments="Thickness" iOS="0, 20, 0, 0" />
	</ContentPage.Padding>

	<StackLayout>
		<TableView Intent="Form" x:Name="tableView">
			
			<TableRoot Title="Data Form">
				<TableSection Title="About Me">
					<EntryCell Label="Name:"
								 Text=""
								 Placeholder="Enter name"
								 Keyboard="Text"
								 x:Name="Name" />
					<EntryCell Label="Email:"
								 Text=""
								 Placeholder="Enter email address"
								 Keyboard="Email"
								 x:Name="Email" />
					<EntryCell Label="Phone:"
								 Text=""
								 Placeholder="Enter phone number"
								 Keyboard="Telephone"
								 x:Name="Phone" />
					<EntryCell Label="Age:"
								 Text=""
								 Placeholder="Enter age"
								 Keyboard="Numeric"
								 x:Name="Age" />
					<EntryCell Label="Language:"
								 Text=""
								 Placeholder="Enter language"
								 Keyboard="Text"
								 x:Name="Language" />
					<SwitchCell Text="Retired?"
									 x:Name="IsRetired" />
					<ViewCell>
						<ViewCell.View>
							<StackLayout Orientation="Horizontal"
										 Padding="16, 0">
								<Label Text="Smartphone:"
										 VerticalOptions="Center" />
								<Picker Title="	Platform	"
										IsEnabled="True"
										x:Name="Platform">
									<Picker.Items>
										<x:String>Android</x:String>
										<x:String>iOS</x:String>
										<x:String>WinPhone</x:String>
										<x:String>Other</x:String>
									</Picker.Items>
								</Picker>
							</StackLayout>
						</ViewCell.View>
					</ViewCell>
				</TableSection>
			</TableRoot>
		</TableView>
		<Button Text="Submit"
				HorizontalOptions="Center" />
	</StackLayout>

</ContentPage>

WebView

WebView inserts a web browser into the form. It is a crude way to embed a web site into an app.

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
		xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
		xmlns:local="clr-namespace:HelloXamarinForms"
		x:Class="HelloXamarinForms.MainPageXaml">

	<ContentPage.Padding>
		<OnPlatform x:TypeArguments="Thickness" iOS="10, 20, 10, 0" Android="10, 0" />
	</ContentPage.Padding>

	<StackLayout>

		<Entry Completed="OnAddressEntered" Keyboard="Url" Placeholder="address" />

		<StackLayout BindingContext="{x:Reference webview}" Orientation="Horizontal">
			<Button Clicked="OnBack" Text="&lt; Back" IsEnabled="{Binding CanGoBack}" HorizontalOptions="FillAndExpand" />
			<Button Clicked="OnForward" Text="Forward &gt;" IsEnabled="{Binding CanGoForward}" HorizontalOptions="FillAndExpand" />
		</StackLayout>

		<WebView x:Name="webview" VerticalOptions="FillAndExpand" />

	</StackLayout>
</ContentPage>
using Xamarin.Forms;

namespace HelloXamarinForms
{
	public partial class MainPageXaml : ContentPage
	{
		public MainPageXaml()
		{
			InitializeComponent();
		}

		void OnAddressEntered(object sender, System.EventArgs e)
		{
			webview.Source = ((Entry)sender).Text;
		}

		void OnBack(object sender, System.EventArgs e)
		{
			webview.GoBack();
		}

		void OnForward(object sender, System.EventArgs e)
		{
			webview.GoForward();
		}
	}
}
<<<[Page 3 of 11]>>>


This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE