Reputation: 1888
Is it possible to have some static text and a bindable context in the same label?
<Label Text = "${Binding totalCost}"
x:Name = "totalCost"
HorizontalOptions = "Start"
VerticalOptions = "Start"
Grid.Row = "6" Grid.Column = "1"/>
Except this displays as "${Binding totalCost}"
I know I could just easily set the field by doing something like totalCost.Text = String.Format("${0}", totalCost);
but just wanted to see if it was possible the other way
Upvotes: 20
Views: 41565
Reputation: 37066
See if this works for you:
Text="{Binding totalCost, StringFormat=${0}}"
Upvotes: 45
Reputation: 119
For labels there is additional feature: ContentStringFormat, example bellow:
<Label Content="{Binding Tag, FallbackValue=Custom}" ContentStringFormat="Length: {0}" DataContext="{Binding ElementName=cbRebarLength, Path=SelectedItem}"/>
Upvotes: 11
Reputation: 318
I'm thinking the .NET way of doing what you want, which is format value string as currency, is using the binding property StringFormat
along with the Currency Format Specifier:
Text="{Binding totalCost, StringFormat=\{0:C\}}"
Your code would look like this
<Label Text="{Binding totalCost, StringFormat=\{0:C\}}"
x:Name = "totalCost"
HorizontalOptions = "Start"
VerticalOptions = "Start"
Grid.Row = "6"
Grid.Column = "1"/>
Cheers.
Upvotes: 3
Reputation: 1020
Although the selected answer is correct, you will be ignoring commas in your currency values or the potential period. A better way would be to expose a get property that provides the appropriate value for the binding. Below is a code snippet for anyone in the future
<Label Text = "${Binding TotalCostFormatted}"
x:Name = "totalCost"
HorizontalOptions = "Start"
VerticalOptions = "Start"
Grid.Row = "6" Grid.Column = "1"/>
In your ViewModel
double totalCost;
public double TotalCost
{
get { return totalCost; }
set
{
totalCost = value;
OnPropertyChanged(nameof(TotalCostFormatted));
}
}
public string TotalCostFormatted
{
get { return TotalCost.ToString("C0"); }
}
Remember you can always just create a get
property in your ViewModel
that exposes some data. Call OnPropertyChanged
or whatever your method is called that implements your INotifyPropertyChanged
interface. If you want the cents on your dollar value, change "C0" to just "C".
Upvotes: 5