如何在 Android 布局元素中绑定多个属性

2024-02-12

我正在使用 MvvmCross 将我的 ViewModel 数据绑定到 Android 视图布局。

从 SimpleBinding 示例中我可以看到,要将值绑定到属性,我这样做:

  <EditText
    android:hint="Subtotal"
    android:gravity="left"
    android:inputType="numberDecimal"
    android:maxLines="1"
    android:numeric="decimal"        
    local:MvxBind="{'Text':{'Path':'SubTotal','Converter':'Float'}}"
  />

因此 Text 绑定到 ViewModel 的 SubTotal 属性。但如何绑定多个属性呢?就我而言,我想将名为 HigherLower 的 ViewModel 属性绑定到布局元素的 TextColor 属性。我无法添加另一个 MvxBind,也无法将 MvxBind 设置为数组。


绑定表达式中使用的 JSON 格式是命名的字典MvxJsonBinding描述 https://github.com/slodge/MvvmCross/blob/master/Cirrious/Cirrious.MvvmCross.Binding/Binders/Json/MvxJsonBindingDescription.css

public class MvxJsonBindingDescription
{
    public string Path { get; set; }
    public string Converter { get; set; }
    public string ConverterParameter { get; set; }
    public string FallbackValue { get; set; }
    public MvxBindingMode Mode { get; set; }
}

这与以下内容一起使用:

  • 字典键名称是绑定的目标(视图)属性。
  • 绑定Path属性是绑定的源 (DataContext) 属性 - 如果Path未指定则整个 DataContext 本身就是绑定源。

对于 Activity/View 级别的 axml,DataContext 是 ViewModel - 但对于子视图 axml,DataContext 通常是 ViewModel 的子对象 - 例如在 ListView 中,DataContext 可能是 ViewModel 拥有的 List 或 ObservableCollection 中的一项。


要指定多个绑定,您可以使用 JSON,例如:

 {
      'TargetProperty1':{'Path':'SourceProperty1'},
      'TargetProperty2':{'Path':'SourceProperty2'}
 }

对于您的特定示例,这可能是:

local:MvxBind="
       {
          'Text':{'Path':'SubTotal','Converter':'Float'}, 
          'TextColor':{'Path':'HigherLower','Converter':'MyColorConverter'}
       }"

你的 ViewModel 是这样的:

public class MyViewModel : IMvxViewModel
{
     public float SubTotal { get; set; }

     public bool HigherLower { get; set; }

     // more code here
}

你的转换器是这样的:

public class MyColorConverter : MvxBaseColorConverter
{
    protected override MvxColor Convert(object value, object parameter, CultureInfo culture)
    {
        return ((bool)value) ? new MvxColor(255,0,0) : new MvxColor(0,255,0);
    }
}

以及该转换器在设置过程中初始化的位置 - 例如看看属性如何转换器 https://github.com/slodge/MvvmCross/blob/master/Sample%20-%20TwitterSearch/TwitterSearch.Core/Converters/Converters.cs类用于推特搜索 https://github.com/slodge/MvvmCross/blob/master/Sample%20-%20TwitterSearch/TwitterSearch.UI.Droid/Setup.cs


BestSellers 是显示多重绑定工作的一个示例 - 请参阅列表项中的单击和文本绑定https://github.com/slodge/MvvmCross/blob/master/Sample%20-%20BestSellers/BestSellers/BestSellers.Droid/Resources/Layout/ListItem_Category.axml https://github.com/slodge/MvvmCross/blob/master/Sample%20-%20BestSellers/BestSellers/BestSellers.Droid/Resources/Layout/ListItem_Category.axml

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Android 布局元素中绑定多个属性 的相关文章

随机推荐