Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

binding string format from code-behind?

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"...

like image 283
Taras Avatar asked Feb 18 '23 14:02

Taras


1 Answers

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);
like image 56
Clemens Avatar answered Feb 20 '23 12:02

Clemens