3

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

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

4

2 回答 2

9

您需要的是 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);
}
于 2008-11-25T15:25:16.817 回答
0

ActualWidth是一个公共只读属性(来自FrameworkElement),默认公开。您要达到的目标是什么?

于 2008-11-24T07:50:10.777 回答