2017-02-13 121 views
2

我无法获取ControlTemplate中定义的绑定以对抗我的模型。Xamarin表单 - 绑定到ControlTemplate

注意在下面的ControlTemplate中,我使用TemplateBinding绑定到名为Count(橄榄色标签)的属性。我正在使用Parent.Count作为prescribed by this article,但是Parent.Count计数都不起作用。

enter image description here

下页使用的ControlTemplate。只是为了证明我的ViewModel工作,我也有一个灰色的标签绑定到Count属性。

enter image description here

通知所得到的屏幕。灰色标签显示Count属性。 ControlTemplate的橄榄色标签没有显示任何内容。

enter image description here

我怎样才能让在控件模板标签显示来自视图模型Count属性?

视图模型

namespace SimpleApp 
{ 
    public class MainViewModel : INotifyPropertyChanged 
    { 
     public MainViewModel() 
     { 
      _count = 10; 
      Uptick = new Command(() => { Count++; }); 
     } 

     private int _count; 
     public int Count 
     { 
      get { return _count; } 
      set 
      { 
       _count = value; 
       OnPropertyChanged("Count"); 
      } 
     } 

     public ICommand Uptick { get; private set; } 

     public event PropertyChangedEventHandler PropertyChanged; 
     protected virtual void OnPropertyChanged(string propertyName) 
     { 
      if (PropertyChanged != null) 
       PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 
} 

XAML

<?xml version="1.0" encoding="utf-8" ?> 
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
      xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
      xmlns:local="clr-namespace:SimpleApp" 
      x:Class="SimpleApp.MainPage" 
      ControlTemplate="{StaticResource ParentPage}"> 
    <StackLayout> 
     <Button Command="{Binding Uptick}" Text="Increment Count" /> 
     <Label Text="{Binding Count}" BackgroundColor="Gray" /> 
    </StackLayout> 
</ContentPage> 

后面的代码

通知的BindingContext在此处设置为MainViewModel。我需要使用我自己的ViewModel,而不是背后的代码。

namespace SimpleApp 
{ 
    public partial class MainPage : ContentPage 
    { 
     public MainPage() 
     { 
      BindingContext = new MainViewModel(); 

      InitializeComponent(); 
     } 
    } 
} 

控件模板

<?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="SimpleApp.App"> 
    <Application.Resources> 

     <ResourceDictionary> 
      <ControlTemplate x:Key="ParentPage"> 

       <StackLayout> 
        <Label Text="{TemplateBinding Parent.Count}" BackgroundColor="Olive" /> 
        <ContentPresenter /> 
       </StackLayout> 

      </ControlTemplate> 
     </ResourceDictionary> 

    </Application.Resources> 
</Application> 
+0

它应该是

+0

我已经尝试过,但它也不起作用。 –

+0

还检查NuGets包和Xamarin本身的更新吗?我重新安装了我的电脑,现在没有Xamarin在这里。我想在这里测试。 – Tony

回答

7

在您的ControlTemplate,请使用以下代码:

<Label Text="{TemplateBinding BindingContext.Count}" BackgroundColor="Olive" /> 

似乎BindingContext中没有被自动应用到您的ContentPage的孩子,也许它可能是Xamarin中的一个错误。

+0

它的工作!你是怎么找到这些信息的? – Heshan