How to replace strings in StringFormat in WPF Binding

穿精又带淫゛_ 提交于 2019-12-20 05:55:58

问题


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" />

How can i do this?


回答1:


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

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" />


来源:https://stackoverflow.com/questions/17369615/how-to-replace-strings-in-stringformat-in-wpf-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!