【问题标题】:MvvmCross Bind to UIButton.TitleLabel.TextMvvmCross 绑定到 UIButton.TitleLabel.Text
【发布时间】:2013-06-24 08:00:11
【问题描述】:

我正在尝试使用 MvvmCross for Xamarin.iOS 绑定到 UIButton 上 TitleLabel 的文本属性。这是我到目前为止所拥有的......

set.Bind(btnFoo).For(btn => btn.TitleLabel.Text).To(vm => vm.BtnFooText);

我也试过了……

set.Bind(btnFoo.TitleLabel).For(lbl => lbl.Text).To(vm => vm.BtnFooText);

这两种方法似乎都不起作用。感谢您的帮助!

【问题讨论】:

标签: c# binding xamarin.ios xamarin mvvmcross


【解决方案1】:

对于调试问题,启用跟踪可能会有所帮助 - 请参阅 MvvmCross Mvx.Trace usage

为了在子控件的固定预先存在的子控件上绑定属性,那么这种方法应该可以工作:

set.Bind(sub.subSub).For(c => c.PropertyName).To(vm => vm.Foo);

但是,如果子控件在任何时候更改其子控件,这将无法继续工作。对于这些情况,请查看自定义绑定 - 例如,请参阅 http://slodge.blogspot.co.uk/2013/06/n28-custom-bindings-n1-days-of-mvvmcross.html

对于一个 uibutton 的具体情况,你可以绑定它的“Title” - 见Fluent Bindings and UIButton titles

【讨论】:

  • 太棒了!我当然感谢您的帮助!我还需要更新 UI 上的图像。看起来自定义绑定是我所有问题的答案。感谢您的反馈和耐心。我要去深入了解自定义绑定池。
  • 按钮上的标签可能很棘手 - 如果您发现单击按钮会导致绑定标签重置回 XIB 中的设置,请尝试以下语法:set.Bind(myButton).For("Title").To(vm => vm.PropertyToBindTo); 我的理解是它调用专门为 UIButton.Title 场景编写的绑定。
【解决方案2】:

对我来说 UIButton 绑定到 TitleLabel 不起作用。我想出了自定义绑定,它工作得很好而且很灵活:

应用绑定:

  set.Bind(FinishedButton).For(UIButtonTextBinding.Property).To(v => v.FinishActionText);

绑定代码:

public class UIButtonTextBinding : MvxTargetBinding
{
    public const string Property = "ButtonText";

    protected UIButton View
    {
        get { return Target as UIButton; }
    }

    public UIButtonTextBinding(UIButton target)
        : base(target)
    {
    }

    public override void SetValue(object value)
    {
        var view = View;
        if (view == null)
            return; 

        var stringValue = value as string;
        view.SetTitle(stringValue, UIControlState.Normal);
    }

    public override Type TargetType
    {
        get { return typeof(string); }
    }

    public override MvxBindingMode DefaultMode
    {
        get { return MvxBindingMode.OneWay; }
    }
}

【讨论】:

    【解决方案3】:

    最简单的方法绑定 UIButton 标题:

    set.Bind(btnFoo).For("Title").To(vm => vm.BtnFooText);
    

    【讨论】:

    • 我认为这是最好的答案,因为它使用了开箱即用的 MvvmCross 提供的自定义绑定器,并且完全符合 OP 试图实现的目的。
    【解决方案4】:

    你可以使用:

    set.Bind(btnFoo).For(btn => btn.BindTitle()).To(vm => vm.BtnFooText);
    

    添加以下使用:

    using MvvmCross.Binding.iOS;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-18
      • 2013-10-17
      相关资源
      最近更新 更多