Xamarin表单绑定属性标签的文本

问题描述:

我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从代码后面绑定到标签)

您需要声明可以“获取”变量。

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

如果你真的想改变这个代码变量,你的类需要执行INotifyPropertyChanged,否则将永远是“个人文本”

+0

...你要叫“OnPropertyChanged(nameof (myProperty)); *更改内容后 – copa017

您需要使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)); } 
    } 
}