Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lukepothier/40342e7ecc48d977d9bcdd1870ab7aaa to your computer and use it in GitHub Desktop.
Save lukepothier/40342e7ecc48d977d9bcdd1870ab7aaa to your computer and use it in GitHub Desktop.
MvxConvertingTargetBinding for Android navigation views which have IMenu members
using Android.Support.Design.Widget;
using MvvmCross.Binding;
using MvvmCross.Binding.Bindings.Target;
using System;
using System.Windows.Input;
namespace YourNamespace
{
public class NavigationItemSelectedTargetBinding : MvxConvertingTargetBinding
{
ICommand _command;
BottomNavigationView _target;
public NavigationItemSelectedTargetBinding(BottomNavigationView target)
: base(target)
{
}
public override Type TargetType => typeof(BottomNavigationView);
public override MvxBindingMode DefaultMode => MvxBindingMode.OneWay;
protected override void SetValueImpl(object target, object value)
{
_target = target as BottomNavigationView;
_command = value as ICommand;
_target.NavigationItemSelected += Target_NavigationItemSelected;
}
// TODO :: Don't use the title as the command parameter -- it is subject to locale issues
void Target_NavigationItemSelected(object sender, BottomNavigationView.NavigationItemSelectedEventArgs e)
=> _command.Execute(e.Item.TitleFormatted.ToString());
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
_target.NavigationItemSelected -= Target_NavigationItemSelected;
}
}
}
@lukepothier
Copy link
Author

This is an example for BottomNavigationView, but a similar TargetBinding should be largely the same for other Android NavigationViews. Implementation is the same as ever.

Binding statement:

yourBindingSet.Bind(YourNavigationView).For("YourBindingKey").To(vm => vm.YourCommand);

Command + navigation helpers:

IMvxCommand _yourCommand;
public IMvxCommand YourCommand =>
        _yourCommand ?? (_yourCommand = new MvxCommand<string>(Navigate));

void Navigate(string navigationKey)
{
    if (navigationKey.Equals("exampleOne", StringComparison.OrdinalIgnoreCase))
        GoToExampleOne();

    if (navigationKey.Equals("exampleTwo", StringComparison.OrdinalIgnoreCase))
        GoToExampleTwo();
}

void GoToExampleOne() => ShowViewModel<ExampleOneViewModel>();

void GoToExampleTwo() => ShowViewModel<ExampleTwoViewModel>();

Setup.cs:

registry.RegisterCustomBindingFactory<BottomNavigationView>("YourBindingKey", view => new BottomNavigationItemSelectedTargetBinding(view));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment