how to have 2 data binding fields in one Xamarin forms label?
*Update: With the release of Xamarin Forms 4.7, you can now use Multi-Bindings instead of creating a getter property. Using the first and last name example, you would do something like this:
<StackLayout Padding="20,0,0,0" HorizontalOptions="CenterAndExpand" >
<Label x:Name="FirstName">
<Label.Text>
<MultiBinding StringFormat="{}{0} {1}">
<Binding Path="FirstName" />
<Binding Path="LastName" />
</MultiBinding>
</Label.Text>
</Label>
.........
</StackLayout>
*Pre-Xamarin Forms 4.7 What I do in this situation is to put an extra property on the model that combines the two properties.
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;
}
Now in your ViewModel, if first or last name changes, you would need to do something like this to update the FirstLastName
property:
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
}
}
}
Then do the same for you LastName
property.
Edit: Your XAML would then look like:
<StackLayout Padding="20,0,0,0" HorizontalOptions="CenterAndExpand" >
<Label x:Name="FirstName" Text="{Binding FirstLastName}"/>
.....
</StackLayout>
Edit2: So since you are probably not ever changing the First or Last Name property while showing the UI, you just need to add the property to your model, like I show in the ContactInfo
code above, and then change your label, like I show in the edit above and you will be good to go.
As Ed Phuket said it is working but :
You need to add Mode=OneWay
if you want it to update with OnPropertyChanged
event to the span because it has OneTime
Binding mode as default