How to bind NSAttributeString (or NSMutableAttribu

2019-07-21 03:37发布

问题:

I want to bind an attributed string to a UILabel using MVVMCross. To bind a regular string I would just do:

set.Bind(MyLabel).To(vm => vm.MyString);

But I need a string where part of the text will use one color and one font size and another part will use a different color and a different font size. If this was static, no problem, I'd add a label in interface builder and set it "attributed" and then set whatever font options I want on which ever parts of the string I need.

So I thought with Mvvmcross, I'd probably need a converter to turn my source string into an attributed string, so I tried creating a converter from MvxValueConverter<string,NSMutableAttributedString> that just does this in its Convert method:

return new NSMutableAttributedString(value);

Eventually I'll actually add some different attributes. Unfortunately, this doesn't work. If I set my binding like this:

set.Bind(MyLabel).To(vm => vm.MyString).WithConversion("MyConverter");

It appears that MvvmCross just does a .ToString on the attributed string and it displays as:

Some Text {}

Note the {} aren't part of the original string.

Is there a way to bind an attributed string in MVVMCross?

回答1:

If you call

 set.Bind(MyLabel).To(vm => vm.MyString);

then you are binding the default property of your UILabel which is the string property Text.

You need to bind the AttributedText instead. Try adding something like:

    .For(l => l.AttributedText)

There are some questions on here about using AttributedText - eg Underline text in UILabel in monotouch (porting ObjC code)

For more on mvx data-binding see https://github.com/slodge/MvvmCross/wiki/Databinding