【问题标题】:TextView Compound Drawable MvvmCross BindingTextView 复合 Drawable MvvmCross 绑定
【发布时间】:2017-08-08 16:08:45
【问题描述】:

TextView 有一些DrawableXXX 属性,如DrawableStartDrawableEndDrawableTop 等,以在TextView 文本旁边显示Drawable。是否可以使用 MvvmCross 绑定此属性?我尝试在绑定中使用local:MvxBind="Drawablename 'check'",但它未能显示 MvxBind 错误:

无法为绑定 DrawableName 创建目标绑定以进行检查

如果此绑定未在 MvvmCross 中实现,那么我将如何自行执行此操作? N+28 使用的方法仍然是添加自定义绑定的推荐方法吗?

【问题讨论】:

  • N+28用于自定义绑定的方法对MvvmCross 4.x仍然有效。如果您使用的是 MvvmCross 5.x,那么您可以使用键入的 MvxAndroidTargetBinding 来代替。

标签: xamarin.android mvvmcross


【解决方案1】:

目前没有任何 MvvmCross 定义用于添加复合可绘制对象的目标绑定。但是,您可以轻松添加自己的。如果您使用的是 MvvmCross 5+,您可以利用新的类型化自定义绑定类。 注意,下例将drawable设置在左侧,但您可以选择任意方向(或多个)放置。

public class CompoundDrawablesDrawableNameBinding : MvxAndroidTargetBinding<TextView, string>
{
    public const string BindingIdentifier = "CompoundDrawableName";

    public CompoundDrawablesDrawableNameBinding(TextView target) : base(target)
    {
    }

    public override MvxBindingMode DefaultMode => MvxBindingMode.OneWay;

    protected override void SetValueImpl(TextView target, string value)
    {
        var resources = AndroidGlobals.ApplicationContext.Resources;
        var id = resources.GetIdentifier(value, "drawable", AndroidGlobals.ApplicationContext.PackageName);
        if (id == 0)
        {
            MvxBindingTrace.Trace(MvxTraceLevel.Warning,
                "Value '{0}' was not a known compound drawable name", value);
            return;
        }

        target.SetCompoundDrawablesWithIntrinsicBounds(
            left: id,
            top: 0,
            right: 0,
            bottom: 0);
    }
}

然后在你的Setup.cs注册

protected override void FillTargetFactories(IMvxTargetBindingFactoryRegistry registry)
{
    base.FillTargetFactories(registry);
    registry.RegisterCustomBindingFactory<TextView>(
        CompoundDrawablesDrawableNameBinding.BindingIdentifier,
        textView => new CompoundDrawablesDrawableNameBinding(textView));
}

然后在你的 XML 中你可以使用

local:MvxBind="CompoundDrawableName &lt;&lt;YOUR PROPERTY TO BIND TO&gt;&gt;"

【讨论】:

  • 如果您支持 API 17+,您也可以使用 SetCompoundDrawablesRelativeWithIntrinsicBounds,它适用于 starttopendbottom
  • 你能做一个 PR 来添加这个吗?
  • @Martijn00,我不确定如何将这一点推广到 Mvx 绑定,以便开发人员可以选择每个方向的一个或多个图像。本质上,我们需要一种方法来获取 1 - 4 个不同的图像并将它们应用于 4 个不同的可能方向。我在GitHub 上创建了一个问题以继续此转换。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-19
  • 1970-01-01
  • 2017-07-18
  • 2013-10-17
  • 2014-10-10
  • 1970-01-01
相关资源
最近更新 更多