Skip to content Skip to sidebar Skip to footer

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.

Solution 1:

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:-

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

    privatevoidPropertyChanged(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:

privatereadonly IUserInteraction _userInteraction;

publicFirstViewModel(IUserInteraction userInteraction)
{
    _userInteraction = userInteraction;
}

privatestring _hello = "Hello MvvmCross";
publicstring 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.

Post a Comment for "Mvvmcross Watch Property From View"