简体   繁体   English

WPF用户控件公开ActualWidth

[英]WPF UserControl expose ActualWidth

How do I expose the ActualWidth property of one of the components of my user control to users? 如何向用户公开用户控件之一组件的ActualWidth属性?

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 . 我已经找到了许多示例,这些示例如何通过创建新的依赖项属性和绑定来公开普通属性,但没有关于如何公开诸如ActualWidth的只读属性的ActualWidth

What you need is a ReadOnly dependency property. 您需要的是ReadOnly依赖项属性。 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. 您需要做的第一件事是在您需要公开的控件上利用ActualWidthProperty依赖项的更改通知。 You can do that by using the DependencyPropertyDescriptor like this: 您可以这样使用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);
}

ActualWidth is a public readonly property (coming from FrameworkElement ) and is exposed by default. ActualWidth是一个公共的只读属性(来自FrameworkElement ),默认情况下公开。 What is the case that you are trying to achieve? 您要达到的目标是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM