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

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

问题描述

我想要的是将字符串绑定到文本块或数据触发器(基本上是一些 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";

我有两个控件 - txtBlock1txtBlock2.

And I have two controls - txtBlock1 and 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 to show only first character 是典型的建议解决方案.但对于我在这里尝试实现的目标来说,这似乎非常冗长.

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天全站免登陆