2010-08-14 69 views
3

我是一個C#新手,也是一個關於WPF的完整新手。對於專業人士來說,這可能是一個非常基本的問題和小菜一碟。請多多包涵。WPF - 運行時更新綁定問題

我需要顯示一個動態文本塊,在運行時更改文本而不需要額外的觸發器,例如按鈕點擊等。出於某種原因(我對這個概念的理解不夠明顯),textblock保持空白。

XAML是簡單,因爲它可以是:

<Window x:Class="WpfApplication1.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" Loaded="Window_Loaded"> 
    <Grid> 
     <TextBlock Text="{Binding Path=Name}"/> 
    </Grid> 
</Window> 

和背後的代碼簡化,以及:預先

using System.ComponentModel; 
using System.Threading; 
using System.Windows; 

namespace WpfApplication1 
{ 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
     } 

     private void Window_Loaded(object sender, RoutedEventArgs e) 
     { 
      Client client = new Client(); 
      client.Name = "Michael"; 
      Thread.Sleep(1000); 
      client.Name = "Johnson"; 
     } 
    } 


    public class Client : INotifyPropertyChanged 
    { 
     private string name = "The name is:"; 
     public event PropertyChangedEventHandler PropertyChanged; 

     public string Name 
     { 
      get 
      { 
       return this.name; 
      } 
      set 
      { 
       if (this.name == value) 
        return; 

       this.name = value; 
       this.OnPropertyChanged(new PropertyChangedEventArgs("Name")); 
      } 
     } 

     protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) 
     { 
      if (this.PropertyChanged != null) 
       this.PropertyChanged(this, e); 
     } 
    } 
} 

謝謝,

的Ceres

回答

4

在爲了使綁定正常工作,需要將窗口的DataContext設置爲所需的對象綁定到,在這個例子中是客戶端對象。

private void Window_Loaded(object sender, RoutedEventArgs e) 
{ 
    Client client = new Client(); 

    // Set client as the DataContext. 
    DataContext = client; 

    client.Name = "Michael"; 
    Thread.Sleep(1000); 
    client.Name = "Johnson"; 
} 

這應該會導致文本框成功更新。

只要指出在加載事件中使用Thread.Sleep()會導致程序在啓動時掛起一秒鐘,更好的方法是使用WPF DispatcherTimer創建1秒延遲。

希望有幫助!

+0

它的確如此!非常感謝! – Ceres 2010-08-16 15:03:23