1

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.

Community
  • 1
  • 1
SkonJeet
  • 4,827
  • 4
  • 23
  • 32

3 Answers3

2

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.

AkselK
  • 2,563
  • 21
  • 39
1

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

ken2k
  • 48,145
  • 10
  • 116
  • 176
1

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.

Saeed Amiri
  • 22,252
  • 5
  • 45
  • 83
  • The textblock I'm binding the string to will be as part of a datatemplate for listbox items. So the string will differ for each item. Thanks a lot for your reply, I'm sure I can use your solution here somehow. – SkonJeet Feb 07 '12 at 13:08