2008-11-23 74 views
3

如何將用戶控件的其中一個組件的ActualWidth屬性公開給用戶?WPF UserControl公開ActualWidth

我發現了很多關於如何通過創建一個新的依賴項屬性和綁定來公開一個普通屬性的例子,但是沒有關於如何公開像ActualWidth這樣的只讀屬性的例子。

回答

8

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

ActualWidth是一個公開只讀屬性(來自FrameworkElement),默認情況下是公開的。你試圖達到什麼樣的情況?

+0

這是公衆對整個控制,而不是控制是由特定的組成部分之一。 – MJS 2008-11-24 21:15:18