wpf 从代码隐藏绑定字符串格式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14769529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
binding string format from code-behind?
提问by Taras
Please, can some body tell me how to get my double value formatted like "0.0" from code-behind, like this:
请有人告诉我如何从代码隐藏中将我的 double 值格式化为“0.0”,如下所示:
Binding b = new Binding(DoubleValue);
b.StringFormat = "????";
In xaml it works just like that "0.0"...
在 xaml 中,它的工作原理就像“0.0”...
回答by Clemens
What about this?
那这个呢?
b.StringFormat = "{0:F1}";
See the documentation of StringFormatand also Standard Numeric Format Stringsand Custom Numeric Format Strings.
请参阅StringFormat以及Standard Numeric Format Strings和Custom Numeric Format Strings的文档。
EDIT: Just to make clear how a binding would be created and assigned (to the Textproperty of an imaginary TextBlock named textBlock) in code:
编辑:只是为了明确如何在代码中创建和分配绑定(到Text名为 的虚构 TextBlock的属性textBlock):
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);

