2017-02-13 95 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