如果你想实现“自定义绑定”,那么有 3 种方法可以做到:
- 实现并注册真正的自定义绑定
- 实现一个自定义控件,该控件公开一个要绑定的自定义属性
- 使用公开自定义属性的中间对象
https://stackoverflow.com/a/19221385/373321 中的答案显示了真正的自定义绑定。
在http://mvvmcross.blogspot.com 的 N=18 中讨论了从标准视图继承的自定义控件 - 这里的示例可能是:
public class DoneEditText : EditText, TextView.IOnEditorActionListener
{
public DoneEditText(Context context) : base(context)
{
Init();
}
public DoneEditText(Context context, IAttributeSet attrs) : base(context, attrs)
{
Init();
}
public DoneEditText(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle)
{
Init();
}
private void Init()
{
this.SetOnEditorActionListener(this);
}
public ICommand DoneAction { get;set; ]
#region Implementation of IOnEditorActionListener
public bool OnEditorAction(TextView v, ImeAction actionId, KeyEvent e)
{
if (actionId == ImeAction.Done)
{
if (DoneAction != null)
DoneAction.Execute(v.Text);
return true;
}
return false;
}
#endregion
}
使用中间对象进行绑定将使用如下类:
public class DoneActionListener : Java.Lang.Object, TextView.IOnEditorActionListener
{
public ICommand DoneAction { get; set; }
public DoneActionListener(TextView v)
{
v.SetOnEditorActionListener(this);
}
#region Implementation of IOnEditorActionListener
public bool OnEditorAction(TextView v, ImeAction actionId, KeyEvent e)
{
if (actionId == ImeAction.Done)
{
if (DoneAction != null)
DoneAction.Execute(v.Text);
return true;
}
return false;
}
#endregion
}
这可以在OnCreate 中使用 Fluent Binding 处理,例如:
private DoneActionListener _listener;
public override OnCreate(Bundle b)
{
base.OnCreate(b);
SetContentView(Resource.Layout.MyLayoutId);
_listener = new DoneActionListener(FindViewById<EditText>(Resource.Id.MyEditId));
var set = this.CreateBindingSet<MyView, MyViewModel>();
set.Bind(_listener).For(v => v.DoneAction).To(vm => vm.TheDoneCommand);
set.Apply();
}