子字符串绑定的字符串 [英] Substring a bound String

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

问题描述

我想要的是将字符串绑定到文本块或数据触发器(基本上是一些WPF对象),然后将字符串作为一部分.该字符串将被定界.因此,例如,我有以下字符串:

What I want is to bind a string to a textblock or datatrigger (basically some WPF object) and take a part of the string. This string will be delimited. So, for example, I have this string:

String values = "value1|value2";

我有两个控件- txtBlock1 txtBlock2 .

在txtBlock1中,我想将Text属性设置为 Text = {Binding values} .在txtBlock2中,我想将Text属性设置为 Text = {Binding values} .

In txtBlock1 I would like to set the Text property like Text={Binding values}. In txtBlock2 I would like to set the Text property like Text={Binding values}.

显然,这将显示相​​同的字符串,因此我需要某种StringFormat表达式来添加此绑定到子字符串值,以便 txtBlock1 读取value1,而 txtBlock2 读取value2.

Obviously this will display the same string so I need some sort of StringFormat expression to add to this binding to substring values so that txtBlock1 reads value1 and txtBlock2 reads value2.

我对此有很好的了解,看起来像这样:仅显示第一个字符的"Wpf Binding Stringformat" .但是对于我在这里想要实现的目标来说,这似乎太漫长了.

I've had a good read about and it seems like this: Wpf Binding Stringformat to show only first character is the typical proposed solution. But it seems awfully long-winded for what I'm trying to achieve here.

非常感谢您提前提供帮助.

Thanks a lot for any help in advance.

推荐答案

这里需要一个转换器.添加转换器参数以指示索引.

What you need here is a converter. Add a converter parameter to indicate the index.

public class DelimiterConverter : IValueConverter
{
    public object Convert(Object value, Type targetType, object parameter, CultureInfo culture)
    {
        string[] values = ((string)value).Split("|");
        int index = int.Parse((string)parameter);
        return values[index];
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return "";
    }

然后,您只需使用ConverterParameter属性在XAML中指定值的索引即可.

Then you just specify the index of the value in XAML with the ConverterParameter attribute.

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

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