2014-07-15 57 views
0

我已經這樣綁定 - 回調被調用兩次

public class StatusProgress : Control 
{ 
    public string Text 
    { 
     get { return (string)GetValue(TextProperty); } 
     set { SetValue(TextProperty, value); } 
    } 
    public static readonly DependencyProperty TextProperty = 
     DependencyProperty.Register("Text", typeof(string), typeof(StatusProgress), 
     new FrameworkPropertyMetadata(null, (d, e) => (d as StatusProgress).TextUpdated(e.OldValue as string))); 

    private void TextUpdated(string text) 
    { 
     Trace.WriteLine("test"); 
    } 
} 

依賴屬性的簡單控制,然後我視圖模型

public class ViewModelPageAnalyse : ViewModelPageBase 
{ 

    private string _progressText; 
    public string ProgressText 
    { 
     get { return _progressText; } 
     set 
     { 
      _progressText = value; 
      OnPropertyChanged(); // base class INotifyPropertyChanged implementation 
     } 
    } 
} 

然後有一個用戶控件(顯示在窗口ContentControl)。用戶控件綁定到查看與數據模板模型(也許這很重要)

而且這是在用戶控制

<local:StatusProgress Text="{Binding ProgressText}"/> 

現在最有趣的部分控制。當在視圖模型中設置/更改ProgressText時,屬性更改回調被調用兩次。我在調試器輸出窗口中看到兩次"test"

更有趣:當視圖改變時,由於某種原因,回調再次調用e.NewValue = null,而沒有什麼直接設置ProgressTextnull

我試過在上升事件之前檢查是否在ProgressText setter中更改了值,試圖單向設置綁定模式,問題仍然是 - 回調被調用兩次具有相同的值,調用堆棧看起來相同,但確實存在很多wpf中的調用都是確定的。

雖然雙槍不是一個真正的問題,它打擾我。用null回調價值是我真正的問題(我認爲他們是相關的)。任何人都知道什麼是錯的?


找到原因的第一個問題的:它是其他控制用Content。在轉換期間,它創建了一個新的Model(因爲ContentViewModel),而不是重新分配現有的用戶控件。完全是我的錯。第二個問題仍然存在,我發現this問題(與不適合我的解決方法)。

需要幫助時,ContentControl中視圖模型改變

的PropertyChanged回調調用默認值。

這意味着nullText在我的情況。任何人?我無法弄清楚它爲什麼叫。如果可以這樣說的話,我的猜測是DataTemplate經理。

回答

-1

試圖改變這一行:

public static readonly DependencyProperty TextProperty = 
    DependencyProperty.Register("Text", typeof(string), typeof(StatusProgress), 
    new FrameworkPropertyMetadata(null, (d, e) => (d as StatusProgress).TextUpdated(e.OldValue as string))); 

與此:

public static readonly DependencyProperty TextProperty = 
    DependencyProperty.Register("Text", typeof(string), typeof(StatusProgress) 
    , new PropertyMetadata("")); 
+0

但是..但是..我需要回調(做一些邏輯和動畫)。您是否可能知道其他解決方案以瞭解依賴項屬性值更改的時間? – Sinatr

+0

我認爲編寫你的邏輯時ProgressText(調用OnPropertyChanged();)的變化比編寫它時更容易DependencyProperty –

+0

ProgressText屬於視圖模型(另一類),這是不可能的。我應該用'MVVM'來標記問題,對不起。 – Sinatr