Ryan Langton
Ryan Langton

Reputation: 6160

MvvmCross watch property from View

I want my android View to trigger a method to create a Toast message whenever a certain property changes in the ViewModel. All the examples I'm finding are binding within the XML. This seems so much simpler yet I can't find any examples.

Upvotes: 0

Views: 1174

Answers (1)

Ross Dargan
Ross Dargan

Reputation: 6021

You can do this by creating a weak subscription to the viewmodel inside the view and showing the toast when the property changes as follows:-

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Android.OS.Bundle savedInstanceState)
    {
        IMvxNotifyPropertyChanged viewModel = ViewModel as IMvxNotifyPropertyChanged;
        viewModel.WeakSubscribe(PropertyChanged);
        return base.OnCreateView(inflater, container, savedInstanceState);            
    }

    private void PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        if (e.PropertyName == "the property")
        {
            //Display toast
        }
    }

I would be tempted however to instead allow your viewmodel to control this behaviour (are you going to write the above code for every implementation?)

Simply add the UserInteraction plugin via nuget and do the following:

private readonly IUserInteraction _userInteraction;

public FirstViewModel(IUserInteraction userInteraction)
{
    _userInteraction = userInteraction;
}

private string _hello = "Hello MvvmCross";
public string Hello
{ 
    get { return _hello; }
    set
    {
        _hello = value;
        RaisePropertyChanged(() => Hello);
        _userInteraction.Alert("Property Changed!");
    }
}

This doesn't display a toast, it displays a message box, but hopefully it will give you enough to go off.

Finally you could use a messenger plugin to send a "Show toast" message.

Upvotes: 3

Related Questions