4
votes

Please, can some body tell me how to get my double value formatted like "0.0" from code-behind, like this:

Binding b = new Binding(DoubleValue);
b.StringFormat = "????";

In xaml it works just like that "0.0"...

1

1 Answers

8
votes

What about this?

b.StringFormat = "{0:F1}";

See the documentation of StringFormat and also Standard Numeric Format Strings and Custom Numeric Format Strings.


EDIT: Just to make clear how a binding would be created and assigned (to the Text property of an imaginary TextBlock named textBlock) in code:

public class ViewModel
{
    public double DoubleValue { get; set; }
}

...

var viewModel = new ViewModel
{
    DoubleValue = Math.PI
};

var binding = new Binding
{
    Source = viewModel,
    Path = new PropertyPath("DoubleValue"),
    StringFormat = "{0:F1}"
};

textBlock.SetBinding(TextBlock.TextProperty, binding);

Alternatively:

var binding = new Binding
{
    Path = new PropertyPath("DoubleValue"),
    StringFormat = "{0:F1}"
};

textBlock.DataContext = viewModel;
textBlock.SetBinding(TextBlock.TextProperty, binding);