简体   繁体   English

绑定到 ControlTemplate 中的属性不起作用

[英]Binding to a property in ControlTemplate does not work

I have a mobile app with Xamarin.Forms and FreshMvvm.我有一个带有 Xamarin.Forms 和 FreshMvvm 的移动应用程序。 Every page uses a control template defined in App.xaml:每个页面都使用 App.xaml 中定义的控件模板:

          <ControlTemplate x:Key="MainPageTemplate">
            <Grid BindingContext="{Binding Source={RelativeSource TemplatedParent}}">
                <Grid.RowDefinitions>
                    <RowDefinition Height="*" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="9*" />
                </Grid.RowDefinitions>
                <Image Source="{local:ImageResource MyApp.Images.My_logo.jpg}" Margin="0, 0, 0, 5" Grid.Row="0" />
                <Label Text="{Binding ScreenName}" FontSize="Subtitle" TextColor="Black" FontAttributes="Bold" HorizontalOptions="Center" Grid.Row="1" />
                <Label Text="{Binding ErrorMessage}" TextColor="Red" Grid.Row="2" />
                <ContentPresenter Margin="10, 0, 10, 10" Grid.Row="3" />
            </Grid>
        </ControlTemplate>

The ScreenName property is defined in the PageModel like this: ScreenName 属性在 PageModel 中定义如下:

        protected string _screenName;

        public string ScreenName => _screenName;

For some reason, the ScreenName is not showing up on the page that uses the control template.由于某种原因,屏幕名称未显示在使用控件模板的页面上。 It does if I replace the Binding with a hard-coded text:如果我将 Binding 替换为硬编码文本,它就会执行:

<Label Text="Something" ...

When setting your BindingContext to your {RelativeSource TemplatedParent} , your binding context is the page.BindingContext设置为{RelativeSource TemplatedParent}时,您的绑定上下文就是页面。

To access your ViewModel, you must change your xaml to access your property through the "BindingContext" of your page.要访问您的 ViewModel,您必须更改您的 xaml 以通过页面的“BindingContext”访问您的属性。

<Label Text="{Binding BindingContext.ScreenName}" FontSize="Subtitle" TextColor="Black" FontAttributes="Bold" HorizontalOptions="Center" Grid.Row="1" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM