Welcome to Windows Communication Foundation (WCF)
Top Tasks :

WCF Community Bloggers

Data binding issue in WPF: with solution

Here's an issue from Windows Forms that appears to have crept into WPF as well – along with a solution (thanks to Sam Bent and Kevin Moore from the WPF team): Consider a class with a property that enforces a business rule - such as that the value must be all upper case: public class Test : INotifyPropertyChanged { public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; // ... private string _data; public string Data { get { return _data; } set { _data = value.ToUpper(); OnNotifyPropertyChanged("Data"); } } } Bind this to a TextBox and type in a lower-case value. The user continues to see the lower-case value on the screen, even though the object obviously has an upper-case value. The PropertyChanged event is blissfully ignored by WPF data binding. I believe this is the same "optimization" as in Windows Forms, where the assumption is that since the value was put into the object by data binding that it can’t be different from what's on the screen - so no refresh is needed. Obviously that is a unfortunate viewpoint, as it totally ignores the idea than an object might be used to centralize business logic or behavior... In Windows Forms the solution to this issue is relatively simple: handle an event from the BindingSource and force the BindingSource to refresh the value. Bill McCarthy wrapped this solution into an extender control , which I included in CSLA .NET, making the workaround relatively painless. In WPF the solution is slightly different, but also relatively painless. It turns out that this optimization doesn’t occur if an IValueConverter is associated with the binding, and if the binding’s UpdateSourceTrigger is not PropertyChanged. For the TextBox control the UpdateSourceTrigger is LostFocus, so it is good by default, but you’ll want to be aware of this property for other control types. An IValueConverter object’s purpose is to format and parse the value as it flows to and from the target control and source data object. In my case however, I don’t want to convert the value at all, I just want to defeat this unfortunate “optimization”. What’s needed is an identity converter : a converter that does no conversion. namespace Csla.Wpf { public class IdentityConverter : IValueConverter { #region IValueConverter Members public object Convert( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return value; } public object ConvertBack( object value, Type targetType, object parameter, System.Globalization.CultureInfo Read More...
Published Tuesday, January 09, 2007 4:08 PM by Rockford Lhotka

Comments

No Comments
Anonymous comments are disabled

Copyright © 2006 Microsoft Corporation. All Rights Reserved. | Terms of Use | Privacy Statement | Contact Us