Reputation: 37
Does anyone know how to bind a Page Title from a model? I wanted to make the Name property as Title Page below is my code
Xaml
<ContentPage BackgroundColor="White"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="app.MainMenuPage"
NavigationPage.HasBackButton="False">
<NavigationPage.TitleView>
<StackLayout>
<Label Text="{Binding Name}"/>
</StackLayout>
</NavigationPage.TitleView>
My Model
public class EmployeeDetails
{
public string PersonnelNumber { get; set; }
public string PrimaryContactEmail { get; set; }
public string Name { get; set; }
}
Upvotes: 1
Views: 2027
Reputation: 13813
If we want to bind a model and display the data of our model to our page, we need to set the model to the BindingContext
of our page. And in general, we usually create a ViewModel for our page.
From document ViewModel , we know that:
The view model implements properties and commands to which the view can data bind to, and notifies the view of any state changes through change notification events. The properties and commands that the view model provides define the functionality to be offered by the UI.
I created a simple demo, you can refer to the following code:
1.create a ViewModel (TestViewModel.cs
) :
In this ViewModel, we can init our data(employee
) .
public class TestViewModel
{
public EmployeeDetails employee { get; set; }
public TestViewModel() {
employee = new EmployeeDetails { PersonnelNumber = "01", Name = "Jack", PrimaryContactEmail = "[email protected]" };
}
}
2.In OurPage.xaml.cs
we can set the BindingContext
public partial class MainPage : ContentPage
{
TestViewModel viewModel;
public MainPage()
{
InitializeComponent();
viewModel = new TestViewModel();
this.BindingContext = viewModel;
}
}
3.In OurPage.xaml
we can display our data like this(<Label Text="{Binding employee.Name}"/>
):
<?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:Class="FormApp1214.MainPage">
<NavigationPage.TitleView>
<StackLayout>
<Label Text="{Binding employee.Name}"/>
</StackLayout>
</NavigationPage.TitleView>
<StackLayout>
</StackLayout>
</ContentPage>
Upvotes: 1
Reputation: 51
You can do it through your viewmodel, assigning your viewmodel to your view with the bindingContext, put this in the constructor of your view BindingContext = new TEstViewModel();
TEstViewModel should be the name of your viewModel.
In your viewmodel you have to have your model as a public property:
public EmployeeDetails Detail { get; set; }
Then in your XAML view you can put Detail.Name
<ContentPage BackgroundColor="White"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="app.MainMenuPage"
Title="{Binding Detail.Name}"
NavigationPage.HasBackButton="False">
Upvotes: 2