我创建了一个新的用户控件。我想听看Visibility属性何时发生变化,以便我可以同时做一些额外的工作。我知道它是一个依赖属性,但它不是我创建的属性,所以我很难理解如何挂钩它。在WinRT应用程序中,没有OverrideMetadata方法,这似乎是最常用的方法。我还尝试创建一个注册到现有属性名称的新依赖项属性,但该回调从未被触发过。
我必须相信依赖对象有一些方法可以监听它自己的属性更改。我错过了什么?
答案 0 :(得分:3)
我在用户控件中使用过类似的东西。然后,您可以订阅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;
}
}