2010-05-04 43 views
1

我正在學習WPF,並試圖創建我的第一個UserControl。我的用戶包括DependencyProperty方向問題

  1. 的StackPanel
  2. StackPanel中包含一個標籤和文本框

我想爲標籤

  • 定位爲創建兩個依賴屬性

    1. 文本StackPanel - 方向將有效地影響標籤和文本框的位置

    我已成功創建文本依賴項屬性並將其綁定到我的UserControls。但是,當我創建的Orientation屬性,我似乎得到以下的錯誤得到財產

    as運算符必須與引用類型或可空類型可以使用(「System.Windows.Controls.Orientation」是一種非非空值類型)

    public static DependencyProperty OrientationProperty = DependencyProperty.Register("Orientation", typeof(System.Windows.Controls.Orientation), typeof(MyControl), new PropertyMetadata((System.Windows.Controls.Orientation)(Orientation.Horizontal))); 
    public Orientation Orientation 
    { 
        get { return GetValue(OrientationProperty) as System.Windows.Controls.Orientation; } 
        set { SetValue(OrientationProperty, value); } 
    } 
    

    感謝您的幫助。

    編輯: 我改變了代碼如下,它似乎按預期工作。但這是解決問題的正確方法嗎?

    public Orientation Orientation 
    { 
         get 
         { 
          Orientation? o = GetValue(OrientationProperty) as System.Windows.Controls.Orientation?; 
          if (o.HasValue) 
          { 
           return (System.Windows.Controls.Orientation)o.Value; 
          } 
          else 
          { 
           return Orientation.Horizontal; 
          } 
         } 
         set { SetValue(OrientationProperty, value); } 
        }  
    
  • 回答

    4

    錯誤消息說明了這一切。該as運營商只能用一個類型,可爲空(引用類型,或Nullable<T>),使用,因爲它會返回的值或者是演員,或者爲null。

    什麼你要使用它是一個枚舉。

    只需使用一個常規演員:

    get { return (System.Windows.Controls.Orientation) GetValue(OrientationProperty); } 
    

    原因:

    1. 你在你的DependencyProperty.Register電話,elimin定義默認值阿婷任何默認空值
    2. 你的DependencyProperty是typeof(Orientation),不允許空值
    3. 你的類的屬性定義爲Orientation,不允許空值
    4. 任何試圖通過設置直接調用無效值到SetValue(OrientationProperty, null)將收到一個異常,所以你的屬性getter將永遠不會看到null值,即使它是一個調皮的用戶。
    +0

    打我吧:) – 2010-05-04 16:17:29

    +0

    我剛剛添加了我在代碼中所做的更改。你能評論我的改變嗎?我應該直接施放還是使用我使用的方法? – byte 2010-05-04 16:19:34

    +0

    只需使用演員。你的財產不允許爲空值。 (您沒有將依賴項屬性定義爲Orientation?,也沒有將您的屬性本身定義爲Orientation?,因此不需要as關鍵字。特別是因爲您在依賴項屬性定義中提供了Orientation.Horizo​​ntal的默認值,所以沒有定義可空性。 – 2010-05-04 16:25:48