pixel
pixel

Reputation: 10587

xamarin.forms - how to have two views' event handlers call same code

I have two views, say one for tablet, one for phone. They have both an Entry field and they use same functionality, layout is the only difference.

I want to remove code duplication and since both Entry fields have identical logic inside OnTextChanged, i would like to move it to another method that both these Entry events can call.

How to make both Entrys OnTextChanged event call same centralized method?

What would be best way to do that in Xamarin Forms?

Upvotes: 0

Views: 192

Answers (1)

Tom
Tom

Reputation: 1749

As mentioned by @SLaks , it sounds like your best approach is to us MVVM. There is a lot of information about MVVM online.

The super simple approach for implementing one method into two events is below:

// Handler for the first Entry
private void Entry1_TextChanged(object s, TextChangedEventArgs e)
{
    HandleTheTextChanged(e.NewText);
}

// Handler for the second Entry
private void Entry2_TextChanged(object s, TextChangedEventArgs e)
{
    HandleTheTextChanged(e.NewText);
}

// Common code
private void HandleTheTextChanged(string newText)
{
    // Do your stuff
}

Upvotes: 1

Related Questions