Tar
Tar

Reputation: 9015

How to bind and ConvertBack separated TextBox strings to an ObservableCollection<string>?

I have view-model with ObservableCollection<string> that's bound to a TextBox. Users must be able to enter textual data with some separators (say a comma or a semicolon), and have the change reflected to the ObservableCollection<string>, so if I type in the box abc,123,one, the ObservableCollection<string> will have three items: abc, 123 and one.

My examplary ViewModel:

class ViewModel {
    public ObservableCollection<string> MyObservableCollection { get; set; }
}

My TextBox:

<TextBox Text="{Binding MyObservableCollection, Converter={StaticResource Conv}, Mode=TwoWay}"/>

My value-converter:

public class ObservableCollectionToAndFromString : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        ObservableCollection<string> oc;
        if (targetType != typeof (string) || (oc = value as ObservableCollection<string>) == null)
            return Binding.DoNothing;

        return string.Join(",", oc);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var str = value as string;
        return str == null
            ? Binding.DoNothing
            : str.Split(',');
    }
}

But it doesn't work from understandable reason - WPF doesn't know how to replace an ObservableCollection<string> with string[].

But I don't want the framework to replace my ObservableCollection<string> object with new ObservableCollection<string> object (in that case I could have just created new one and return it in the ConvertBack method). I want it to add/remove items to/from the existing ObservableCollection<string>.

How can I accomplish this (without another model-view string property that will do the work in code-behind)?

Edit:

Ok, I give up... movel-view is the way to go... I hoped to make it work on several fields in one time, but that just to awkward.

Upvotes: 0

Views: 592

Answers (1)

Ivan Zub
Ivan Zub

Reputation: 805

I think it's better to add a string representation of data to your viewmodel.

internal class ViewModel
{
    public ObservableCollection<string> MyObservableCollection { get; set; }

    public string MyString
    {
        get { return string.Join(",", MyObservableCollection); }
        set { // update observable collection here based on value }
    }
}

<TextBox Text="{Binding MyString, Mode=TwoWay}"/>

Upvotes: 3

Related Questions