如何在一个Xamarin表单标签中有2个数据绑定字段?

你好,我有一个应用程序,我正在从xamrian froms工作,从服务获取数据。 我要做的是让名字和姓氏字段显示在同一标签中,但它当前显示名字然后它返回一行,然后显示姓氏。 inheritance我的xaml代码:

                           

编辑这是我的代码隐藏:

 using Newtonsoft.Json; using ReadyMo.Data; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Net.Http; using System.Threading.Tasks; using Xamarin.Forms; namespace ReadyMo { public partial class ContactInfo : ContentPage { private County item; public static async Task GetContactString(string contactid) { HttpClient client = new HttpClient(); var url = $"URL"; var response = await client.GetAsync(url); if (response.IsSuccessStatusCode) { var responsetext = await response.Content.ReadAsStringAsync(); return responsetext; } throw new Exception(response.ReasonPhrase); } public ContactInfo() { InitializeComponent(); ContactInfoList = new ObservableCollection(); } ObservableCollection ContactInfoList; public ContactInfo(County item) : this() { this.item = item; this.BindingContext = ContactInfoList; } protected override async void OnAppearing() { if (item == null) return; var contact = await GetContactString(item.id); var models = JsonConvert.DeserializeObject<List>(contact); foreach (var model in models) ContactInfoList.Add(model); } } } 

任何帮助都会很棒!

提前致谢 :)

我在这种情况下做的是在组合两个属性的模型上放置一个额外的属性。

 public class ContactInfo { public string FirstName { get; set; } public string LastName { get; set; } public string FirstLastName { get { return FirstName + " " + LastName; }} //Or use C# 6 goodness //public string FirstLastName => FirstName + " " + LastName; } 

现在在ViewModel中,如果名字或名字发生变化,你需要做类似的事情来更新FirstLastName属性:

 private string _firstLastName; public string FirstLastName { get { return _firstLastName; } set { if(_firstLastName != value) { _firstLastName = value; SetPropertyChanged(); } } } private string _firstName; public string FirstName { get { return _firstName; } set { if(_firstName != value) { _firstName = value; SetPropertyChanged(); SetPropertyChanged("FirstLastName"); //Also send alert that FirstLastName changed } } } 

然后为你做LastName属性。

编辑:您的XAML将如下所示:

   .....  

Edit2:因为你可能在显示UI时没有更改First或Last Name属性,你只需要将属性添加到模型中,就像我在上面的ContactInfo代码中显示的那样,然后更改你的标签,就像我展示的那样在上面的编辑中你会很高兴。

看起来像Label可以包含多个Spans ,与WPF中的TextBlock / Run大致相似:

   

错误的答案

结果是Span.Text不可绑定。 上面的XAML不起作用; 它抛出exception。 但我会把它留在这里,所以没有其他人浪费时间在我所做的同样注定的概念上。

更新:

Afzal Ali评论说,截至2018年8月,这在XF 3.1中有效。

正如Ed Phuket所说,它正在发挥作用,但是:
如果要将OneTime事件更新为跨度,则需要添加Mode=OneWay ,因为它具有默认的OneTime Binding模式

虽然Xamarin Forms的团队仍在使用Span元素计算绑定,但您可以更改标签的格式以使其正常工作: