Jaime Santos
Jaime Santos

Reputation: 557

how to use "text.changed" control from code using MVVM (in Xamarin.Forms)

I am trying to make a text box change its color when an entry's text meets some requisites, calling a function form my ViewModel every time a new character is added to the text, and I am using FreshMVVM, meaning that I cant directly use the control "text.changed" since bindings can't be used for controls (if I am not mistaken).

Looking for answers I have found the nugget package "Behaviors.Forms", which would let me do it. The problem is that I am not using an entry perse, but a custom view that works as an entry, and the previously mentioned package doesn't let me use entry.behaviors for my custom entry.

Most of the posts and discussions about this matter were old (from 2016 or 2017), so is there any way to bind controls to your ViewModel now?, and if not, is there any way to do the specific task that I have explained?

Thank you all for your time, hope you have a good day.

Upvotes: 0

Views: 724

Answers (2)

user9098171
user9098171

Reputation:

You can use Behaviors, They are used to enhance the functionality of a control. this link : https://xamarinhelp.com/xamarin-forms-triggers-behaviors-effects/ : discusses a similar use case u are looking for.

your code should be something like this,

public class DoSomethingOnTextChanged: Behavior<>
{

    protected override void OnAttachedTo(Entry bindable)
    {
        bindable.TextChanged += bindable_TextChanged;
    }

    private void bindable_TextChanged(object sender, TextChangedEventArgs e)
    {
       var newTextValue = (string)e.NewTextValue;
       //Do Some Logic
    }

    protected override void OnDetachingFrom(Entry bindable)
    {
        bindable.TextChanged -= bindable_TextChanged;
    }
}

Upvotes: 2

Chetan Rawat
Chetan Rawat

Reputation: 588

you can try Triggers like below example

<Entry Placeholder="Insert your name"
        BackgroundColor="LightCoral" >
      <Entry.Triggers>
          <Trigger TargetType="Entry"
                   Property="Text" 
                   Value="Charlin">
              <Setter Property="BackgroundColor" Value="LightBlue" />
              <Setter Property="Scale" Value="1.1" />
          </Trigger>
      </Entry.Triggers>
 </Entry>

Upvotes: 1

Related Questions