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)
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.
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.
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.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With