Bindings
Bindings
Person.cs
public class Person
{
public string Name { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
}
mainPage.xaml
<ContentPage
x:Class="BindingDemo.MainPage">
<VerticalStackLayout
Padding="30,0"
Spacing="25"
VerticalOptions="Center">
<Label x:Name="txtName"
HorizontalOptions="Center"
Text="Usama"
FontSize="50"
VerticalOptions="Center"/>
<Button
x:Name="CounterBtn"
Text="Click me"
Clicked="OnCounterClicked"
HorizontalOptions="Fill" />
</VerticalStackLayout>
MainPage.xaml.cs
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
};
Binding personBinding = new Binding();
personBinding.Source = person;
personBinding.Path = "Name";
txtName.SetBinding(Label.TextProperty, personBinding);
}
}
Context binding
Person.cs
public class Person
{
public string Name { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
}
mainPage.xaml
<ContentPage x:Class="BindingDemo.MainPage">
<VerticalStackLayout
Padding="30,0"
Spacing="25"
VerticalOptions="Center">
<Label
// for method 1 this line is needed
// x:Name="txtName"
HorizontalOptions="Center"
Text="{Binding Name}"
FontSize="50"
VerticalOptions="Center"/>
<Label
// for method 1 this line is needed
// x:Name="txtPhone"
HorizontalOptions="Center"
Text="{Binding Phone}"
FontSize="50"
VerticalOptions="Center"/>
<Label
// for method 1 this line is needed
//x:Name="txtAddress"
HorizontalOptions="Center"
Text="{Binding Address}"
FontSize="50"
VerticalOptions="Center"/>
<Button
x:Name="CounterBtn"
Text="Click me"
Clicked="OnCounterClicked"
HorizontalOptions="Fill" />
</VerticalStackLayout>
MainPage.xaml.cs
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private void OnCounterClicked(object sender, EventArgs e)
{
var person = new Person()
{
Name = "Hammad",
Phone = "0009",
Address = "Usman hostel"
};
// method 1
// txtName.BindingContext = person;
// txtName.SetBinding(Label.TextProperty, "Name");
// txtPhone.BindingContext = person;
// txtPhone.SetBinding(Label.TextProperty, "Phone");
// txtAddress.BindingContext = person;
// txtAddress.SetBinding(Label.TextProperty, "Address");
//end here
// method 2
BindingContext=person;
}
}