【发布时间】:2019-02-19 00:40:11
【问题描述】:
我在我的 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>
<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>
你可以看到我有一个我的控件数据绑定:
Text="{TemplateBinding BindingContext.HeadingText}"
控件模板工作正常,我可以将其添加到页面没有任何问题,除了绑定的属性不显示:
这是我的页面代码:
<?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>
这是我的代码:
using System;
using System.Collections.Generic;
using MyApp.ViewModels;
using Xamarin.Forms;
namespace MyApp.Pages
{
public partial class ContactPage : ContentPage
{
public ContactPage(ContactPageViewModel viewModel)
{
InitializeComponent();
viewModel.Navigation = Navigation;
BindingContext = viewModel;
}
}
}
在这里您可以看到我正在将绑定上下文设置为 ViewModel(适用于模板之外的所有内容)。这是我的 ViewModel:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using MyApp.Helpers;
using Xamarin.Forms;
namespace MyApp.ViewModels
{
public class ContactPageViewModel : ViewModel
{
public string HeadingText = "Contact Us";
//Other properties and commands here, removed for brevity
}
}
如您所见,我在这里有一个名为“HeadingText”的公共属性,这是我在视图中绑定的。
我已阅读文档和一些示例/教程。据我所见,这应该可行。谁能看出这是怎么回事?
编辑:
我现在已经开始工作了。在我的 ViewModel 中,我改变了这个:
public string HeadingText = "Contact Us";
到这里:
public string HeadingText
{
get
{
return "Contact Us";
}
}
现在让问题悬而未决,希望有人能提供解释。
【问题讨论】:
-
是的,问题是使用属性。(docs.microsoft.com/en-us/dotnet/csharp/programming-guide/…) 你可以发布答案并标记它。
-
如果你想让它更干净一点,你可以写 public string HeadingText => "Contact Us";
标签: mvvm xamarin.forms controltemplate