2016-09-04 32 views
0

我想使View類的ViewModel成爲其一部分(本身是基於xaml的)。我正在使用的框架是Xamarian.Forms如何在xamarin-forms基於xaml的視圖類中綁定到這個

現在我試着對x:Name xaml中的根對象進行設置,然後設置綁定上下文以引用該名稱。

MainPage.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:App" 
      x:Class="App.MainPage" 
      x:Name="MainPageRoot"> 

    <Label 
    BindingContext="{x:Reference Name=MainPageRoot}" 
    Text="{Binding Path=LabelText}" 
    VerticalOptions="Center" 
    HorizontalOptions="Center" /> 

</ContentPage> 

我在MainPage.xaml.cs添加的數據:

namespace App 
{ 
    public partial class MainPage : ContentPage 
    { 
     public string LabelText; 

     public MainPage() 
     { 
      LabelText = "Wow, this works"; 
      InitializeComponent(); 
     } 
    } 
} 

但標籤仍然是空的。

爲什麼這不起作用?我如何使用this的房產?

回答

0

的問題是,該LabelText屬性沒有消氣定義,此代碼的工作:

public partial class MainPage : ContentPage 
{ 
    public string LabelText { get; } 

    public MainPage() 
    { 
     LabelText = "Wow, this works"; 
     InitializeComponent(); 
    } 
}