如何从用户控件中侦听属性值更改
本文关键字:属性 用户 控件 | 更新日期: 2023-09-27 18:35:07
我创建了一个新的用户控件。 我想倾听可见性属性何时更改,以便我可以同时做一些额外的工作。 我知道它是一个依赖属性,但它不是我创建的,所以我正在努力了解如何挂钩它。 在 WinRT 应用中,没有替代元数据方法,这似乎是执行此操作的最常见方法。 我还尝试创建一个注册到现有属性名称的新依赖项属性,但该回调从未触发。
我必须相信依赖对象有某种方法来侦听它自己的属性更改。 我错过了什么?
我在用户控件中使用了这样的东西。然后,您可以订阅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;
}
}