如何将简单的字符串对象绑定到 Xamarin Forms 中的标签文本?

How to bind simple string object to a Label Text in Xamarin Forms?

我是Xamarin开发的新手,如果问题太简单请多包涵。我的 C# 代码(代码隐藏)中有一个简单的单个 string 对象。我想将它绑定到 XAML 中的 Label,以便每当字符串更改时,它都会反映在 XAML 页面中。

这是我的 C# 代码

public string Name { get; set; }

public HomePage()
{
    InitializeComponent();
    BindingContext = this;
    Name = "John";
}

这是我的XAML代码

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

我该怎么做。我做错了什么吗?

了解 MVVM 模式以及如何执行数据绑定很重要。你可以看到这个link:https://docs.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-basics/data-bindings-to-mvvm.

基本上,你可以这样做:

为您的主页创建一个 ViewModel。

public class HomePageViewModel : INotifyPropertyChanged
{
    private string name;
    public string Name
    {
        get
        {
            return name;
        }
        set
        {
            name = value;
            OnPropertyChanged(nameof(Name));
        }
    }
    public HomePageViewModel()
    {
        // some initialization code here ...
        Name = "John";
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

}

现在将您的 ViewModel 附加到主页视图

public HomePageView()
{
    InitializeComponent();
    BindingContext = new HomePageViewModel();
}

然后在您的 XAML 中,您可以这样绑定:

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

那么每当 ViewModel 中的 Name 发生变化时,它都会反映在 XAML 视图中。