MvxTableViewCell上的AttributedText

时间:2015-05-12 08:40:07

标签: c# ios uitableview xamarin.ios mvvmcross

我正在尝试在MvxTableViewCell的UILabel上设置下划线。

    [Register("KittenCell")]
    public class KittenCell : MvxTableViewCell
    {
        private UIImageView MainImage;
        private UILabel NameLabel;
        private UILabel PriceValueLabel;
        private UILabel PriceLabel;

        public static readonly NSString Key = new NSString ("KittenCell");
        private MvxImageViewLoader imageLoader;

        public KittenCell ()
        {
            CreateLayout ();
            InitializeBindings ();
        }

        public KittenCell(IntPtr handle)
            : base(handle) 
        {
            CreateLayout ();
            InitializeBindings ();
        }

        void CreateLayout ()
        {
            MainImage = new UIImageView (new RectangleF (0, 0, 160, 100));

            NameLabel = new UILabel (new RectangleF (168, 15, 144, 21));
            NameLabel.TextAlignment = UITextAlignment.Left;
            var attrs = new UIStringAttributes {
                UnderlineStyle = NSUnderlineStyle.Single
            };
            NameLabel.AttributedText =new NSAttributedString(NameLabel.Text,attrs);

            PriceLabel = new UILabel (new RectangleF (168, 59, 57, 21));
            PriceLabel.Text = "Price:";
            PriceLabel.TextAlignment = UITextAlignment.Left;
            PriceValueLabel = new UILabel (new RectangleF (228, 59, 84, 21));
            PriceValueLabel.TextAlignment = UITextAlignment.Left;
            PriceValueLabel.TextColor = UIColor.Blue;
            ContentView.AddSubviews (MainImage, NameLabel, PriceLabel, PriceValueLabel);
        }

        void InitializeBindings ()
        {
            imageLoader = new MvxImageViewLoader (() => this.MainImage);

            this.DelayBind (() => {
                var set = this.CreateBindingSet<KittenCell, Kitten> ();
                set.Bind (NameLabel).To(kitten => kitten.Name);
                set.Bind (PriceValueLabel).To(kitten => kitten.Price);
                set.Bind (imageLoader).To(kitten => kitten.ImageUrl);
                set.Apply ();
            });

        }
    }

但是当显示UILabel时,它下面没有下划线。我的解释是,下划线应用于尚未绑定的文本。但是如何在绑定后设置它呢?

1 个答案:

答案 0 :(得分:1)

您可以使用转换器:

public class UnderlineTextValueConverter : MvxValueConverter<string, NSAttributedString>
    {
        protected override NSAttributedString Convert(string value, Type targetType, object parameter, CultureInfo cultureInfo)
        {
            var attrs = new UIStringAttributes {
                UnderlineStyle = NSUnderlineStyle.Single
            };
            return new NSAttributedString(value, attrs);
        }
    }

然后更新你的绑定......

set.Bind (NameLabel).For(l => l.AttributedText).To(kitten => kitten.Name).WithConversion("UnderlineText", null);

上面的代码未经测试,但它应该没有或很少修改。