如何在 WPF 绑定中替换 StringFormat 中的字符串 [英] How to replace strings in StringFormat in WPF Binding

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

问题描述

我需要在我的字符串中用 ,\n(New Line) 替换 ,我想在 StringFormat

I need to replace a , with ,\n(New Line) in my string i want to do it on ClientSide in StringFormat

<TextBlock Grid.Row="0" Text="{Binding Address}" Grid.RowSpan="3" />

我该怎么做?

推荐答案

你不能通过 StringFormat 绑定操作来做到这一点,因为它不支持替换,只支持输入组合.

You can't do this via a StringFormat binding operation, as that doesn't support replacement, only composition of inputs.

您确实有两个选择 - 在您的 VM 上公开一个具有替换值的新属性,然后绑定到该属性,或者使用 IValueConverter 来处理替换.

You really have two options - expose a new property on your VM that has the replaced value, and bind to that, or use an IValueConverter to handle the replacement.

值转换器可能如下所示:

A value converter could look like:

public class AddNewlineConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string original = Convert.ToString(value);
        return original.Replace(",", ",\n");
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplemnentedException();
    }
}

然后你会在你的绑定中使用它.您可以添加资源:

You'd then use this in your binding. You could add a resource:

<Window.Resources>
    <local:AddNewlineConverter x:Key="addNewLineConv" />
</Window.Resources>

在您的绑定中,您需要将其更改为:

In your binding, you'd change this to:

<TextBlock Grid.Row="0" 
      Text="{Binding Path=Address, Converter={StaticResource addNewLineConv}}"
      Grid.RowSpan="3" />

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

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