2016-11-23 50 views
0

綁定的內容,這是我的代碼:如何獲得在Xamarin

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取決於「發件人」。意思是:當發送者是「我」時,應該留下對齊,否則應該是正確的。那麼如何獲得「發件人」的內容?

非常感謝! 克里茲

回答

0

您可以將標籤的TextAlignment屬性綁定到發送者的財產,並編寫返回正確的TextAlignment發件人的價值ValueConverter:

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(); 
    } 
} 
+0

謝謝!但還有另一種方式嗎?我記得有一種方法可以訪問像Bindingcontext這樣的綁定(「Sender」),但是我找不到它......因爲我還需要獲得「body」的長度以適應viewcell .. –

+0

嘿TommyHaugland,你能給我一個提示如何使用這個轉換器? –

+0

我很少構建代碼我的UI元素的背後,但我認爲這應該工作:'lblSender.SetBinding(Label.TextAlignmentProperty,新的綁定( 「發件人」,BindingMode.Default, 新TextAlignmentConverter(),NULL));' – TommyHaugland

相關問題