In my previous (and first) posting on Learning Xamarin, I demonstrated how to create a pretty cool program out of the box. Let’s back up now, and start with a blank app, and see what we can build from there.
Create a new project as described in the previous posting, but this time choose a Blank application.
Next, let’s add a label to our user interface. Open the file MainPage.xaml and remove the label that is there, and replace it with this one:
<!-- Place new controls here -->
<Label
x:Name="WelcomeLabel"
Text="Welcome to Xamarin.Forms!"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand" />
Notice that our label has a Name property, we’ll be using that shortly. It also has a Text property for setting the text to be displayed, and then it has Horizontal and Vertical properties for setting where the text should appear. We’ll be coming back to these properties in later posts.
Run the application; you should see Welcome to Xamarin.Forms! in the center of your screen.
Now we want to add a button. The job of the button will be to change the text of the label. There are a lot of ways to do this, and we’re going to start with a dead simple approach. Later, we’ll see how to use properties and a ViewModel, but one step at a time.
First, add the button to the page, immediately below the label.
<Button Text="Change" Clicked="ButtonClicked" />
Notice that this button has a Text property (the text will be displayed on the button) and a Clicked property which is assigned the name ButtonClicked. ButtonClicked will be a method in the code-behind page (MainPage.Xaml.cs)
Open the code behind page and let’s add that method:
private void ButtonClicked( object sender,
EventArgs e )
{
WelcomeLabel.Text = "Hello Jesse!";
}
The ButtonClicked method, like all event handlers, returns void and takes two parameters. The first is the “sender” — in this case our Button, the second is of type EventArgs or a class derived from EventArgs. The base class EventArgs, has no properties or methods, it is just a placeholder.
In the body of the
Run the program again, and you should see Hello Jesse where you previously saw Welcome to Xamarin.Forms.
More to come, soon.