WPF UserControl expose ActualWidth

前端 未结 2 1851
星月不相逢
星月不相逢 2020-12-18 11:33

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

相关标签:
2条回答
  • 2020-12-18 11:50

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

    0 讨论(0)
  • 2020-12-18 11:59

    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);
    }
    
    0 讨论(0)
提交回复
热议问题