Substring a bound String

2019-08-03 16:15发布

问题:

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

And I have two controls - txtBlock1 and txtBlock2.

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}.

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.

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.

回答1:

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 "";
    }

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



回答2:

I would use a value converter as explained in the example your linked.

But if you want something that is more straightforward, you could use the following property and bindings:

public string[] ValueArray
{
    get
    {
        return values.Split('|');
    }
}

<TextBlock Text="{Binding ValueArray[0]}" />
<TextBlock Text="{Binding ValueArray[1]}" />

But take care of what could happen if values is either null or doesn't contain |.



回答3:

If you just have two string you can simply do:

<TextBlock Text=Text={Binding value1}/>
<TextBlock Text=Text={Binding value2}/>

and

public string value1
{
   get{return values.Split('|')[0]}
   set{values = value + values.Remove(0, values.IndexOf('|')+1)}
}
public string value2 ....
public string values ...

In fact you can write a function for set value and get value for related index (extend above approach),But if you don't like this syntax, IMO what you referred is best option for you.