MvvmCross watch property from View

家住魔仙堡 提交于 2019-12-12 04:38:26

问题


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.


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

    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.



来源:https://stackoverflow.com/questions/20849112/mvvmcross-watch-property-from-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!