2011-08-20 3 views
0

작동하지 않습니다 바인딩이 텍스트 상자 (tbCommand)에 문자열 (History.current_commad) 바인딩 내 데이터입니다 :WPF 데이터

 history = new History(); 

     Binding bind = new Binding("Command"); 

     bind.Source = history; 
     bind.Mode = BindingMode.TwoWay; 
     bind.Path = new PropertyPath("current_command"); 
     bind.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; 

     // myDatetext is a TextBlock object that is the binding target object 
     tbCommand.SetBinding(TextBox.TextProperty, bind); 
     history.current_command = "test"; 

history.current_command은 변경되지만 텍스트 상자가 갱신되지 않는 . 뭐가 잘못 되었 니? current_command 그냥 필드이므로이 업데이트되면서 됐어요 때 Binding 알고하지 않기 때문에

감사

+0

'History' 클래스는 어떤 모습입니까? – dlev

+0

공용 클래스 기록 {public string current_command; } – Charlie

답변

1

변화가 TextBlock에 반영이 표시되지 않는 이유입니다. 당신이 할당 할 때, 이제

public class History : INotifyPropertyChanged 
{ 

    public event PropertyChangedEventHandler PropertyChanged; 

    private void NotifyPropertyChanged(string propName) 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(propName)); 
     } 
    } 

    private string _current_command; 
    public string current_command 
    { 
     get 
     { 
      return _current_command; 
     } 
     set 
     { 
      if (_current_command == null || !_current_command.Equals(value)) 
      { 
       // Change the value and notify that the property has changed 
       _current_command = value; 
       NotifyPropertyChanged("current_command"); 
      } 
     } 
    } 
} 

:

그 문제를 해결하는 가장 쉬운 방법은, 당신의 History 클래스 INotifyPropertyChanged를 구현하고있는 속성에 current_command를 변환 한 다음 재산의 세터에 PropertyChanged 이벤트를 발생하는 것입니다 current_command의 값이면 이벤트가 실행되고 Binding은 대상을 업데이트하는 것을 알게됩니다.

속성에 바인딩하려는 클래스가 많은 경우 이벤트 및 도우미 메서드를 기본 클래스로 이동하여 동일한 코드를 반복해서 작성하지 않도록 고려해야합니다 .

+0

고마워요 @dlev 잘 작동합니다. 나는 WPF에서 너무 순진하다. – Charlie

+0

도움이되어 기뻤습니다. – dlev

+0

안녕하세요 @dlev,이 문제 좀 봐 주시겠습니까? http://stackoverflow.com/questions/7130143/wpf-xmlns-the-clr-namespace-uri-refers-to-a-namespace-that-is-not-included-in 내가 데이터 바인딩을하고있는 이유 코드는 xmlns 일을 올바르게 처리 할 수 ​​없습니다. 감사 – Charlie