WPF UserControl expose ActualWidth
Asked Answered
C

2

3

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.

Connected answered 23/11, 2008 at 23:40 Comment(0)
M
10

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);
}
Manufacture answered 25/11, 2008 at 15:25 Comment(0)
J
0

ActualWidth is a public readonly property (coming from FrameworkElement) and is exposed by default. What is the case that you are trying to achieve?

Jolee answered 24/11, 2008 at 7:50 Comment(1)
it's public for the whole control, but not for one of the specific components the control is made up of.Connected

© 2022 - 2024 — McMap. All rights reserved.