【问题标题】:Xamarin DisplayAlert when entry max length reached达到条目最大长度时的 Xamarin DisplayAlert
【发布时间】:2021-10-18 05:07:27
【问题描述】:

我有一个设置为最大长度 3 的条目。当用户尝试输入 4 个字符时,我想显示一个简单的 DisplayAlert 消息,如 here 所示。我正在尝试使用 MVVM 实现它,但很难绑定警报所需的等待。我知道如果有帮助,最大长度将始终为 3。

Xaml:

<Entry Text = "{Binding BoundText}"/>

视图模型:

string _boundText;
public string BoundText
{
   get => _boundText;
   set
   {
       if(value.Length > 3)
       {
          await DisplayAlert("Alert", "You have been alerted", "OK");
       }
       else
       {
          ...
       }
   }
}

我得到的错误是 await 运算符需要在 async 方法中,但是当我添加它时,我得到一个错误,即修饰符 async 对构造函数无效。关于如何实现这一点的任何想法?

【问题讨论】:

    标签: c# xamarin mvvm async-await binding


    【解决方案1】:

    我们不能将异步方法放入Setter 方法中。

    并且不建议将DisplayAlert放到viewmodel中,因为方法属于page,会破坏mvvm模式。

    这里有两种解决方法

    1. Setter方法中发送MessagingCenter,在页面中做一些事情。

      
           //viewmodel
           set
               {
                   if (value.Length > 3)
                   {
                       MessagingCenter.Send<object>(this, "Hi");
                   }
               ...
      
      
           //page
           public Page1()
           {
      
               InitializeComponent();
               this.BindingContext = model;
      
               MessagingCenter.Subscribe<object>(this, "Hi", async (obj) =>
               {
                   await DisplayAlert("Alert", "You have been alerted", "OK");
               });
           }
      
    2. 在Entry的TextChanged处理。

        <Entry Text = "{Binding BoundText}" TextChanged="Entry_TextChanged"/>
      
      
          private async void Entry_TextChanged(object sender, TextChangedEventArgs e)
          {
              if(e.NewTextValue.Length > 3)
              {
                  await DisplayAlert("Alert", "You have been alerted", "OK");
              }
          }
      

    【讨论】:

    • 是的,这就是为什么它只能是一种解决方法而不是解决方案,建议使用第二种方法。
    • 谢谢,我正在按照建议使用 TextChanged。将解决如何将条目的MaxLength设置为3并仍然显示消息的逻辑:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-07
    • 2017-12-15
    相关资源
    最近更新 更多