MvxTableViewCell 上的属性文本

AttributedText on MvxTableViewCell

我正在尝试在 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 时,它下面没有下划线。我的解释是下划线应用于尚未绑定的文本。但是绑定后怎么设置呢?

你可以使用转换器:

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

以上代码未经测试,但无需修改或稍作修改即可正常工作。