2014-12-19 40 views
3

我想在Android中使用If-Else ValueCombiner绑定TextView的TextStyle属性。我尝试以下,但它无法创建绑定:如何使用MVVMCross绑定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属性相似的结合,它工作得很好,所以我想这是寻找字符串以外的东西吗?

+2

您很可能不得不使用ValueConverter,因为您无法通过绑定中的字符串传递Android类型。 – Cheesebaron

+0

你有没有找到一种方法来做到这一点? –

+0

@AaronBratcher我刚刚做到了,请查看下面。 – PmanAce

回答

2

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

添加在您的安装文件如下(我有两个自定义绑定属性,风格摘要):

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(我的自定义绑定是风格明显,文本TEXTCOLOR是转换器):

<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; } 
    } 
} 

希望这有助于!