WPF UserControl 公开 ActualWidth [英] WPF UserControl expose ActualWidth

查看:18
本文介绍了WPF UserControl 公开 ActualWidth的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何向用户公开我的用户控件组件之一的 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.

推荐答案

您需要的是 ReadOnly 依赖项属性.您需要做的第一件事是利用您需要公开的控件的 ActualWidthProperty 依赖项的更改通知.您可以像这样使用 DependencyPropertyDescriptor 来做到这一点:

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

这篇关于WPF UserControl 公开 ActualWidth的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆