2012-05-14 71 views
6

簡單地說,我可以創造一個WPF控件2個依賴屬性,並把代碼中的每個屬性更改通知更改其他財產(即PropA變更集PropBPropB變更集PropA)。依賴屬性重入(或:爲什麼這個工作)

我認爲這會消失在自己的背後,但WPF似乎很好地處理它。這對我而言非常方便,但我無法在任何地方找到這種行爲。

那麼這是怎麼回事? WPF依賴屬性是否改變通知系統防止重新進入?

代表代碼如下:

XAML

<Window x:Class="WPFReentrancy1.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
     <TextBox Text="{Binding PropB, UpdateSourceTrigger=PropertyChanged}"/> 

    </Grid> 
</Window> 

後面的代碼:

public partial class MainWindow : Window 
    { 

     public string PropA 
     { 
      get { return (string)GetValue(PropAProperty); } 
      set { SetValue(PropAProperty, value); } 
     } 
     public static readonly DependencyProperty PropAProperty = 
         DependencyProperty.Register("PropA", typeof (string), typeof (MainWindow),new UIPropertyMetadata("0", PropAChanged)); 


     public string PropB 
     { 
      get { return (string)GetValue(PropBProperty); } 
      set { SetValue(PropBProperty, value); } 
     } 

     public static readonly DependencyProperty PropBProperty = 
      DependencyProperty.Register("PropB", typeof (string), typeof (MainWindow), new UIPropertyMetadata("", PropBChanged)); 

     private static void PropBChanged(DependencyObject lDependencyObject, DependencyPropertyChangedEventArgs lDependencyPropertyChangedEventArgs) 
     { 
      ((MainWindow) lDependencyObject).PropA = (string) lDependencyPropertyChangedEventArgs.NewValue; 
     } 


     private static void PropAChanged(DependencyObject lDependencyObject, DependencyPropertyChangedEventArgs lDependencyPropertyChangedEventArgs) 
     { 
      ((MainWindow) lDependencyObject).PropB = 
       double.Parse((string) lDependencyPropertyChangedEventArgs.NewValue).ToString("0.000"); 
     } 


     public MainWindow() 
     { 
      InitializeComponent(); 
      DataContext = this; 
      PropA = "1.123"; 
     } 
    } 
+0

沒有具體的答案,但假設:考慮到WPF使沿元素的樹遞歸流和過相關的屬性,它只是「節省「(具體事件)哪些節點已經通過併發出通知,因此如果再次遇到它們,請跳過它們。 – Tigran

回答

3

如果物業改變這些回調,僅啓動,你的代碼完成不創造無限循環不同的值

試試這個,你會得到一個SO例外:

private static readonly Random _random = new Random(); 
private static void PropBChanged(DependencyObject lDependencyObject, DependencyPropertyChangedEventArgs lDependencyPropertyChangedEventArgs) 
{ 
    ((MainWindow)lDependencyObject).PropA = _random.Next().ToString(); 
} 
private static void PropAChanged(DependencyObject lDependencyObject, DependencyPropertyChangedEventArgs lDependencyPropertyChangedEventArgs) 
{ 
    ((MainWindow)lDependencyObject).PropB = _random.Next().ToString(); 
} 
+0

我猜想這個線索就是名字!我假設通知會被解僱,不過我剛剛做了一個快速測試,看起來這正是發生的事情。 – MarcE