繁体   English   中英

如何将简单字符串 object 绑定到 Label Xamarin Z6450242531912981C3683CAE8Z 中的文本

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

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

这是我的 C# 代码

public string Name { get; set; }

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

这是我的 XAML 代码

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

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

了解 MVVM 模式以及如何执行数据绑定非常重要。 你可以看到这个链接: 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 视图中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM