C# WPF 操作一个绑定字符串来替换最后一个 / 之前的所有内容,然后添加一个不同的前缀

C# WPF manipulate a bound string to replace everything before the last / and add then a different prefix

我刚刚学习 Datagrids,有一个问题我找不到明确的答案。 我将如何操作绑定字符串以替换最后一个 / 之前的所有内容,然后添加一个不同的前缀。

这将在数据网格中显示图像。

例如img变量绑定的是

img: "/img_banner/testBanner.jpg"

最后需要输出的是:

http://www.testsite.com/img_thumnail/testBanner.jpg

到目前为止,我已经找到了有关向绑定字符串添加文本的信息,但我想删除部分字符串。

这是我目前得到的结果:

<Image Source="{Binding img, StringFormat=http://www.testsite.com/img_thumnail{0}}" Height="40"/>

有什么方法可以轻松 trim 最后一个 / 之前的所有内容?

您可以使用 IValueConverter:

public class MyUrlConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if(value == null)
            {
                return null;
            }
            var urlString = value as string;

            //now do whatever you want to do with the string
            //then return it
            return urlString;
        }

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

然后将其添加到您的资源中

<Window.Resources>
   <local:MyUrlConverter x:Key="conv"></local:MyUrlConverter>
</Window.Resources>

并将其用作:

 <Image Source="{Binding img,Converter={StaticResource ResourceKey=conv}}"></Image>

请注意,如果逻辑依赖于您的视图模型,那么您最好在 img 属性

的 getter 或 setter 中执行操作