【问题标题】:WPF UserControl expose ActualWidthWPF UserControl 公开 ActualWidth
【发布时间】:2010-09-23 17:02:20
【问题描述】:

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

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

【问题讨论】:

    标签: wpf binding user-controls readonly actualwidth


    【解决方案1】:

    您需要的是 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);
    }
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 它对整个控件是公开的,但不是对组成该控件的特定组件之一。
      猜你喜欢
      • 1970-01-01
      • 2010-12-19
      • 1970-01-01
      • 1970-01-01
      • 2017-07-07
      • 1970-01-01
      • 2015-04-01
      • 2011-01-25
      • 1970-01-01
      相关资源
      最近更新 更多