【问题标题】:How do I bind TextStyle using MVVMCross?如何使用 MVVMCross 绑定 TextStyle?
【发布时间】:2015-08-12 14:51:35
【问题描述】:

我想在 Android 中使用 If-Else ValueCombiner 绑定 TextView 的 TextStyle 属性。我尝试了以下方法,但无法创建绑定:

<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp" android:layout_gravity="center_vertical" android:layout_row="0" android:layout_column="1" android:textSize="28dp" android:gravity="left" android:text="MyText" local:MvxBind="TextStyle If(ShowBold, 'bold', 'normal')" />

我用 Text 属性测试了类似的绑定,它工作正常,所以我猜它正在寻找字符串以外的东西?

【问题讨论】:

  • 您很可能必须使用 ValueConverter,因为您无法通过绑定中的字符串传入 Android 类型。
  • 你有没有找到办法做到这一点?
  • @AaronBratcher 我刚刚做到了,请在下方查看。

标签: android xamarin xamarin.android mvvmcross


【解决方案1】:

有点晚了,但我有同样的要求,现在就做了。

在您的设置文件中添加以下内容(我有两个自定义绑定属性,StyleSummary):

protected override void FillTargetFactories(IMvxTargetBindingFactoryRegistry registry)
{
    base.FillTargetFactories(registry);

    registry.RegisterFactory(new MvxCustomBindingFactory<TextView>("Style", textView => new StyleTextViewBinding(textView)));
    registry.RegisterFactory(new MvxCustomBindingFactory<TextView>("Summary", textView => new SummaryTextViewBinding(textView)));
}

在我的 TextView 中(我的自定义绑定显然是 StyleTextTextColor 是转换器):

<TextView
    style="@style/TeamDifficulty"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:text="@string/dummy_title"
    local:MvxBind="Text TeamDifficultyText(RowItem.DifficultyEnumCaptain1Int); TextColor TeamDifficultyTextColor(RowItem.DifficultyEnumCaptain1); Style RowItem.DifficultyEnumCaptain1;" />

以及实际的代码(基本上它会检查我的文本是否为空,如果是,它将加粗,因为我的转换器会在之后为其添加一个值):

public class StyleTextViewBinding : MvxAndroidTargetBinding
{
    readonly TextView _textView;

    public StyleTextViewBinding(TextView textView) : base(textView)
    {
        _textView = textView;
    }

    #region implemented abstract members of MvxConvertingTargetBinding
    protected override void SetValueImpl(object target, object value)
    {
        _textView.SetTypeface(_textView.Typeface, Android.Graphics.TypefaceStyle.Bold);            

        if (value != null && Convert.ToBoolean(value))            
            _textView.SetTypeface(_textView.Typeface, Android.Graphics.TypefaceStyle.Normal);                
    }
    #endregion

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

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

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    这是 Stuart 帮助其他人使用的文本颜色示例。 In MvvmCross how do I do custom bind properties

    使用它,您应该能够对文本样式进行逆向工程。

    【讨论】:

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