binding string format from code-behind?

人盡茶涼 提交于 2020-01-04 12:48:33

问题


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:


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);


来源:https://stackoverflow.com/questions/14769529/binding-string-format-from-code-behind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!