WPF用户控件暴露ActualWidth的 [英] WPF UserControl expose ActualWidth

查看:949
本文介绍了WPF用户控件暴露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.

推荐答案

您需要的是一个只读依赖属性。你需要做的第一件事是进军在您需要公开控件中的 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用户控件暴露ActualWidth的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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