2

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

从 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 设置为数组。

4

2 回答 2

3

The format of the JSON used in the binding expression is a Dictionary of named MvxJsonBindingDescriptions

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

This is used with:

  • the dictionary Key name being the target (View) property for the binding.
  • the binding Path property being the source (DataContext) property for the binding - if Path is not specified then the whole DataContext itself is the binding source.

For Activity/View level axml the DataContext is the ViewModel - but for sub-View axml then the DataContext will normally be a child object of the ViewModel - e.g. inside a ListView the DataContext might be an item inside a List or ObservableCollection owned by the ViewModel.


To specify multiple bindings you can use JSON like:

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

For your particular example this might be:

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

where your ViewModel is something like:

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

     public bool HigherLower { get; set; }

     // more code here
}

and your converter is something like:

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

and where that converter is initialized during Setup - e.g. see how the properties of the Converters class are used in TwitterSearch


One sample that shows Multiple Bindings at work is BestSellers - see Click and Text bound in the list item https://github.com/slodge/MvvmCross/blob/master/Sample%20-%20BestSellers/BestSellers/BestSellers.Droid/Resources/Layout/ListItem_Category.axml

于 2012-05-21T18:08:33.933 回答
1

Path':'HigherLower你必须这样做:

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

请注意:

bind="{ 'Text':{xx}, 'Other':{yy} }"
于 2012-05-21T16:22:33.153 回答