问题描述
我有一个带有Xamarin.Forms和FreshMvvm的移动应用程序。每个页面都使用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,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,10,10" Grid.Row="3" />
</Grid>
</ControlTemplate>
ScreenName属性在PageModel中定义如下:
protected string _screenName;
public string ScreenName => _screenName;
由于某些原因,使用控件模板的页面上没有显示ScreenName。如果我将绑定替换为硬编码的文本,它将起作用:
<Label Text="Something" ...
解决方法
将BindingContext
设置为{RelativeSource TemplatedParent}
时,绑定上下文就是页面。
要访问ViewModel,必须更改xaml以通过页面的“ BindingContext”访问属性。
<Label Text="{Binding BindingContext.ScreenName}" FontSize="Subtitle" TextColor="Black" FontAttributes="Bold" HorizontalOptions="Center" Grid.Row="1" />