2013-07-24 45 views
1

我有一種情況,我需要攔截WPF嘗試設置綁定到文本框的屬性的值,並更改實際存儲的值。基本上,我允許用戶在TextBox中輸入複雜的值,但會自動將其解析爲組件。在PropertyChangedCallback期間更新綁定屬性的值

一切正常,除非我無法獲取用戶界面來刷新並向用戶顯示新計算的值。

視圖模型

public class MainViewModel : INotifyPropertyChanged 
{ 
    private string serverName = string.Empty; 

    public event PropertyChangedEventHandler PropertyChanged; 

    public string ServerName 
    { 
    get 
    { 
     return this.serverName; 
    } 
    set 
    { 
     this.serverNameChanged(value); 
    } 
    } 

    private void NotifyPropertyChanged(String propertyName) 
    { 
    if (this.PropertyChanged != null) 
    { 
     this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
    } 
    } 

    private void serverNameChanged(string value) 
    { 
    if (Uri.IsWellFormedUriString(value, UriKind.Absolute)) 
    { 
     var uri = new Uri(value); 
     this.serverName = uri.Host; 
     this.NotifyPropertyChanged("ServerName"); 

     // Set other fields and notify of property changes here... 
    } 
    } 
} 

查看

<TextBox Text="{Binding ServerName}" /> 

當用戶按鍵/糊劑/等。在「服務器名稱」文本框中輸入完整的URL並跳出,視圖模型代碼將運行,視圖模型中的所有字段都將正確設置。將綁定到UI的所有其他字段刷新並顯示。但是,即使ServerName屬性返回正確的值,屏幕上顯示的Text也是舊值。

有沒有辦法強制WPF採取我的新屬性值,並刷新顯示,而在「源屬性更改」過程中?

注:

我也試圖做一個ServerNameDependencyProperty做的工作在實際PropertyChangedCallback但結果是一樣的。

+0

我無法重現您的問題。如果在NotifyPropertyChanged(「ServerName」)之後註釋掉所有代碼,它會起作用嗎?通常你可以使用Dispatcher.CurrentDispatcher.BeginInvoke(new Action(()=> this.NotifyPropertyChanged(「ServerName」)))來實現這一點。 –

+0

您是否在輸出窗口中看到任何錯誤? – McGarnagle

+0

@BillZhang實際工作(通過調度程序運行通知);你可以做出答案,我可以接受嗎? –

回答

0

正如Bill Zhang所指出的那樣,實現這個目標的方法是通過調度員來運行NotifyPropertyChanged;這會導致事件在當前事件結束後運行,並正確更新顯示。

Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => 
    this.NotifyPropertyChanged("ServerName"))) 
相關問題