2016-08-23 41 views
1

我Xamarin窗體XAML:Xamarin表單綁定屬性標籤的文本

// 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:BlankAppXamlXamarinForms" 
      x:Class="BlankAppXamlXamarinForms.MainPage"> 

<Label Text="{Binding myProperty}" /> 

</ContentPage> 

而且我後面的代碼:

// MainPage.xaml.cs 
namespace BlankAppXamlXamarinForms { 
    public partial class MainPage : ContentPage 
    { 
     public string myProperty= "MY TEXT"; 

     public MainPage() 
     { 
      InitializeComponent(); 
      BindingContext = this; 
     } 
    } 
} 

應該myProperty的綁定到標籤的文本。但是,標籤中沒有顯示任何內容。如何將myProperty綁定到標籤的文本? (我知道我應該使用ViewModel能夠通知有關屬性更改的視圖,但在此示例中我真的只想將myProperty從代碼後面綁定到標籤)

回答

2

您需要聲明可以「獲取」變量。

public string myProperty { get; } = "MY TEXT"; 

如果你真的想改變這個代碼變量,你的類需要執行INotifyPropertyChanged,否則將永遠是「個人文本」

+0

...你要叫「OnPropertyChanged(nameof (myProperty)); *更改內容後 – copa017

0

您需要使ContentPage實現爲INotifyPropertyChanged所以:

public partial class MainPage : ContentPage, System.ComponentModel.INotifyPropertyChanged { 

    public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; 

    .... 

    protected virtual void OnPropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string propertyName = null) { 

     System.ComponentModel.PropertyChangedEventHandler handler = PropertyChanged; 

     if(handler != null) { handler(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } 
    } 
}