如何将用户控件的其中一个组件的ActualWidth
属性公开给用户?WPF UserControl公开ActualWidth
我发现了很多关于如何通过创建一个新的依赖项属性和绑定来公开一个普通属性的例子,但是没有关于如何公开像ActualWidth
这样的只读属性的例子。
如何将用户控件的其中一个组件的ActualWidth
属性公开给用户?WPF UserControl公开ActualWidth
我发现了很多关于如何通过创建一个新的依赖项属性和绑定来公开一个普通属性的例子,但是没有关于如何公开像ActualWidth
这样的只读属性的例子。
你需要的是ReadOnly依赖项属性。你需要做的第一件事是进入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
),默认情况下是公开的。你试图达到什么样的情况?
这是公众对整个控制,而不是控制是由特定的组成部分之一。 – MJS 2008-11-24 21:15:18