4

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 Answer 1

9

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);
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks, but I saw all those articles. It doesn't work, i don't know why... Can you try it in real case?
Ok, it's a textBox in a user control bound to ObservableCollection item.Value, binding works by itself and there is output, but StringFormat doesn't influence on it. And I've noticed that I was wrong about value type it's float, does it make a difference?
Why don't you post the relevant code parts? At least the relevant part of the item class, i.e. the DoubleValue property declaration. Also the code where you actually apply the binding would be interesting. Otherwise, it's all guesswork. And what exactly is DoubleValue in your sample code?
As i said DoubleValue is actually not a double but a float value of property in a view model, sorry but it would be tons of code for you to get clear what is happening.. But this place is pretty simple, I'm pretty sure that there are no other bindings, so only this binding works, and even StringFormat works, for example if i make it "{0:F1}asdas" the output is "12.12321asdas" but it is not formatting the value..
I can reproduce a StringFormat of "{0:F1}asdas" creating an output of "12.12321asdas", just by changing the property type from float to string. You're binding is wrong somehow, that's why I strongly suggest to post more code. Not all, but the relevant parts.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.