Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
ValueConverter behaviour
Message
From
14/07/2011 13:27:53
 
 
To
All
General information
Forum:
ASP.NET
Category:
Windows Presentation Foundation (WPF)
Title:
ValueConverter behaviour
Environment versions
Environment:
C# 4.0
Miscellaneous
Thread ID:
01518156
Message ID:
01518156
Views:
82
Hi,
Background:
I have data stored in a SQL table as varbinary(max) (which in .NET is byte[]). The data is a serialized copy of a WPF Framework Element. I'm trying to decide where, in a MVVM model, this deserialization should take place. One possibility would be to just use a ValueConverter so the conversion happens between the VM and the View so I came up with this:
public class IllObjectBinding : Binding
    {
        public IllObjectBinding()
        {
            Converter = new IllObjectValueConverter();
        }

        [ValueConversion(typeof(byte[]), typeof(ILLObject))]
        class IllObjectValueConverter : IValueConverter
        {
 
            public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                if (value == null) return Binding.DoNothing;
                 //Change from bytearray to object instance
                     byte[] b = (byte[])value;
                    return (ILLObject)BinarySerializer.Deserialize(b);
            }

            public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                ILLObject o = (ILLObject)value;
                return (byte[]) BinarySerializer.SerializeToByteArray(o);
            }
        }
    }
(I thought I'd embed the actual converter within the binding so that the UI guys don't have to remember to use it...)

Now when the Target changes then ConvertBack() gets called as expected. But what surprised me is that the Convert() is also immediately called even though I'm not raising a PropertyChanged on the VM. Looking at the stack trace it seems as if this is being called internally by the Binding itself (Data.BindingExpression.TransferValue()) . Can't find anything in the documentation that would indicate this is normal behaviour but obviously in my scenario it is not desirable (BinarySerializer.Deserialize is not exactly a light weight conversion and, in this case, is unneccessary).
I've verified that the same thing happens with a simple, bog-standard ValueConverter - anyone know why? Or how it can be supressed? (I could set a flag in ConvertBack() so that the next Convert would do nothing but it seems a bit risky.....)

It would probably be a better idea to add a property to the VM and not use a ValueConverter at all so it's no big deal - just curious as to why Binding/ValueConverter is implemented this way.....
Next
Reply
Map
View

Click here to load this message in the networking platform