8

I have both VS2008 and VS2010 installed, and I see a very strange behavior

In VS2008, I have a simple WPF app:

<TextBox x:Name="textbox" Text="{Binding Path=MyProperty,Mode=TwoWay}"></TextBox>

and

public Window1()
{
    InitializeComponent();
    DataContext = this;
}
public string MyProperty
{
    get { return (string)GetValue(MyPropertyProperty); }
    set { SetValue(MyPropertyProperty, value); }
}
public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register("MyProperty", typeof(string), typeof(Window1), new PropertyMetadata("default",null,Coerce));

private static object Coerce(DependencyObject d, object baseValue)
{
    return "Coerced Value";
}

When I enter random string in textbox and hit tab, I expect the textbox.Text to be reset to "Coerced Value". If I debug I see that the app breaks in the Coerce function but the UI is not updated.

Interestingly this same code works in VS2010, the UI gets updated with Coerced value. Anybody has an idea whats happening?

Is it a WPF bug? or am I missing something?

H.B.
  • 166,899
  • 29
  • 327
  • 400
Nitin Chaudhari
  • 1,497
  • 16
  • 39

1 Answers1

3

You have to force an update via UpdateTarget(). Take a look at http://social.msdn.microsoft.com/forums/en-US/wpf/thread/c404360c-8e31-4a85-9762-0324ed8812ef/

Daniel Rose
  • 17,233
  • 9
  • 65
  • 88
  • 2
    That worked, but whats the point if coercion can only happen on Button click or something... I might as well update the value manually. Interestingly VS2010/.net4.0 can automatically do it. So looks like .net3.5SP1 does not have Coercion fully baked. – Nitin Chaudhari Jun 09 '10 at 06:56
  • I'd guess that too many people complained that Coerce did not work as expected. – Daniel Rose Jun 09 '10 at 07:42
  • 1
    I've found hints to that solution several times now, but none of them explains *where* to insert the call to `UpdateTarget()`. In the `CoerceValueCallback`? That's certainly too early, as the value hasn't been coerced by that time yet. So - when should `UpdateTarget()` be invoked? (I have elaborated more extensively in my [related question](http://stackoverflow.com/questions/13830989/force-propagation-of-coerced-value).) – O. R. Mapper Dec 15 '12 at 11:14