Xamarin从模型中形成绑定页面标题



有人知道如何从模型绑定页面标题吗?我想使名称属性作为标题页下面是我的代码

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>

我的型号

public class EmployeeDetails
{        
public string PersonnelNumber { get; set; }        
public string PrimaryContactEmail { get; set; }
public string Name { get; set; }
}

您可以通过您的视图模型,使用bindingContext将视图模型分配给视图,并将其放入视图BindingContext = new TEstViewModel();的构造函数中

TEstViewModel应该是您的viewModel的名称。

在你的视图模型中,你必须将你的模型作为公共财产:

public EmployeeDetails Detail { get; set; }

然后在XAML视图中,您可以放置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">

如果我们想绑定一个模型并将模型的数据显示到我们的页面,我们需要将模型设置为我们页面的BindingContext。通常,我们通常会为页面创建一个ViewModel。

从文档ViewModel中,我们知道:

视图模型实现视图所指向的属性和命令可以将数据绑定到,并通过更改通知事件。视图的属性和命令模型提供了定义UI提供的功能。

我创建了一个简单的演示,您可以参考以下代码:

1.创建ViewModel(TestViewModel.cs(:

在这个ViewModel中,我们可以初始化我们的数据(employee(。

public  class TestViewModel
{
public EmployeeDetails employee { get; set; }
public TestViewModel() {
employee = new EmployeeDetails { PersonnelNumber = "01", Name = "Jack", PrimaryContactEmail = "test123@gmail.com" };
}
}

2.在OurPage.xaml.cs

我们可以设置BindingContext

public partial class MainPage : ContentPage
{
TestViewModel viewModel;
public MainPage()
{
InitializeComponent();
viewModel = new TestViewModel();
this.BindingContext = viewModel;
}
}

3.OurPage.xaml

我们可以这样显示我们的数据(<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>

最新更新