到目前为止,大多数示例使用 Xamarin.Forms正在使用 C# 来构建 UI。我更喜欢将 XAML 用于 UI,并将其数据绑定(bind)到 ViewModels。
我在使用 Xamarin.Forms.MasterDetailPage 时遇到问题结合 XAML,我似乎无法将 C# 示例移植到 XAML + ViewModels。
这是我到目前为止得到的 XAML:
<?xml version="1.0" encoding="UTF-8" ?>
<MasterDetailPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:NSContacten;assembly=NSContacten"
x:Class="MasterDetailExample.Main"
Title="Master Detail Example">
<MasterDetailPage.Master BindingContext="{Binding Menu}">
<ContentPage Padding="5, 25">
<StackLayout Orientation="Vertical">
<Label Text="Master" HorizontalOptions="Center" />
<Label Text="{Binding Subtitle}" HorizontalOptions="Center" />
</StackLayout>
</ContentPage>
</MasterDetailPage.Master>
<MasterDetailPage.Detail BindingContext="{Binding Detailpage}">
<ContentPage Padding="5, 25">
<StackLayout Orientation="Vertical">
<Label Text="Detail" HorizontalOptions="Center" />
<Label Text="{Binding Subtitle}" HorizontalOptions="Center" />
</StackLayout>
</ContentPage>
</MasterDetailPage.Detail>
</MasterDetailPage>
该组件有效:我确实看到了“主”和“详细”标签。不显示绑定(bind)标签(在 BindingContext 对象上)。
我使用了很多不同的组合,但我仍然卡住:这是如何工作的?我的绑定(bind)不正确(应该在“ContentPage”上),我不能绑定(bind)到 .Master 和 .Detail 属性等吗? “菜单”和“详细信息页面”绑定(bind)应该是什么样子?
如果有人可以帮助我,那将是一个巨大的帮助!下一步是当在 .Master 中按下按钮时 .Detail 将被更改。提前致谢!
最佳答案
您的 Xaml 几乎没问题,但是:
{BindingContext}
在属性上无效,应该在 ContentPage
上元素 MasterDetailPage.Master
需要 Page.Title
要设置,否则它会抛出。 这是为我工作的正确 Xaml:
<?xml version="1.0" encoding="UTF-8" ?>
<MasterDetailPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:NSContacten;assembly=NSContacten"
x:Class="MasterDetailExample.Main"
Title="Master Detail Example">
<MasterDetailPage.Master>
<ContentPage Padding="5, 25" BindingContext="{Binding Menu}" Title="Master">
<StackLayout Orientation="Vertical">
<Label Text="Master" HorizontalOptions="Center" />
<Label Text="{Binding Subtitle}" HorizontalOptions="Center" />
</StackLayout>
</ContentPage>
</MasterDetailPage.Master>
<MasterDetailPage.Detail>
<ContentPage Padding="5, 25" BindingContext="{Binding Detailpage}">
<StackLayout Orientation="Vertical">
<Label Text="Detail" HorizontalOptions="Center" />
<Label Text="{Binding Subtitle}" HorizontalOptions="Center" />
</StackLayout>
</ContentPage>
</MasterDetailPage.Detail>
</MasterDetailPage>
我使用匿名类型作为页面 View 模型对其进行了测试:
public MyMDPage ()
{
InitializeComponent ();
BindingContext = new {
Menu = new { Subtitle = "I'm Master" },
Detailpage = new { Subtitle = "I'm Detail" }
};
}
这很好用。在您的情况下,您可能希望 View 模型的具体类型而不是匿名类型,但您明白了。
关于xaml - Xamarin.Forms 中 MasterDetailPage 的 XAML 中的数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24229168/