Skip to main content
 首页 » 编程设计

c#之如何从用户控件中监听属性值的变化

2024年08月06日28davidwang456

我创建了一个新的用户控件。我想监听 Visibility 属性何时更改,以便我可以同时做一些额外的工作。我知道它是一个依赖属性,但它不是我创建的,所以我很难理解如何连接它。在 WinRT 应用程序中,没有 OverrideMetadata方法,这似乎是最常见的方法。我还尝试创建一个注册到现有属性名称的新依赖属性,但从未触发该回调。

我不得不相信依赖对象有一些方法可以监听它自己的属性变化。我错过了什么?

请您参考如下方法:

我在我的用户控件中使用过类似的东西。然后您可以订阅 VisibilityChanged 事件。请注意,我在属性上使用了 new 关键字。

    /// <summary> 
    /// The current visiblity of this user control. 
    /// </summary> 
    private Visibility _visibility; 
 
    /// <summary> 
    /// Gets or sets the visibility of a UIElement. 
    /// A UIElement that is not visible is not rendered and does not communicate its desired size to layout. 
    /// </summary> 
    /// <returns>A value of the enumeration. The default value is Visible.</returns> 
    public new Visibility Visibility 
    { 
        get { return _visibility; } 
        set 
        { 
            bool differ = false; 
            if (value != _visibility) 
            { 
                _visibility = value; 
                differ = true; 
            } 
 
            base.Visibility = value; 
 
            if (differ) 
            { 
                RaiseVisibilityChanged(value); 
            } 
        } 
    } 
 
 
    /// <summary> 
    /// Raised when the <see cref="Visibility"/> property changes. 
    /// </summary> 
    public event EventHandler<VisibilityChangedEventArgs> VisibilityChanged; 
 
    /// <summary> 
    /// Raises the <see cref="VisibilityChanged"/> event of this command bar. 
    /// </summary> 
    /// <param name="visibility">The new visibility value.</param> 
    private void RaiseVisibilityChanged(Visibility visibility) 
    { 
        if (VisibilityChanged != null) 
        { 
            VisibilityChanged(this, new VisibilityChangedEventArgs(visibility)); 
        } 
    } 
 
    /// <summary> 
    /// Contains the arguments for the <see cref="SampleViewModel.VisibilityChanged"/> event. 
    /// </summary> 
    public sealed class VisibilityChangedEventArgs : EventArgs 
    { 
        /// <summary> 
        /// The new visibility. 
        /// </summary> 
        public Visibility NewVisibility { get; private set; } 
 
        /// <summary> 
        /// Initializes a new instance of the <see cref="VisibilityChangedEventArgs"/> class. 
        /// <param name="newVisibility">The new visibility.</param> 
        /// </summary> 
        public VisibilityChangedEventArgs(Visibility newVisibility) 
        { 
            this.NewVisibility = newVisibility; 
        } 
    }