wpf TextBlock:Text 和 StringFormat 的绑定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18515482/
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
TextBlock: Binding of Text and StringFormat
提问by as74
Is it possible to bind Textand StringFormattoo?
是否有可能结合Text并StringFormat吗?
<TextBlock Text="{Binding Path=Price, StringFormat={Binding Path=DecimalPoints}}" />
DecimalPointsis constantly changing from F0to F15. Unfortunatelly the code above doesn't compile.
DecimalPoints不断从F0变为F15。不幸的是,上面的代码不能编译。
回答by Anatoliy Nikolaev
As mentioned @Sheridan, in this case, Bindingwill not work. But you can create a class with static strings, and refer to them in XAML. The syntax is:
如前所述@Sheridan,在这种情况下,Binding将不起作用。但是您可以使用静态字符串创建一个类,并在 XAML 中引用它们。语法是:
<x:Static Member="prefix : typeName . staticMemberName" .../>
Below is an example:
下面是一个例子:
XAML
XAML
xmlns:local="clr-namespace:YourNameSpace"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
<Grid>
<TextBlock Text="{Binding Source={x:Static sys:DateTime.Now}, StringFormat={x:Static Member=local:StringFormats.DateFormat}}"
HorizontalAlignment="Right" />
<TextBlock Text="{Binding Source={x:Static sys:DateTime.Now}, StringFormat={x:Static Member=local:StringFormats.Time}}" />
</Grid>
Code behind
Code behind
public class StringFormats
{
public static string DateFormat = "Date: {0:dddd}";
public static string Time = "Time: {0:HH:mm}";
}
For more information, please see:
有关更多信息,请参阅:
回答by Liz
I think your best bet is definitely a converter. Then your binding would look like this:
我认为您最好的选择绝对是转换器。那么您的绑定将如下所示:
<TextBlock.Text>
<MultiBinding Converter="{StaticResource StringFormatConverter }">
<Binding Path="Price"/>
<Binding Path="DecimalPoints"/>
</MultiBinding>
</TextBlock.Text>
Then a quick converter (you can certainly make it nicer, but this is the general idea).
然后是一个快速转换器(你当然可以让它更好,但这是一般的想法)。
public class StringFormatConverter : IMultiValueConverter
{
#region IMultiValueConverter Members
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
double number = (double)values[0];
string format = "f" + ((int)values[1]).ToString();
return number.ToString(format);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
回答by Sheridan
No you can't... the reason is because you can only bind to a DependencyPropertyof a DependencyObjectand the StringFormatproperty of the Bindingclass is just a string.
不,你不能......原因是你只能绑定到DependencyPropertyaDependencyObject并且类的StringFormat属性Binding只是 a string。

