I am binding a dependency property to textboxex in WPF. The property is a string that has some values separated by '/' (example: "1/2/3/4" ). I need to bind individual values to separate textboxes which is fine with following implementation of Convert()
method:
public object Convert(object value, Type targetType, object parameter,System.Globalization.CultureInfo culture)
{
if (!string.IsNullOrEmpty(value as string))
{
String[] data = (value as string).Split('/');
return data[Int16.Parse(parameter as string)];
}
return String.Empty;
}
And I am using the ConverterParameter
in xaml
to specify the position of wanted value.
However, the problem is with ConvertBack()
method. I do not know, how to get the source value so I could just add or change just one value in the string (on the specified position).
Thanks for any help.
Would you be better off using an IMultiValueConverter and a MultiBinding?
In this case, if you really want to be able to edit the constituents, you could represent your number by a more complex object which allows you to access its 4 constituent parts through an indexer. That way it's just a simple binding and the object that keeps the 4 parts is accessed and can piece together the whole number:
In most cases, you can safely make
ConvertBack
just throwNotImplementedException
.Indeed, you just haven't got enough information to recreate the source value from its part!
If you really need the back conversion (e.g., if you use two-direction binding), I would split the property into 3 strings in the view model (the class used in
DataContext
), and bind to them separately.I just built up quick sample. Please check if you are looking for the same. This is working at my end.
Xaml Code
Code Behind
However, I couldn't understand the exact issue with
ConvertBack
method. Could you please elaborate on this?Update
You have probably solved your issue already with the help of Vlad, I just thought I should add another way of actually getting the source value in the converter.
First you could make your converter derive from
DependencyObject
so you can add a Dependency Property to it which we shall bind toUnfortunately, a Converter doesn't have a
DataContext
so the Binding won't work out of the box but you can use Josh Smith's excellentDataContextSpy
: Artificial Inheritance Contexts in WPFEnd of Update
Dr.WPF has an elegant solution to this, see the following thread
The way to access binding source in ConvertBack()?
Edit
Using the solution by Dr.WPF, you could supply both the string index and the source
TextBox
to the converter with this (perhaps a little verbose) sample codeAnd then you could later access both the index and the
TextBox
in the ConvertBack method