简体   繁体   中英

WPF Binding not updating with UpdateSourceTrigger=PropertyChanged

I have a TabControl in which I set the DataContext to an instance of the this class, It's basicly a wrapper for DependencyProperties of a static class with the same properties.

In my Markup I set the DataContext like this

<TabControl DataContext="{Binding ElementName=self, Path=Settings}">

and binding to the property within the TabControl like this

<TextBox Text="{Binding Path=Url, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

However, this does not lead to any updates of the source when the content of the TextBox is changed. I can change the content of the TextBox, let it loose focus etc. it does just not update the source.

Url is a dependency property and when set from XAML, wrapper property setter won't be called .

From MSDN :

The current WPF implementation of its XAML processor is inherently dependency property aware. The WPF XAML processor uses property system methods for dependency properties when loading binary XAML and processing attributes that are dependency properties. This effectively bypasses the property wrappers. When you implement custom dependency properties, you must account for this behavior and should avoid placing any other code in your property wrapper other than the property system methods GetValue and SetValue.


In case you want to do something on its property changed you should provide PropertyChangedCallback and write code there.

You can refer to the sample here in case PropertyChangedCallback is new to you. Something like:

public static readonly DependencyProperty UrlProperty = 
  DependencyProperty.Register(
  "Url",
  typeof(string),
  typeof(SettingsWrapper),
  new PropertyMetadata(OnUrlChanged)
  )
);

private static void OnUrlChanged(DependencyObject d,
                                 DependencyPropertyChangedEventArgs e)
{
    SettingsWrapper instance = (SettingsWrapper)d;
    instance.Settings.Url = e.NewValue.ToString();
}

You said in a (now deleted) comment that your Window has x:Name="self" , however the Window class does not have a property called Settings .

If this is an attached property, you need to reference it by the attached property by the full name, and wrap it in parenthesis.

For example,

<TabControl DataContext="{Binding ElementName=self, Path=(local:MyClass.Settings)}">

See WPF Attached Property Data Binding for more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM