So in my XAML I have this:
<TextBlock Text="{Binding MyDecimalProperty, StringFormat={}{0:#.###}}"/>
When the value of MyDecimalProperty is for example 5.35570256 then the TextBlock value shown is 5.356
Is there a way to have the TextBlock show 5.355 instead (i.e. to truncate the number instead rounding it) using StringFormat?
I know I can use a Value Converter but I wanted to know if I can use StringFormat or anything else defined in the XAML to achieve the same.
Update: People keep wondering why I don't want to use a converter. Please read above in bold. Its not that I don't want to; I just wanted to know if I can do the same with StringFormat or any other XAML construct.
Thank you.
if I can use StringFormat or anything else defined in the XAML to achieve the same
StringFormat is specific to the Binding Markup Extension (actually the binding base BindingBase.StringFormat Property (System.Windows.Data)) and ultimately uses the .Net string formatting such as ToString("G3")
(see Standard Numeric Format Strings) which rounds and doesn't truncate; so it is not possible to override in Xaml such features.
Create another property on the viewmodel which is an associated string
type which simply parrot's the value wanted, but truncated. Then bind as such.
ViewModel
public decimal TargetDecimal
{
get { return _TargetDecimal; }
set { _TargetDecimal = value;
OnPropertyChanged("TargetDecimal");
OnPropertyChanged("TargetValueTruncated"); }
}
// No error checking done for example
public string TargetValueTruncated
{
get { return Regex.Match(_TargetDecimal.ToString(), @"\d+\.\d\d\d").Value; }
}
Xaml
<TextBlock Text="{Binding TargetDecimal, StringFormat=Original: {0}}"/>
<TextBlock Text="{Binding TargetDecimal, StringFormat=Modified: {0:#.###}}"/>
<TextBlock Text="{Binding TargetValueTruncated, StringFormat=Truncated: {0}}"/>
Result