1

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

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

我怎样才能做到这一点?

4

1 回答 1

8

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

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

值转换器可能如下所示:

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();
    }
}

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

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

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

<TextBlock Grid.Row="0" 
      Text="{Binding Path=Address, Converter={StaticResource addNewLineConv}}"
      Grid.RowSpan="3" />
于 2013-06-28T16:41:44.757 回答