Binding 以Xamarin形式与BasePage绑定

Binding 以Xamarin形式与BasePage绑定,binding,xamarin.forms,freshmvvm,binding-context,Binding,Xamarin.forms,Freshmvvm,Binding Context,我正在用FreshMVVM框架实现一个Xamarin应用程序,我想使用一个BasePage在页面之间共享一些代码。 问题是,当我需要绑定MainPage.xaml中的某些属性时,我必须以这种方式指定源文件,以使其工作:Text=“{Binding Title,Source={x:Reference MainPage}}”。否则,没有源绑定将无法工作。 好的,我明白了,但这是正确的方法吗?有没有其他方法可以达到同样的效果?当我在一个页面中有很多绑定时会怎么样?例如,是否可以在un较高级别“设置”源

我正在用FreshMVVM框架实现一个Xamarin应用程序,我想使用一个BasePage在页面之间共享一些代码。 问题是,当我需要绑定MainPage.xaml中的某些属性时,我必须以这种方式指定源文件,以使其工作:Text=“{Binding Title,Source={x:Reference MainPage}}”。否则,没有绑定将无法工作。 好的,我明白了,但这是正确的方法吗?有没有其他方法可以达到同样的效果?当我在一个页面中有很多绑定时会怎么样?例如,是否可以在un较高级别“设置”源,因为在我看来,为每个绑定设置相同的源是非常烦人的

BasePage.xaml


BasePage.xaml.cs

使用Xamarin.Forms;
使用Xamarin.Forms.Xaml;
名称空间TestXamarin
{
[XamlCompilation(XamlCompilationOptions.Compile)]
公共部分类基页:ContentPage
{
公共静态只读BindableProperty TextProperty=BindableProperty.Create(
名称(文本),
类型(字符串),
类型(基本页));
公共字符串文本
{
获取{return(string)GetValue(TextProperty);}
set{SetValue(TextProperty,value);}
}
公共静态只读BindableProperty PageContentProperty=BindableProperty.Create(
名称(页面内容),
类型(对象),
类型(基本页));
公共对象页面内容
{
获取{返回GetValue(PageContentProperty);}
set{SetValue(PageContentProperty,value);}
}
公共基页()
{
初始化组件();
}
}

}
另一种实现您想要做的事情的方法是使用控件模板

在这里,我在App.xaml中定义了一个模板

<ControlTemplate x:Key="ActivityIndicatorTemplate">
    <Grid>
        <ContentPresenter />
        <StackLayout Style="{StaticResource BlockingPanel}"
                     IsVisible="{TemplateBinding BindingContext.IsBusy}">
            <ActivityIndicator Style="{StaticResource ActivityIndicatorStyle}"
                               IsVisible="{TemplateBinding BindingContext.IsBusy}"
                               IsRunning="{TemplateBinding BindingContext.IsBusy}" />
        </StackLayout>
    </Grid>
</ControlTemplate>

请注意内容呈现者和TemplateBinding

我在这样的页面上使用它

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Test.MyTestPage"
             ControlTemplate="{StaticResource ActivityIndicatorTemplate}"
             Title="{Binding Title}">

    <Grid>
    ...
    </Grid>
</ContentPage>

...

页面内容将替换模板中的内容演示者。看起来比基本页面简单。

您使用的是MVVM框架吗?如果不是,我建议您研究一下,因为它可以大大简化您的绑定体验。只有
BindingContext
支持属性值继承,而不是
Source
@StevenThewissen实际上我使用的是FreshMVVM,但它似乎有同样的问题。是的,您提出的是一个有效的解决方案,事实上,目前我正在通过使用ControlTemplate摆脱这个问题。我不喜欢这个解决方案的一点是,它对BasePage方法的灵活性很小。据我所知,将参数传递给ControlTemplate的唯一方法是从ViewModel属性进行绑定,而在某些情况下,我希望从Xaml页面设置参数,并使用BindableProperty来完成。