如何在WPF绑定中替换StringFormat中的字符串

Kri*_*ota 0 wpf string-formatting

我需要在我的字符串中替换,with ,\n(New Line),我想在ClientSide上执行此操作StringFormat

<TextBlock Grid.Row="0" Text="{Binding Address}" Grid.RowSpan="3" />
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Ree*_*sey 6

您不能通过StringFormat绑定操作执行此操作,因为它不支持替换,只支持输入组合.

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

值转换器可能如下所示:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您将在绑定中使用它.您可以添加资源:

<Window.Resources>
    <local:AddNewlineConverter x:Key="addNewLineConv" />
</Window.Resources>
Run Code Online (Sandbox Code Playgroud)

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

<TextBlock Grid.Row="0" 
      Text="{Binding Path=Address, Converter={StaticResource addNewLineConv}}"
      Grid.RowSpan="3" />
Run Code Online (Sandbox Code Playgroud)