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

标签 c# user-controls windows-runtime

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

关于c# - 如何从用户控件中监听属性值的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27634877/

相关文章:

ASP.NET:公开 Web 用户控件的控件

C# .net 将事件从页面冒泡到用户控件(子)

c# - 使用Windows Phone 8.1媒体编辑API的音频合成

xaml - 右键单击 GridView 项目时显示 AppBar

c# - 在表格单元格中显示按钮悬停/鼠标悬停

c# - 将 Entity Framework 与现有模型结合使用

c# - Web API授权access_token验证

c# - 通过查看字节来检查 decimal 是否包含小数位

c# - 动态添加控件到用户控件

c# - 应用程序无法导航到 MainPage