繁体   English   中英

如何从usercontrol中侦听属性值更改

[英]How to listen for a property value change from within a usercontrol

我创建了一个新的用户控件。 我想听看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;
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM