【问题标题】:WPF: Update Dependency Property without INotifyPropertyChanged (UserControl)WPF:在没有 INotifyPropertyChanged (UserControl) 的情况下更新依赖属性
【发布时间】:2011-09-02 22:19:30
【问题描述】:

场景:具有只读文本框和按钮的用户控件。每当按下按钮时,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>

【问题讨论】:

    标签: wpf wpf-controls binding


    【解决方案1】:

    1) 不,您不必为 DependencyProperties 调用 NotifyPropertyChanged。
    2) 使用相对来源进行绑定:

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

    附加信息:

    要查找与绑定相关的错误,请在 Visual Studio 输出窗口中查找绑定错误消息。它们大多非常清晰,可以快速引导您解决问题。

    【讨论】:

    • 完美解决方案!我会尝试更多地关注输出窗口,但在这种情况下它似乎没有显示绑定错误。再次感谢。
    • 为什么需要RelativeSource?为什么不继承DataContext?
    猜你喜欢
    • 1970-01-01
    • 2014-08-31
    • 2010-12-26
    • 2013-08-12
    • 1970-01-01
    • 2021-02-11
    • 1970-01-01
    • 2011-04-02
    • 1970-01-01
    相关资源
    最近更新 更多