我知道XAML实际上没有从另一个页面扩展(继承)的工具,但是我看到其他人使用ControlTemplates来实现这种效果。
在这种情况下,我很难找到一个绑定。在我的示例中,我有一个由ContentPage扩展的基本MainPage。而且,我使用的是FreshMVVM,所以这就是为什么视图模型是最小的,因为FreshMVVM处理所有属性更改通知的管道。
当应用程序运行时,标签应该得到在MainPageModel中初始化的值"Xamarin Forms Header“。
我在github 这里上有一个完全可运行的源代码,但是下面是代码。有人能看到问题所在吗?
MainPage.xaml
<local:PageBase xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:SampleApp"
x:Class="SampleApp.MainPage">
<StackLayout>
</StackLayout>
</local:PageBase>MainPageModel.xaml
public class MainPageModel : FreshBasePageModel
{
public MainPageModel()
{
LabelText = "Xamarin Forms Header";
}
public string LabelText { get; set; }
}PageBase.xaml
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="SampleApp.PageBase">
<ContentPage.ControlTemplate>
<ControlTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Label Grid.Row="0" Text="{Binding LabelText}" />
<ContentPresenter Grid.Row="1" />
</Grid>
</ControlTemplate>
</ContentPage.ControlTemplate>
</ContentPage>发布于 2019-07-15 09:02:12
你可以尝试像这样改变:
MainPage.xaml:
<?xml version="1.0" encoding="utf-8" ?>
<local:PageBase xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:SampleApp"
x:Class="SampleApp.MainPage"
LabelText ="{Binding LabelText} "
>
<StackLayout>
</StackLayout>
</local:PageBase>PageBase.xaml
<?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="SampleApp.PageBase">
<ContentPage.ControlTemplate>
<ControlTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Label Grid.Row="0" Text="{TemplateBinding LabelText}" />
<ContentPresenter Grid.Row="1" />
</Grid>
</ControlTemplate>
</ContentPage.ControlTemplate>
</ContentPage>在你的PageBase.xaml.cs里
public partial class PageBase : ContentPage
{
public static readonly BindableProperty LabelTextProperty = BindableProperty.Create("LabelText", typeof(string), typeof(PageBase), "Control Template Demo App");
public string LabelText
{
get { return (string)GetValue(LabelTextProperty); }
}
public PageBase ()
{
InitializeComponent ();
}
}您可以参考TemplateBinding
发布于 2019-07-12 20:40:51
TemplateBinding不绑定到视图模型,所以整个代码都是错误的,请阅读主题https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/templates/control-templates/template-binding
同样值得注意的是,如果您使用Binding而不是TemplateBinding,这可能会奏效,但我不认为这样做是有意义的,因为我说了一些根本问题。
https://stackoverflow.com/questions/57013261
复制相似问题