I have in my database a string corresponding to a serialized byte array. I'd like to be able to modify bytes present in that string and add or remove some of them.
I'm converting my string retrieved from my database to my viewmodel to a list of bytes in my XAML via a converter present in my listbox binding. I then use the byte array represented as textboxes with a datatemplate. But the problem is that I'm not able to retrieve changes done in the textboxes back to the listbox and then back to the Serialized string. What I tried:
<ListBox ItemsSource="{Binding ByteArray, Converter={converter:HexStringToListOfBytesConverter}}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=., Mode=TwoWay}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
I'm having an idea about why it isn't working but can't get my head around how to make it work. I think that the converter doesn't affect the textboxes. Ideally the string to byte array conversion should only be used to edit an existing Serialized array. And a new made one from the modifications done should replace the old one.
You can't bind to a string
TwoWay. You bind to properties of objects, the binding source. In a TwoWay binding you can change the value of these properties. This means, in theory, you could bind to properties of string to change its content.Additionally,
stringis immutable.You must introduce a wrapper type to represent a byte or character representation. This way you can modify the property value of a binding source.
In general, your approach is overly complicated. You can directly work on
stringor evenchar. There is a bult-in compiler conversion betweencharandbyte. It doesn't make sense to convert astringtobyte[]only to convert it back tostringfor editing in the view. Which human being does not prefer to edit text presented as characters instead of bytes...I recommend to convert the hex string to a text string and edit those values.
The following example introduces a
ByteValuewrapper and encapsulates the conversion in aByteValueCollectionthat you can directly bind to.The
ByteValueenables you to edit both the byte value and the character representation. MainWindow.xaml.csMainWIndow.xaml
ByteValue.cs
ByteValueCollection.cs