Search code examples
xamarin.androidmvvmcrossxamarin.forms

MvvmCross Bind command to <include> toolbar


I want to bind commands to my toolbars' items. Is it possible? I have tried this but it's still doesn't work https://stackoverflow.com/a/21936542/6160208

Toolbar.axml

<Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:local="http://schemas.android.com/apk/res-auto"
            android:background="@android:color/holo_blue_light"
            android:layout_width="match_parent"
            android:layout_height="85dp">

        <ImageButton
            android:src="@drawable/search"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/searchImageButton"
            android:layout_marginLeft="290dp"
            local:MvxBind="Click DoSearchCommand"
            android:background="@android:color/holo_blue_light" />

MainView.axml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:local="http://schemas.android.com/apk/res-auto"
          android:orientation="vertical"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent">
          <include
              layout="@layout/toolbar" />
</LinearLayout>

MainViewModel.cs

    private MvxCommand _searchCommand;
    public System.Windows.Input.ICommand SearchCommand
    {
        get
        {
            _searchCommand = _searchCommand ?? new MvxCommand(DoSearchCommand);
            return _searchCommand;
        }
    }
    private void DoSearchCommand()
    {
        ShowViewModel<SearchViewModel>();
    }

Solution

  • You bind to DoSearchCommand but that is the method. You should bind to SearchCommand

    local:MvxBind="Click SearchCommand"
    

    As improvement you could use a IMvxCommand instead of a ICommand too, and add the ShowViewModel as lambda.

    private MvxCommand _searchCommand;
        public IMvxCommand SearchCommand
        {
            get
            {
                _searchCommand = _searchCommand ?? new MvxCommand(() => ShowViewModel<SearchViewModel>());
                return _searchCommand;
            }
        }