Mvvm Xamarin.Forms控件模板绑定不起作用
我在我的App.xaml中指定了一个控件模板:Mvvm Xamarin.Forms控件模板绑定不起作用,mvvm,xamarin.forms,controltemplate,Mvvm,Xamarin.forms,Controltemplate,我在我的App.xaml中指定了一个控件模板: <?xml version="1.0" encoding="utf-8"?> <Application xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="MyApp.App"> <Application.Resources>
<?xml version="1.0" encoding="utf-8"?>
<Application xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="MyApp.App">
<Application.Resources>
<ResourceDictionary>
<ControlTemplate x:Key="PageTemplate">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<BoxView Grid.Row="0"
Grid.RowSpan="3"
BackgroundColor="#2B653E"/>
<Label Grid.Row="1"
TextColor="White"
HorizontalOptions="Center"
FontSize="36"
FontFamily="TimesNewRomanPS-BoldMT"
Text="{TemplateBinding BindingContext.HeadingText}"/>
<Image Grid.Row="2"
Grid.RowSpan="2"
Source="TGL_BG"/>
<ContentPresenter Grid.Row="4"/>
</Grid>
</ControlTemplate>
</ResourceDictionary>
</Application.Resources>
</Application>
控件模板工作正常,我可以将其添加到页面中,没有任何问题,但绑定属性不显示:
这是我的页面代码:
<?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="MyApp.Pages.ContactPage">
<ContentView ControlTemplate="{StaticResource PageTemplate}">
<StackLayout>
<!-- Page content here, removed for brevity -->
</StackLayout>
</ContentView>
</ContentPage>
在这里,您可以看到我正在将绑定上下文设置为ViewModel(它适用于模板之外的所有内容)。这是我的ViewModel:
使用系统;
使用System.Collections.Generic;
使用系统文本;
使用System.Threading.Tasks;
使用System.Windows.Input;
使用MyApp.Helpers;
使用Xamarin.Forms;
名称空间MyApp.ViewModels
{
公共类ContactPageViewModel:ViewModel
{
公共字符串HeadingText=“联系我们”;
//此处的其他属性和命令,为简洁起见已删除
}
}
正如您所看到的,我在这里有一个公共属性,名为'HeadingText',它是我在视图中绑定到的
我已经阅读了文档和一些示例/教程。据我所见,这应该行得通。有人知道这有什么问题吗
编辑:
我现在已经让它工作了。在我的ViewModel中,我更改了以下内容:
public string HeadingText=“联系我们”;
为此:
公共字符串头文本
{
得到
{
返回“联系我们”;
}
}
现在将问题留待讨论,希望有人能提供解释。绑定只适用于公共属性
// this is a field, not a property
public string HeadingText = "Contact Us";
// this is a property
public string HeadingText
{
get
{
return "Contact Us";
}
}
是的,问题是使用属性。()您可以发布答案并将其标记。如果您想让它更干净,可以编写公共字符串HeadingText=>“联系我们”;谢谢Jason,是的,我知道这一点(这是从我的帖子中直接出来的),我只是在努力理解它,因为它似乎违反了封装。
// this is a field, not a property
public string HeadingText = "Contact Us";
// this is a property
public string HeadingText
{
get
{
return "Contact Us";
}
}