Reputation: 141
I am creating a simple calculator in MAUI as this is my first time using MAUI.
So, I have an Entry to display the entered numbers, operations and the answer. There are two ways to change the text in the Entry: The keyboard and the buttons (C#) given in the UI. I want to detect if the text in the Entry is changed by keyboard input or by using the UI buttons (C#).
I am using .NET 8 targeting Windows and Android.
I tried using the TextChanged event but it runs every time the text changes (it doesn't differentiate between Keyboard input and C#). Then I tried to use the KeyPress event, but I don't know where and how to use it, or does it even work in MAUI.
Why do I need to check? - I want that only numbers, decimal point and the mathematical operations should be in the Entry. So, if the input is coming from the UI buttons, don't check anything and just append the text. And if the input is coming from the keyboard then check the input and then decide weather to append or not.
Upvotes: 1
Views: 489
Reputation: 13853
Yes, we can use event TextChanged
to validate the input just as Sam said.
InputView has defines a TextChanged
event, which is raised when the text in the Entry changes. The TextChangedEventArgs
object that accompanies the TextChanged
event has NewTextValue
and OldTextValue
properties, which specify the new and old text, respectively.
void OnEntryTextChanged(object sender, TextChangedEventArgs e)
{
string oldText = e.OldTextValue;
string newText = e.NewTextValue;
string myText = entry.Text;
}
For more information, you can check document: Entry.
Upvotes: 0
Reputation: 31
I'm not sure how efficient this might be, but what if you use a binding for it?
Create two variables:
private string _calculatorText { get; set; }
public string CalculatorText
{
get => _calculatorText;
set
{
_calculatorText = value;
bool usingKeyboard = true;
SomeMethod(usingKeyboard);
OnPropertyChanged(nameof(CalculatorText));
}
}
And in your XAML entry, bind the text like this:
xml
<Entry Text="{Binding CalculatorText}" />
This way, when you detect the change through CalculatorText, you know it was done via the keyboard. In contrast, if you handle _calculatorText directly, it was done through C# code.
Upvotes: 0