WPF UserControl公开ActualWidth

时间:2008-11-23 23:40:21

标签: wpf binding user-controls readonly actualwidth

如何向用户公开我的用户控件的某个组件的ActualWidth属性?

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

2 个答案:

答案 0 :(得分:8)

您需要的是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);
}

答案 1 :(得分:0)

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

相关问题