Search code examples
xamarinmvvmcross

How do I bind a UILabel with MvvmCross


I am writing a small sample app with Xamarin and MvvmCross 6.4.2. I completed the Xamarin.Android version and am now starting the Xamarin.iOS version. I created a view controller for the first screen:

[Register("SignInViewController")]
public class SignInViewController : MvxViewController<SignInViewModel>
{
    public SignInViewController() : base(nameof(SignInViewController), null)
    {

    }

    public SignInViewController(IntPtr handle) : base(handle)
    {
    }

    public override void ViewDidLoad()
    {
        // Why does it crash when I call base.ViewDidLoad() ?
        //base.ViewDidLoad();

        NavigationController.NavigationBar.BarTintColor = UIColor.Blue;

        var label = new UILabel();
        label.Text = "test";
        label.BackgroundColor = UIColor.Red;
        label.Frame = new CoreGraphics.CGRect(30, 100, 100, 100);

        View.Add(label);

        // This does not seem to work. If I remove it, label.Text will be "test"
        var set = this.CreateBindingSet<SignInViewController, SignInViewModel>();
        set.Bind(label).For("Text").To(vm => vm.Username);
        set.Apply();
    }
}

I put a test label just to get started and make sure everything works. I'm expecting the label to have the text "username test" since I hard coded it, but it's blank when I run the app. Also, it crashes if I try to call base.ViewDidLoad() with null reference exception, which it shouldn't so I think I am missing something important.

Note: I don't want to use MvvmCross 7 because it's still under development.


Solution

  • Call this.Request = MvxViewModelRequest<SignInViewModel>.GetDefaultRequest(); for you fisrt view :

       public override void ViewDidLoad()
        {
            // Why does it crash when I call base.ViewDidLoad() ?
            this.Request = MvxViewModelRequest<SignInViewModel>.GetDefaultRequest();
            base.ViewDidLoad();
    
            NavigationController.NavigationBar.BarTintColor = UIColor.Blue;
    
            var label = new UILabel();
            label.Text = "test";
            label.BackgroundColor = UIColor.Red;
            label.Frame = new CoreGraphics.CGRect(30, 100, 100, 100);
    
            View.Add(label);
    
            // This does not seem to work. If I remove it, label.Text will be "test"
            var set = this.CreateBindingSet<SignInViewController, SignInViewModel>();
            set.Bind(label).For("Text").To(vm => vm.Username);
            set.Apply();
        }
    

    Refer: how-to-call-mvxdialogviewcontroller-as-a-popover)