WPF用户控件公开ActualWidth属性

3

我该如何将用户控件中一个组件的ActualWidth属性暴露给用户?

我找到了很多关于如何通过创建新的依赖属性和绑定来公开普通属性的示例,但没有关于如何公开只读属性,比如ActualWidth的示例。

2个回答

10

你需要的是一个只读的依赖属性。首先,您需要利用需要公开的控件上的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);
}

0

ActualWidth 是一个公共只读属性(来自于 FrameworkElement),默认情况下是公开的。您想要实现什么样的情况?


它是公开的,适用于整个控件,但不适用于控件中的某个特定组件。 - MJS

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接