我在iOS中有一个需要以两种模式显示的视图,一种在导航标题中有一个关闭按钮,另一种没有关闭按钮。我在viewmodel中添加了一个bool来处理这个问题。但是,UIBarButtonItem在我的viewmodel中没有绑定到此bool的Hidden属性。有关如何解决此问题的任何建议?注意:我不需要在运行时更改此关闭按钮的可见性。这只是在显示视图之前我需要的初始只读设置。
答案 0 :(得分:1)
对于静态设置,您只需尝试检查ViewDidLoad代码中的viewmodel属性。
有关创建自定义绑定的信息,请参阅https://speakerdeck.com/cirrious/custom-bindings-in-mvvmcross
答案 1 :(得分:1)
我遇到了同样的问题,但需要动态更改。通过禁用按钮并将色调颜色设置为清除,我能够模拟可见性。
创建自定义TargetBinding:
/// <summary>
/// Hides a UIBarButtonItem by disabling and setting the TintColor to Clear
/// </summary>
public class UIBarButtonItemVisibilityTargetBinding : MvxConvertingTargetBinding
{
protected UIBarButtonItem Button => base.Target as UIBarButtonItem;
private readonly UIColor _tintColor;
public UIBarButtonItemVisibilityTargetBinding(UIBarButtonItem button) : base(button)
{
this._tintColor = button.TintColor;
if (button == null) {
MvxBindingTrace.Trace(MvxTraceLevel.Error, "Error - UIBarButtonItem is null in UIBarButtonItemVisibilityTargetBinding");
}
}
public override MvxBindingMode DefaultMode => MvxBindingMode.OneWay;
public override System.Type TargetType => typeof(bool);
protected override void SetValueImpl(object target, object value)
{
var button = (UIBarButtonItem) target;
var enabled = (bool) value;
button.Enabled = enabled;
button.TintColor = enabled ? _tintColor : UIColor.Clear;
}
}
在设置文件中注册TargetBinding:
protected override void FillTargetFactories (MvvmCross.Binding.Bindings.Target.Construction.IMvxTargetBindingFactoryRegistry registry)
{
base.FillTargetFactories (registry);
registry.RegisterCustomBindingFactory<UIBarButtonItem> ("Visibility", button => new UIBarButtonItemVisibilityTargetBinding (button));
}
使用自定义绑定绑定到视图控制器中的按钮:
set.Bind (btnBarItem).For("Visibility").To (vm => vm.ShowButton);