Xamarin Forms 将属性绑定到标签的文本 [英] Xamarin Forms bind property to label's text

查看:26
本文介绍了Xamarin Forms 将属性绑定到标签的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 Xamarin Forms xaml:

I have 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>

而且我有代码:

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

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

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

It should bind myProperty to label's text. However, nothing displays in the label. How to bind myProperty to label's text? (I know I should use ViewModel to be able to notify view about changes of the property but in this example I really just want to bind myProperty from code behind to the label)

推荐答案

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

You need to declare that you can "get" the variable.

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

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

If you actually want to change this variable in code, your class will need to implement INotifyPropertyChanged, otherwise it will always be "MY TEXT"

这篇关于Xamarin Forms 将属性绑定到标签的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆