绑定字符串格式 [英] Binding StringFormat

查看:33
本文介绍了绑定字符串格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组要显示的文本块,我需要以不同方式显示每个文本块的文本.我目前正在标签属性中保存格式字符串,我需要以这种格式显示文本.如何绑定 StringFormat 部分?

I have a collection of textblocks that I'm going to be showing and I'm needing the text of each textblock to be displayed differently. I'm currently saving the format string in the tag property and I'm needing to display the text in this format. How do I bind the StringFormat section?

类似于以下部分:

<TextBlock Tag="{Binding MyFormatString}" Text="{Binding MyProperty, StringFormat='{}{0:MyTag}'}"/>

推荐答案

由于 BindingBase.StringFormat 不是依赖属性,我认为您无法绑定它.如果格式字符串不同,恐怕你将不得不求助于这样的事情

Since BindingBase.StringFormat is not a dependency property, I do not think that you can bind it. If the formatting string varies, I'm afraid you will have to resort to something like this

<TextBlock Text="{Binding MyFormattedProperty}" />

并在您的视图模型中进行格式化.或者,您可以使用 MultiBinding 和转换器(示例代码未经测试):

and do the formatting in your view model. Alternatively, you could use a MultiBinding and a converter (example code untested):

<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]);
    }
    ...
}

这篇关于绑定字符串格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆