2016-07-05 2 views
0

문자열을 텍스트 상자로 바인딩하고 싶습니다. 문자열은 지속적으로 스레드에서 업데이트되는 :지속적으로 문자열을 텍스트 상자로 바꿉니다.

나중에 바인딩 선언에
String inputread; 

    public event PropertyChangedEventHandler PropertyChanged; 

    public string InputRead 
    { 
     get { return inputread; } 
     set 
     { 
      if (Equals(inputread, value) == true) return; 
      inputread = value; 
      this.OnPropertyChanged(nameof(this.inputread)); 
     } 


    } 
    void threadFunc() 
    { 
     try 
     { 
      while (threadRunning) 
      { 
       plc.Read(); 
       InputRead =plc.InputImage[1].ToString(); 
       MessageBox.Show(InputRead); 
      } 
     } 
     catch (ThreadAbortException) 
     { 
     } 
    } 
    protected void OnPropertyChanged(string name) 
    { 
     PropertyChangedEventHandler handler = PropertyChanged; 
     if (handler != null) 
     { 
      handler(this, new PropertyChangedEventArgs(name)); 
     } 
    } 

:이 (텍스트 상자가 완전히 비어)는 작동하지 않는 이유

Binding bind = new Binding("InputRead"); 
bind.Mode = BindingMode.OneWay; 
BindingOperations.SetBinding(newtextbox, TextBox.TextProperty, bind); 

나는 문제의 그 부분을 이해 스레드를 실행할 때마다 새로 고치지 않기 때문입니다. 어떻게해야합니까? 또한 바인딩 선언에 결함이있는 것으로 판단됩니다.

데이터 바인딩에 대한 MSDN 기사를 읽었을 때 도움이되었습니다.
나는 그것이 내가 이전까지 Stackoverflow의 도움으로, 지금까지 아무런 성공도 얻지 못했다.

편집 : 코드를 약간 편집했지만 아직 텍스트 상자는 비어 있습니다 (0이 아님). 나는 wpf를 사용하고있다! 쉬울 경우 다른 사람이 나를 dispatcher.invoke를 사용하도록 유도 할 수 있습니까?

감사합니다.

+0

재산에 TextBox을 결합해야합니까? 'Winforms','WPF' – Fabio

+0

wpf, – zadrian

+0

_ 누군가가 dispatcher.invoke_를 사용하도록 안내 할 수 있습니다. Wpf는 크로스 스레드 안전합니다. 발생 된 PropertyChanged 이벤트는 UI 스레드로 마샬링됩니다. – Fabio

답변

0

threadFunc() 함수에서 값을 직접 inputread (소문자)으로 설정하면 필드이고 OnPropertyChanged을 호출하지 않습니다. threadFunc()에서 코드를 변경할 수 있습니다. InputRead=plc.InputImage[1].ToString(); 잘 작동되기를 바랍니다.

+0

문제가 있다고 생각합니다. 아마도 당신은 DataContext를 설정하는 것을 잊었을 것입니다. 'InputRead'에 바인딩하지만 'InputRead'가 어디에 있는지 컴파일러에게 말하지 않습니다. 그래서 바인딩 선언에이 줄을 추가하면 도움이 될 수 있습니다. DataContext = new <클래스에 InputRead>()가 있습니다. – tandat

0

당신은 속성을 만들고 UI 프레임 워크 당신은 무엇을 사용하고있다

private string _Inputed; 
public string Inputed 
{ 
    get { return _Inputed; } 
    set 
    { 
     if(Equals(_Inputed, value) == true) return; 
     _Inputed = value; 
     this.OnPropertyChanged(nameof(this.Inputed)); 
    } 
} 

void threadFunc() 
{ 
    try 
    { 
     while (threadRunning) 
     { 
      plc.Read(); 
      this.Inputed = plc.InputImage[1].ToString(); 
     } 
    } 
    catch (ThreadAbortException) 
    { 
    } 
} 

public event PropertyChangedEventHandler PropertyChanged; 
protected void OnPropertyChanged(string name) 
{ 
    PropertyChangedEventHandler handler = PropertyChanged; 
    if (handler != null) 
    { 
     handler(this, new PropertyChangedEventArgs(name)); 
    } 
} 

XAML

<TextBlock Text="{Binding Path=Inputed}"/> 
+0

감사합니다! 속성에 텍스트 상자를 어떻게 바인딩합니까? 내 해결책이 좋지 않니? 나는 원래의 질문을 편집하여 내가있는 곳을 보여줄 것이다. – zadrian

관련 문제