Scenario: UserControl that has a read-only TextBox and a Button. TextBox.Text is modified and updated whenever the Button is pressed.
Problem: TextControl.Text property is bound to UserControl.Message dependency property but does not update when UserControl.Message is modified from within UserControl. However, target does update when INotifyPropertyChanged is implemented.
I don’t actually need to implement INotifyPropertyChanged on a dependency property do I? What am I missing? Please see demonstration code here.
Thanks.
Message Property Declaration
public static readonly DependencyProperty MessageProperty =
DependencyProperty.Register("Message", typeof (string),
typeof (TextControl), new FrameworkPropertyMetadata("[WPFApp]" +
Environment.NewLine, OnMessageChanged, OnMessageCoerce));
public string Message
{
get { return (string) GetValue(MessageProperty); }
set { SetValue(MessageProperty, value); }
}
private static object OnMessageCoerce(DependencyObject obj,
object baseValue)
{
return (string) obj.GetValue(MessageProperty) + (string) baseValue;
}
private static void OnMessageChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
// do i need to do this?
((TextControl) d).NotifyPropertyChanged("Message");
}
UserControl abbreviated XAML
<UserControl x:Class="WPFApp.TextControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d" d:DesignHeight="64" d:DesignWidth="355"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
<TextBox Text="{Binding Message, Mode=OneWay}" ... />
<Button ... />
</Grid>
</UserControl>
1) No, you don’t have to call NotifyPropertyChanged for DependencyProperties.
2) Use a relative source for the binding:
Additional information:
To find binding related errors, look in the Visual Studio outut window for binding error messages. They are mostly very clear and lead you quickly to the problem.