Xamarin Forms 模型中的绑定页面标题

Xamarin Forms Binding Page Title from Model

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

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 应该是您的视图模型的名称。

在您的视图模型中,您必须将模型设置为 public 属性:

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 中,我们知道:

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.

我制作了一个简单的demo,你可以参考下面的代码:

1.create 一个 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.In OurPage.xaml.cs

我们可以设置BindingContext

public partial class MainPage : ContentPage
{
    TestViewModel viewModel;
    public MainPage()
    {
        InitializeComponent();

        viewModel = new TestViewModel();

        this.BindingContext = viewModel;
    }
}

3.In 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>