我该如何将用户控件中一个组件的ActualWidth
属性暴露给用户?
我找到了很多关于如何通过创建新的依赖属性和绑定来公开普通属性的示例,但没有关于如何公开只读属性,比如ActualWidth
的示例。
我该如何将用户控件中一个组件的ActualWidth
属性暴露给用户?
我找到了很多关于如何通过创建新的依赖属性和绑定来公开普通属性的示例,但没有关于如何公开只读属性,比如ActualWidth
的示例。
你需要的是一个只读的依赖属性。首先,您需要利用需要公开的控件上的ActualWidthProperty
依赖项的更改通知。您可以这样使用DependencyPropertyDescriptor
实现:
// Need to tap into change notification of the FrameworkElement.ActualWidthProperty
Public MyUserControl()
{
DependencyPropertyDescriptor descriptor = DependencyPropertyDescriptor.FromProperty
(FrameworkElement.ActualWidthProperty, typeof(FrameworkElement));
descriptor.AddValueChanged(this.MyElement, new EventHandler
OnActualWidthChanged);
}
// Dependency Property Declaration
private static DependencyPropertyKey ElementActualWidthPropertyKey =
DependencyProperty.RegisterReadOnly("ElementActualWidth", typeof(double),
new PropertyMetadata());
public static DependencyProperty ElementActualWidthProperty =
ElementActualWidthPropertyKey.DependencyProperty;
public double ElementActualWidth
{
get{return (double)GetValue(ElementActualWidthProperty); }
}
private void SetActualWidth(double value)
{
SetValue(ElementActualWidthPropertyKey, value);
}
// Dependency Property Callback
// Called when this.MyElement.ActualWidth is changed
private void OnActualWidthChanged(object sender, Eventargs e)
{
this.SetActualWidth(this.MyElement.ActualWidth);
}
ActualWidth
是一个公共只读属性(来自于 FrameworkElement
),默认情况下是公开的。您想要实现什么样的情况?