2010-04-16 55 views
4

我試圖在我的代碼中使用這種依賴屬性,但它給了我錯誤,說默認值類型與屬性'MyProperty'的類型不匹配。 但短應接受0作爲默認值。wpf DependencyProperty短期不接受默認值

如果我試圖給它一個null作爲默認值,它的工作原理,即使它是一個非nullabel類型。 該如何來發生..

public short MyProperty 
{ 
    get { return (short)GetValue(MyPropertyProperty); } 
    set { SetValue(MyPropertyProperty, value); } 
} 

使用的DependencyProperty作爲後備存儲myProperty的。這使得動畫製作,造型,綁定,等等

public static readonly DependencyProperty MyPropertyProperty = 
    DependencyProperty.Register(
     "MyProperty", 
     typeof(short), 
     typeof(Window2), 
     new UIPropertyMetadata(0) 
    ); 

回答

13

問題是C#編譯器將文字值解釋爲整數。你可以告訴它將它們解析爲長或超長(40L是長期的,40UL是超長期的),但是沒有簡單的方法來宣佈短期。

簡單鑄造字面將工作:

public short MyProperty 
{ 
    get { return (short)GetValue(MyPropertyProperty); } 
    set { SetValue(MyPropertyProperty, value); } 
} 

public static readonly DependencyProperty MyPropertyProperty = 
    DependencyProperty.Register(
     "MyProperty", 
     typeof(short), 
     typeof(Window2), 
     new UIPropertyMetadata((short)0) 
    ); 
0
public short MyProperty 
{ 
    get { return (short)GetValue(MyPropertyProperty); } 
    set { SetValue(MyPropertyProperty, value); } 
} 


// Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc... 
     public static readonly DependencyProperty MyPropertyProperty = 
      DependencyProperty.Register("MyProperty", typeof(short), typeof(Window2), new UIPropertyMetadata((short)0)); 
    } 

這似乎是工作...貌似0將被解釋爲int..but爲什麼..?

+2

UIPropertyMetadata構造函數獲取目標參數,所以沒有轉換。 C#規範說整數文字用於寫入int,uint,long和ulong類型的值。當你在沒有強制轉換的情況下寫0時,你會得到一個int。 – majocha 2010-04-16 13:04:16

+2

不要回答你自己的問題。更新它。 – Will 2010-04-16 13:14:47

+0

@Will 如果我更新我的問題,那麼它將不再是一個問題..那麼它將如何利用相同的probs其他人... – biju 2010-04-16 13:26:41