WPF:在不使用INotifyPropertyChanged(UserControl)的情况下更新依赖属性

8

场景: 一个用户控件包含一个只读的文本框和一个按钮。每当按钮按下时,TextBox.Text会被修改和更新。

问题: TextControl.Text属性绑定到了UserControl.Message依赖属性,但是当UserControl.Message从UserControl内部修改时,它不会更新。然而,当实现INotifyPropertyChanged时,目标会更新。

我真的不需要在依赖属性上实现INotifyPropertyChanged吗?我错过了什么?请参见演示代码这里

谢谢。

Message属性声明

    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");
    }

使用XAML缩写的UserControl

<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个回答

6

1) 不需要为DependencyProperties调用NotifyPropertyChanged方法。
2) 在绑定中使用相对源:

<TextBox Text="{Binding Message, Mode=OneWay,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=UserControl}}" ... />

额外信息:

要查找与绑定相关的错误,请在Visual Studio输出窗口中查找绑定错误消息。它们通常非常清晰,并快速引导您找到问题所在。


完美的解决方案!我会试着更关注输出窗口,但在这种情况下似乎没有显示绑定错误。再次感谢。 - BakaBoy
1
为什么需要RelativeSource?为什么不继承DataContext? - Derrick Moeller

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接