Я указал шаблон элемента управления в своем 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}"
Шаблон элемента управленияработает нормально, я могу добавить его на страницу без проблем, за исключением того, что свойство привязки не отображает:
![image](https://i.stack.imgur.com/7KoC2.png)
Here is my page code:
<?xml version="1.0" encoding="UTF-8"?>
Вот мой код:
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', к которому я привязываюсь в представлении.
IПрочитал документацию и несколько примеров / учебников.По тому, что я вижу, это должно работать.Кто-нибудь может увидеть, что с этим не так?
РЕДАКТИРОВАТЬ:
У меня теперь это работает.В моей ViewModel я изменил это:
public string HeadingText = "Contact Us";
на это:
public string HeadingText
{
get
{
return "Contact Us";
}
}
Оставив вопрос открытым, надеясь, что кто-то может дать объяснение.