Xamarin Forms将属性绑定到标签的文本

Mar*_*sek 8 xamarin

我有Xamarin Forms 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:BlankAppXamlXamarinForms"
             x:Class="BlankAppXamlXamarinForms.MainPage">

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

</ContentPage>
Run Code Online (Sandbox Code Playgroud)

我有代码背后:

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

        public MainPage()
        {
            InitializeComponent();
            BindingContext = this;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

它应该将myProperty绑定到标签的文本.但是,标签中没有显示任何内容.如何将myProperty绑定到标签的文本?(我知道我应该使用ViewModel来通知视图有关属性的更改,但在这个例子中我真的只想将myProperty从代码绑定到标签)

Ric*_*ike 6

你需要声明你可以"获取"变量.

public string myProperty { get; } = "MY TEXT";
Run Code Online (Sandbox Code Playgroud)

如果你真的想在代码中改变这个变量,那么你的类需要实现INotifyPropertyChanged,否则它将永远是"MY TEXT"

  • ...并且您必须在更改内容后调用 'OnPropertyChanged(nameof(myProperty));* (2认同)