c# - 我的绑定(bind)标签没有改变 [INotifyPropertyChanged]

标签 c# xamarin xamarin.forms

我最近开始学习 Xamarin,我偶然发现了以下问题。我的 XAML 文件中有一个标签绑定(bind)到 ViewModel 属性。我正在使用 ICommand 接口(interface)将点击手势绑定(bind)到我的 ViewModel 中的一个方法,该方法应该更新标签的文本。但是,它没有更新“请触摸我一次!”。我只是想知道我在这里做错了什么?

主页 xaml:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:App1"
         x:Class="App1.MainPage">

<Label Text="{Binding MessageContent, Mode=TwoWay}"
       VerticalOptions="Center"
       HorizontalOptions="Center">
    <Label.GestureRecognizers>
        <TapGestureRecognizer Command="{Binding OnLabelTouchedCmd}" />
    </Label.GestureRecognizers>

</Label>

</ContentPage>

代码隐藏:

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();

        BindingContext = new MainPageViewModel();
    }
}

View 模型:

class MainPageViewModel : INotifyPropertyChanged
{
    private string _messageContent;

    public MainPageViewModel()
    {
        MessageContent = "Please touch me once!";

        OnLabelTouchedCmd = new Command(() => { MessageContent = "Hey, stop toutching me!"; });
    }

    public ICommand OnLabelTouchedCmd { get; private set; }

    public string MessageContent
    {
        get => _messageContent;
        set
        {
            _messageContent = value;
            OnPropertyChanged(value);
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;


    protected virtual void OnPropertyChanged(string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

最佳答案

您正在调用 OnPropertyChanged有一个错误的论点,如下所示:

protected virtual Void OnPropertyChanged ([System.Runtime.CompilerServices.CallerMemberName] String propertyName)

它需要属性的名称而不是您现在传递的值。试试这个:

public string MessageContent
{
    get => _messageContent;
    set
    {
        _messageContent = value;
         OnPropertyChanged("MessageContent");
    }
}

关于c# - 我的绑定(bind)标签没有改变 [INotifyPropertyChanged],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46014265/

相关文章:

c# - 将组合框绑定(bind)到模型/ View 模型

c# - 根据嵌套数组内的条件选择对象

c# - 并行 C#

android - 在我的本地 andorid 设备上部署解决方案时,Xamarin.Android 不支持运行以前的版本

azure - 在 Xamarin 和 Microsoft Authenticator 中使用 ADAL for .NET 进行身份验证在 iOS 上失败

c# - 搜索栏 xamarin 表单

xamarin.forms - Xamarin Forms共享项目新内容页面cs文件未耦合

c# - 如何以 DateTime 格式初始化 8 小时

android - Xamarin.Forms 中心标题和透明导航栏 - Android

pdf - 保护 pdf 文件和 Xamarin Forms 的安全