Home > front end >  How do I properly bind an ASCII string in the form of a list<byte> to a textbox?
How do I properly bind an ASCII string in the form of a list<byte> to a textbox?

Time:01-18

I have a List that represents an ASCII string, and I'm trying to let it be edited via a textbox. I've set up the binding like this:

public List<byte> ParamData;

var b = new TextBox();
b.DataContext = ParamData;
var binding = new Binding(".");
binding.Converter = new ListToStringConverter();
binding.Mode = BindingMode.TwoWay;
binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
b.SetBinding(TextBox.TextProperty, binding);


internal class ListToStringConverter : IValueConverter {
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
        var orig = (List<byte>) value;
        var res = Encoding.ASCII.GetString(orig.ToArray());
        return res;

    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
        var orig = (string) value;
        var res = Encoding.ASCII.GetBytes(orig);
        return new List<byte>(res);
    }
}

However, I find that changing the text in the textbos doesn't trigger ConvertBack, and ParamData doesn't actually get updated. I've tried triggering UpdateSource() on text change in the textbox, nbut itl still nothing.

Any ideas?

CodePudding user response:

you need to set binding source to a property, which can be updated by binding. as of now, binding uses entire object as its source and cannot replace it with completely different object (new list from ConvertBack method)

public class ByteListWrapper
{
    public List<byte> ParamData { get; set; }
}

var b = new TextBox();
b.DataContext = new ByteListWrapper { ParamData = someData };
var binding = new Binding("ParamData")
{
    Converter = new ListToStringConverter(),
    Mode = BindingMode.TwoWay,
    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
};

b.SetBinding(TextBox.TextProperty, binding);

so again: now binding updates value of a source property, instead of replacing source (which it cannot do)

  •  Tags:  
  • Related