Xamarin.Forms: bind to a code behind property in XAML
Just add BindingContext = this;
in code behind file.
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:TrackValigie"
x:Class="TrackValigie.SelViaggioPage">
<ContentPage.Content>
<StackLayout>
<Label Text="{Binding LblText}" />
</StackLayout>
</ContentPage.Content>
</ContentPage>
Code Behind
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SelViaggioPage : ContentPage
{
private string _lblText;
public string LblText
{
get
{
return _lblText;
}
set
{
_lblText = value;
OnPropertyChanged();
}
}
public SelViaggioPage()
{
InitializeComponent();
BindingContext = this;
}
protected override void OnAppearing()
{
base.OnAppearing();
this.LblText = "Ciao!!";
}
}
You need to set the x:Name for ContentPage as mentioned by Jason's Answer .
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:TrackValigie"
x:Class="TrackValigie.SelViaggioPage"
x:Name = "MyControl"/>
Instead of using BindingContext, you can use ElementName
<TextBlock Text="{Binding ElementName=TestControl,Path=StudentName}"/>
Or if you don't want to swap the binding context for the entire control then use the following:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Name="this"
x:Class="SomePage">
<ContentPage.Content>
<StackLayout>
<Label Text="{Binding SomeProp, Source={x:Reference this}}" />
</StackLayout>
</ContentPage.Content>
</ContentPage>
your page will need to implement INotifyPropertyChanged
, but the binding syntax should just be
<ContentPage x:Name="MyPage" ... />
...
<Label BindingContext="{x:Reference Name=MyPage}" Text="{Binding LblText}" />