2010-08-14 6 views
3

저는 WPF와 관련하여 C#과 완전한 초보자 인 초심자입니다. 아마 그것은 프로들을위한 아주 기본적인 질문 일뿐입니다. 나와 함께 견뎌주세요.WPF - 런타임 업데이트 바인딩 질문

버튼 클릭과 같은 추가 트리거없이 런타임에 텍스트가 변경된 동적 텍스트 블록을 표시해야합니다. 어떤 이유로 (분명히 개념에 대한 나의 불충분 한 이해) textblock은 비어 있습니다.

<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); 
     } 
    } 
} 

감사합니다,

세레스

답변

4

에서 그것을 될 수

XAML은 간단합니다 바인딩을 작동시키기 위해서는 윈도우의 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"; 
} 

이렇게하면 TextBox가 성공적으로 업데이트되어야합니다.

로드 된 이벤트에서 Thread.Sleep()을 사용하면 프로그램이 시작될 때 잠깐 멈추게된다는 것을 지적하기 위해 WPF DispatcherTimer을 사용하여 1 초 지연을 만드는 것이 더 좋습니다.

희망 하시겠습니까?

+0

그렇습니다! 고마워요! – Ceres