I am using
MvxBindableListView
to bind a List<>
of data objects to a ListView
. The layout I am using for the rows has several TextView
s. I am successfully binding the Text
property for each of these to a property in my data object, but I have found that I cannot bind to TextColor
as that property does not exist in Mono For Android TextView
s; instead you have use the SetTextColor()
method. So how can I bind a data object property to a method?! Below is the code I tried to use:
The answer
There's an example of adding a custom 2-way binding for "IsFavorite" in the Conference sample - see:
- the binding - https://github.com/slodge/MvvmCross/blob/master/Sample%20-%20CirriousConference/Cirrious.Conference.UI.Droid/Bindings/FavoritesButtonBinding.cs
- the binding setup in
FillTargetFactories
inhttps://github.com/slodge/MvvmCross/blob/master/Sample%20-%20CirriousConference/Cirrious.Conference.UI.Droid/Setup.cs
This example is explained a bit further in: MVVMCross Bindings in Android
For a one-way "source-to-target" custom binding, the code should be a bit simpler - you only need to handle the
SetValue
- and don't need to invoke FireValueChanged
in any event handling code.
For textColor, I'd imagine the binding would look a bit like:
public class MyCustomBinding
: MvxBaseAndroidTargetBinding
{
private readonly TextView _textView;
public MyCustomBinding(TextView textView)
{
_textView = textView;
}
public override void SetValue(object value)
{
var colorValue = (Color)value;
_textView.SetTextColor(colorValue);
}
public override Type TargetType
{
get { return typeof(Color); }
}
public override MvxBindingMode DefaultMode
{
get { return MvxBindingMode.OneWay; }
}
}
and would be setup with:
protected override void FillTargetFactories(MvvmCross.Binding.Interfaces.Bindings.Target.Construction.IMvxTargetBindingFactoryRegistry registry)
{
base.FillTargetFactories(registry);
registry.RegisterFactory(new MvxCustomBindingFactory("TextColor", (textView) => new MyCustomBinding(textView)));
}
No comments:
Post a Comment