加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

WPF:更新依赖属性而不使用INotifyPropertyChanged(UserControl)

发布时间:2020-12-13 20:10:21 所属栏目:百科 来源:网络整理
导读:场景:具有只读TextBox和Button的UserControl.只要按下按钮,TextBox.Text就会被修改和更新. 问题:TextControl.Text属性绑定到UserControl.Message依赖项属性,但在UserControl中修改UserControl.Message时不会更新.但是,当实现INotifyPropertyChanged时,目标
场景:具有只读TextBox和Button的UserControl.只要按下按钮,TextBox.Text就会被修改和更新.

问题:TextControl.Text属性绑定到UserControl.Message依赖项属性,但在UserControl中修改UserControl.Message时不会更新.但是,当实现INotifyPropertyChanged时,目标会更新.

我实际上不需要在依赖属性上实现INotifyPropertyChanged吗?我错过了什么?请参阅演示代码here.

谢谢.

消息属性声明

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 outut窗口中查找绑定错误消息.他们大多非常清楚,并迅速引导您解决问题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读