Issue
I have an entry which is set to max length of 3. When the user tries to input 4 characters I want to display a simple DisplayAlert message as shown here. I am trying to implement it with MVVM but having hard time with the binding of the await needed for the alert. I know that the max length will always be 3 if that helps.
Xaml:
<Entry Text = "{Binding BoundText}"/>
ViewModel:
string _boundText;
public string BoundText
{
get => _boundText;
set
{
if(value.Length > 3)
{
await DisplayAlert("Alert", "You have been alerted", "OK");
}
else
{
...
}
}
}
The error I am getting is that the await operator needs to be in an async method, but when I add it I get an error that the modifier async is not valid for the constructor. Any ideas on how to implement this?
Solution
We can't place an async method into Setter method .
And it is not recommended to place DisplayAlert into viewmodel , cause the method belongs to page , it breaks mvvm pattern .
Here are two workarounds .
Send
MessagingCenterinSettermethod , and do something in page .//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"); }); }Handle it in
TextChangedof Entry .<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"); } }
Answered By - ColeX - MSFT
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.