WPF:没有INotifyPropertyChangedUserControl的更新依赖项属性

问题描述

| 场景:UserControl具有一个只读的TextBox和一个Button。每当按下按钮时,都会修改和更新TextBox.Text。 问题:TextControl.Text属性绑定到UserControl.Message依赖项属性,但是从UserControl中修改UserControl.Message时不会更新。但是,在实现INotifyPropertyChanged时,目标会更新。 我实际上不需要在依赖项属性上实现INotifyPropertyChanged吗?我想念什么?请在此处查看演示代码。 谢谢。 消息属性声明
    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缩写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)不,您不必为DependencyProperties调用NotifyPropertyChanged。 2)使用相对来源进行绑定:
<TextBox Text=\"{Binding Message,Mode=OneWay,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=UserControl}}\" ... />
附加信息: 若要查找与绑定相关的错误,请在Visual Studio输出窗口中查找绑定错误消息。它们大部分都非常清晰,可以使您快速找到问题所在。     

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...