Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin Forms bind property to label's text

Tags:

xamarin

I have Xamarin Forms xaml:

// MainPage.xaml
<?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:BlankAppXamlXamarinForms"
             x:Class="BlankAppXamlXamarinForms.MainPage">

<Label Text="{Binding myProperty}" />

</ContentPage>

And I have code behind:

// MainPage.xaml.cs
namespace BlankAppXamlXamarinForms {
    public partial class MainPage : ContentPage
    {
        public string myProperty= "MY TEXT";

        public MainPage()
        {
            InitializeComponent();
            BindingContext = this;
        }
    }
}

It should bind myProperty to label's text. However, nothing displays in the label. How to bind myProperty to label's text? (I know I should use ViewModel to be able to notify view about changes of the property but in this example I really just want to bind myProperty from code behind to the label)

like image 419
Martin Dusek Avatar asked Aug 23 '16 14:08

Martin Dusek


People also ask

How do you bind property in Xamarin forms?

The binding references the source object. To set the data binding, use the following two members of the target class: The BindingContext property specifies the source object. The SetBinding method specifies the target property and source property.

How do I use BindingContext in Xamarin forms?

Data Bindings In code, two steps are required: The BindingContext property of the target object must be set to the source object, and the SetBinding method (often used in conjunction with the Binding class) must be called on the target object to bind a property of that object to a property of the source object.

What is two way binding in Xamarin forms?

However, the default binding mode for the Value property of Slider is TwoWay . This means that when the Value property is a data-binding target, then the target is set from the source (as usual) but the source is also set from the target. This is what allows the Slider to be set from the initial Opacity value.

What is label in Xamarin?

A Label is used to display single-line text elements as well as multi-line blocks of text. The following example, adapted from the default Xamarin.Forms solution, shows a basic use: C# Copy.


1 Answers

You need to declare that you can "get" the variable.

public string myProperty { get; } = "MY TEXT";

If you actually want to change this variable in code, your class will need to implement INotifyPropertyChanged, otherwise it will always be "MY TEXT"

like image 107
Richard Pike Avatar answered Oct 16 '22 19:10

Richard Pike