【问题标题】:Xamarin Forms bind property to label's textXamarin Forms 将属性绑定到标签的文本
【发布时间】:2016-12-30 10:22:09
【问题描述】:

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

【问题讨论】:

    标签: xamarin


    【解决方案1】:

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

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

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

    【讨论】:

    • ...您必须在更改内容后调用 'OnPropertyChanged(nameof(myProperty));*
    • INotifyPropertyChanged 在我的情况下不需要,但@copa017 是的,这很关键。谢谢!
    • 嘿@robbpriestley,你为什么不添加INotifyPropertyChanged
    猜你喜欢
    • 2018-09-09
    • 1970-01-01
    • 1970-01-01
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-10
    相关资源
    最近更新 更多