MVVMCross绑定到badgevalue

时间:2014-12-05 09:17:17

标签: xamarin mvvmcross

我正在尝试绑定到TabBarItem的徽章值,如下所示:

var set = this.CreateBindingSet<MyView, MyViewModel>();
set.Bind(ViewControllers[0].TabBarItem.BadgeValue).To(vm => vm.MyNumber);
set.Apply();

但是我收到以下错误:

MvxBind: Error:   6.30 Empty binding target passed to MvxTargetBindingFactoryRegistry

但是,如果我像这样直接设置值,则会出现徽章:

ViewControllers[0].TabBarItem.BadgeValue = ((MyViewModel)ViewModel).MyNumber;

为什么绑定不起作用? 谢谢!

2 个答案:

答案 0 :(得分:2)

这不起作用,因为如果您要绑定的内容已经作为有效的绑定目标存在,则需要设置自己的绑定扩展。

看看here Stuart为Android回答类似的问题。

答案 1 :(得分:1)

创建自定义绑定:

public class TabBadgeBinding : MvxTargetBinding
{
    public const string TargetPropertyName = nameof(TabBadgeBinding);

    private readonly UIViewController _viewController;

    public TabBadgeBinding(UIViewController viewController) : base(viewController)
    {
        _viewController = viewController;
    }

    public override Type TargetType => typeof(UIViewController);

    public override MvxBindingMode DefaultMode => MvxBindingMode.OneWay;

    public override void SetValue(object value)
    {
        if (value is string badgeValue)
        {
            _viewController.TabBarItem.BadgeValue = badgeValue;
        }
    }
}

Setup.cs中注册绑定:

    protected override void FillTargetFactories(IMvxTargetBindingFactoryRegistry registry)
    {
        base.FillTargetFactories(registry);
        registry.RegisterFactory(new MvxCustomBindingFactory<UIViewController>(TabBadgeBinding.TargetPropertyName, (controller) => new TabBadgeBinding(controller)));
    }

在您的VC中使用绑定:

    set.Bind(ParentViewController).For(TabBadgeBinding.TargetPropertyName).To(vm => vm.UnreadNotificationsCount);