我有一组要显示的文本 block ,我需要每个文本 block 的文本以不同方式显示。我目前正在将格式字符串保存在标签属性中,并且需要以这种格式显示文本。如何绑定(bind) StringFormat 部分?
类似于下面的部分:<TextBlock Tag="{Binding MyFormatString}" Text="{Binding MyProperty, StringFormat='{}{0:MyTag}'}" />
最佳答案
由于BindingBase.StringFormat
不是依赖属性,我不认为你可以绑定(bind)它。如果格式化字符串不同,恐怕你将不得不诉诸这样的事情
<TextBlock Text="{Binding MyFormattedProperty}" />
并在您的 View 模型中进行格式化。或者,您可以使用 MultiBinding和一个转换器(示例代码未经测试):
<TextBlock>
<TextBlock.Text>
<MultiBinding Converter="{StaticResource myStringFormatter}">
<Binding Path="MyProperty" />
<Binding Path="MyFormatString" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
public class StringFormatter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return string.Format((string)values[1], values[0]);
}
...
}
关于wpf - 绑定(bind)字符串格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4010772/