Reputation: 81
I can get convert to work from an object to a textbox. But I am a little loss at convertback. Any lead or help is much appreciated.
[ValueConversion(typeof(Object), typeof(String))]
public class DataConverter : IValueConverter
{
// This converts the DateTime object to the string to display.
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
BasePar data = (BasePar)value;
return data.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
string strValue = value as string;
Object objString = (Object)strValue;
return objString;
}
}
Upvotes: 0
Views: 2292
Reputation: 184506
Just generally speaking: You cannot assume that every conversion is lossless, especially ToString
is normally quite the opposite, unless your object is very simple you will not be able to reconstruct it.
Simple example, convert number to its digit-sum: 2584 -> 19
, the backwards conversion is indeterminate because the unique mapping is one-way only. There are quite a lot of numbers with a digit sum of 19
but 2584
has only one digit sum.
Upvotes: 3
Reputation: 66355
indeed what H.B. said, why are you trying to convert between a textbox object and a string anyway? Seems like you might need to look at your design - its called value converter for a reason! If you really want to do it look into class serialization - serialize to a MemoryStream and deserialize to an object. You can deserialize from a string (http://stackoverflow.com/questions/2347642/deserialize-from-string-instead-textreader) too but why bother since you wouldn't want to display that kind of a string anyway? If for some mad reason you do want to serialize into a string you can set the memory position to 0 and pass the memory stream to a StreamReader and then call StreamReader.ReadToEnd().ToString().
Upvotes: 1
Reputation: 3925
Try something along the lines:
var textBoxValue = value as string;
if(textBoxValue != null) {
// Create BasePar instance, setting the textBoxValue as a property value or whatever and return it
}
return DependencyProperty.UnsetValue;
Upvotes: 1