【问题标题】:Why doesn't my Xamarin.Forms Entry get empty in the UI when I set the bound string to ""?当我将绑定字符串设置为“”时,为什么我的 Xamarin.Forms 条目在 UI 中没有变空?
【发布时间】:2019-04-25 08:24:04
【问题描述】:

我使用以下方法来设置我的变量:

    private string _password = "";
    public string Password
    {
        get => _password;
        set {
            _password = value;
            this.OnPropertyChanged("Password");
            this.OnPropertyChanged("_password");
        }
    }

这是在我通过以下方式绑定的 ViewModel 中:

<ContentPage.BindingContext>
    <vm:MainPageViewModel/>
</ContentPage.BindingContext>

我的 xaml 中有一个条目:

<Entry Text="{Binding Password,Mode=TwoWay}"                               
   HorizontalOptions="Start"
   VerticalOptions="Start">
</Entry>

我在 ViewModel 中访问条目中的信息没有问题,但是当我调用时

Password = "";

在屏幕上的 UI 中显示的条目文本保持不变。如何从我的 ViewModel 中删除条目中的文本? 该行为发生在 Android/iOS 和 UWP 中。

【问题讨论】:

  • 你的虚拟机真的实现了 INotifyPropertyChanged 吗?

标签: xamarin xamarin.forms


【解决方案1】:

进行以下更改,它应该适合您:

当您通知属性已更改而不是字段已更改时,请删除此 this.OnPropertyChanged("_password");

因此它看起来像:

 public string Password
{
    get => _password;
    set {
        _password = value;
        this.OnPropertyChanged("Password");           
    }
}

其次,据我所知,您可能希望在 MainThread 上更改密码,例如:

 Device.BeginInvokeOnMainThread(() => { Password = string.Empty; });

INotifyPropertyChanged 的原因不是线程安全的!你可以在异步方法中这样做

【讨论】:

  • 谢谢,使用Device.BeginInvokeOnMainThread 对我有帮助。
猜你喜欢
  • 2015-03-11
  • 1970-01-01
  • 1970-01-01
  • 2020-01-14
  • 1970-01-01
  • 1970-01-01
  • 2020-08-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多