2011-07-05 76 views
2

我有以下代碼:依賴屬性回調不工作

private static readonly DependencyProperty IDProperty = DependencyProperty.Register(
      "ID", typeof(int), typeof(DetailDataControl), new PropertyMetadata(-1, new PropertyChangedCallback(IDChanged))); 

    public int ID 
    { 
     get { return (int)GetValue(IDProperty); } 
     set { SetValue(IDProperty, value); } 
    } 

    private static void IDChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
    { 
     // Do something here! 
    } 

我可以看到,當我改變ID,該行的SetValue(IPproperty的叫法),但它不叫IDChanged。

爲什麼?

回答

5

您的代碼是正確的,但PropertyChanged回調將不會被調用,直到它已更改。嘗試在連續的代碼行中將屬性更改爲兩個不同的值,並有一個斷點,您可以看到它已被擊中。我相信它被設置爲-1,因此它不被調用。

+0

位A疑難雜症的,我無法得到它的圓形火第一次,所以我設置的依賴屬性默認爲非標準的默認值價值迫使它提高回調。 –

0

使DP公共靜態只讀。在XAML中設置值時,不使用包裝器,直接使用DP。所以它必須是公開的。

但是...顯然你是從代碼內設置它?在那種情況下,我不知道有什麼問題...但是你可以隨時嘗試。

0

我不知道這是否曾經解決過,但如果您在使用它的XAML文件中設置值,那麼在某些情況下,程序代碼默認值將成爲先例,並且它永遠不會從最初設置在XAML中。所以去除-1所以

private static readonly DependencyProperty IDProperty = DependencyProperty.Register(
      "ID", typeof(int), typeof(DetailDataControl), new PropertyMetadata(-1, new PropertyChangedCallback(IDChanged))); 

成爲

private static readonly DependencyProperty IDProperty = DependencyProperty.Register(
     "ID", typeof(int), typeof(DetailDataControl), new PropertyMetadata(new PropertyChangedCallback(IDChanged)));