【问题标题】:How to get a Binding content in Xamarin如何在 Xamarin 中获取绑定内容
【发布时间】:2017-04-07 05:36:01
【问题描述】:

这是我的代码:

public ChatItemCell()
    {
        TextAlignment Ausrichtung = TextAlignment.Start;

        var lblBody = new Label()
        {
            FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label)), 
            HorizontalTextAlignment = Ausrichtung,
            TextColor = Color.Black
        };
        lblBody.SetBinding(Label.TextProperty, "Body");

        var lblSender = new Label()
        {
            FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)),
            HorizontalTextAlignment = Ausrichtung,
            TextColor = Color.Gray,
            FontAttributes = FontAttributes.Italic
        };
        lblSender.SetBinding(Label.TextProperty, "Sender");

        var layout = new StackLayout()
        {
            Opacity = 90,
            Orientation = StackOrientation.Vertical,
            Children = {lblSender, lblBody}
        };

        Frame outerFrame = new Frame()
        {
            Padding = new Thickness(5, 5, 5, 5),
            OutlineColor = Color.Accent,
            BackgroundColor = Color.Yellow,
            Content = layout,
        };

        Frame objFrame_Outer = new Frame
        {
            Padding = new Thickness(10, 0, 10, 10),
            Content = outerFrame
        };

        View = objFrame_Outer;

    }

我想要的是,TextAligment 取决于“发件人”。意思是:当发件人是“我”时,对齐应该是左,否则应该是右。那么如何获取“Sender”的内容呢?

非常感谢! 克里兹

【问题讨论】:

    标签: c# xamarin data-binding binding chat


    【解决方案1】:

    您可以将标签的TextAlignment属性绑定到Sender属性,并编写一个ValueConverter,为Sender的值返回正确的TextAlignment:

    public class TextAlignmentConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var s = value as string;
            if (s == null) return TextAlignment.End;
            if (s.ToLower() == "me")
                return TextAlignment.Start;
            return TextAlignment.End;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

    【讨论】:

    • 谢谢!但是还有其他方法吗?我记得有一种方法可以访问像 Bindingcontext.("Sender") 这样的绑定,但我找不到它......因为我还需要获取“body”的长度以适应视单元..
    • 嘿,TommyHaugland,你能告诉我如何使用这个转换器吗?
    • 我很少在后面的代码中构建我的 UI 元素,但我认为这应该可行:lblSender.SetBinding(Label.TextAlignmentProperty, new Binding("Sender", BindingMode.Default, new TextAlignmentConverter(), null));
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-10
    • 1970-01-01
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 2014-05-31
    相关资源
    最近更新 更多