wpfbindinguser-controlsreadonlyactualwidth

WPF UserControl expose ActualWidth


How do I expose the ActualWidth property of one of the components of my user control to users?

I have found plenty of examples of how to expose a normal property by creating a new dependency property and binding, but none on how to expose a read-only property like ActualWidth.


Solution

  • What you need is a ReadOnly dependency property. The first thing you need to do is to tap into the change notification of the ActualWidthProperty dependency on the control that you need to expose. You can do that by using the DependencyPropertyDescriptor like this:

    // 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);
    }