Search code examples
xamarinmvvmxamarin.androidmvvmcross

Xamarin Android: Dynamic update UI based on Viewmodel


In my android project, the webview url is dynamic. I am using mvvmcros binding on view side but its not being dynamic. If the url content on view model is changing its not being updated on view. Can anyone help me out?

View

public string WebContentUrll { get; set; }    
protected override void OnCreate(Android.OS.Bundle bundle)    
{        
  var bindingSet = this.CreateBindingSet<view, ViewModel>(); 
  bindingSet.Bind(this).For(v => v.WebContentUrll).To(vm => vm.WebContentUrl).TwoWay();    
} 

ViewModel

   private string webContentUrl;      
    public string WebContentUrl      
    {       
     get       
     {        
       return webContentUrl;       
     }       
     set       
     {        
      webContentUrl = value;        
      RaisePropertyChanged(() => webContentUrl);       
     }      
    }
  public void Init()
  {
     webContentUrl = "https://.."'
  }

The value of web content url in the view model changes after the page is loaded but the android view is not able to get the new updated url.

Can anyone please advise. Thank you.

Update

The web view is opened on a button click and the url is updated after the page loads and before the button is clicked


Solution

  • From you description in the opening post. In your Activity you have defined a property WebContentUrll. You want to bind this and update something when it is changed.

    The definition of WebContentUrll is:

    public string WebContentUrll { get; set; }
    

    This is not wrong and you should see the value reflected in WebContentUrll when it changes from the ViewModel through your binding. However, there is no code updating any visual states, views or anything based on that property.

    If you have a WebView you want to change content for, you could modify your property to something like:

    private string _webContentUrll;
    public string WebContentUrll
    {
        get => _webContentUrll;
        set 
        {
            _webContentUrll = value;
            _webView.LoadUrl(_webContentUrll);
        }
     }
    

    Given that _webView is your instance of a WebView.