MVVMCross for android - how to do binding in code?

前端 未结 1 784
别那么骄傲
别那么骄傲 2020-12-09 21:28

I want to use MVVMCross, however for my android application I also want to use other libraries (sliding menu and action bar) which require me to inherit my activity classes

1条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 21:58

    Yes - you can use fluent bindings in Android if you want to.

    Exactly the same code should work.

    You'll need to get references to the ui controls using FindViewById(), then you can bind them.

    For example, in TipCalc you can add identified controls like:

    
    

    and then implement binding using:

    protected override void OnViewModelSet()
    {
        SetContentView(Resource.Layout.View_Tip);
    
        var edit = this.FindViewById(Resource.Id.FluentEdit);
    
        var set = this.CreateBindingSet();
        set.Bind(edit).To(vm => vm.SubTotal);
        set.Apply();
    
        // for non-default properties use 'For':
        // set.Bind(edit).For(ed => ed.Text).To(vm => vm.SubTotal);
    
        // you can also use:
        //   .WithConversion("converter", "optional parameter")
        //   .OneTime(), .OneWay() or .TwoWay()
    }
    
    

    Additionally, you can convert any FooActivity into a data-binding MvxFooActivity by:

    • inheriting from FooActivity to provide events from lifetime events in an EventSourceFooActivity
    • inheriting from EventSourceFooActivity to provide a datacontext in an MvxFooActivity
    • you can then write your code inside activities inheriting from MvxFooActivity

    To see, the code required, see:

    • https://github.com/slodge/MvvmCross/blob/v3/Cirrious/Cirrious.MvvmCross.Droid.Fragging/MvxEventSourceFragmentActivity.cs
    • https://github.com/slodge/MvvmCross/blob/v3/Cirrious/Cirrious.MvvmCross.Droid.Fragging/MvxFragmentActivity.cs

    You'll see the same code in all the mvx adapted Activities - MvxActivity, MvxTabActivity, ... There is a little cut-and-paste here, but as much code as possible is place in shared extension methods.

    In previous versions, people have used this technique to bind monogame and google ads activities - eg see Insert a Monogame view inside MvvmCross monodroid Activity

    0 讨论(0)
提交回复
热议问题