2014-02-18 4 views
1

WPF 바인딩을 시도하고 있습니다. 작은 응용 프로그램을 작성했지만 문제가 있습니다. UI가 업데이트되지 않습니다. 문제가 무엇UI가 업데이트되지 않는 이유 (WPF)?

namespace WpfApplication1 
{ 
    public partial class MainWindow : Window 
    { 
     MyClass mc; 

     public MainWindow() 
     { 
      InitializeComponent(); 
     mc = new MyClass(this.Dispatcher); 

     text.DataContext = mc; 
    } 

    private void Button_Click(object sender, RoutedEventArgs e) 
    { 
     Task task = new Task(() => 
     { 
      mc.StartCounting(); 
     }); 

     task.ContinueWith((previousTask) => 
     { 

     }, 
     TaskScheduler.FromCurrentSynchronizationContext()); 

     task.Start(); 
    } 
} 

public class MyClass 
{ 
    public int Count { get; set; } 
    public Dispatcher MainWindowDispatcher; 

    public MyClass(Dispatcher mainWindowDispatcher) 
    { 
     MainWindowDispatcher = mainWindowDispatcher; 
    } 

    public void StartCounting() 
    { 
     while (Count != 3) 
     { 
      MainWindowDispatcher.Invoke(() => 
      { 
       Count++;      
      }); 
     } 
    } 
} 

}

:

<Grid> 
    <Button Content="Button" HorizontalAlignment="Left" Margin="345,258,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/> 
    <TextBox x:Name="text" HorizontalAlignment="Left" Height="23" Margin="75,165,0,0" TextWrapping="Wrap" Text="{Binding Path=Count}" VerticalAlignment="Top" Width="311"/> 
</Grid> 

그리고 코드 숨김 : 여기 내 코드입니다. 그리고 내가 이것을 올바르게 작성 했는가? 이것을 할 수있는 더 좋은 방법이 있습니까?

+4

'MyClass'는'[WPF에 윈도우 폼에서 전환 중]의 INotifyPropertyChanged' –

+0

가능한 중복 (http://stackoverflow.com/questions/15681352/transition를 구현해야 ing-from-windows-forms-to-wpf) –

답변

3

양방향 WPF 데이터 바인딩을 지원하려면 데이터 클래스가 Implement the INotifyPropertyChanged interface이어야합니다. 모든

첫째, UI 스레드로 마샬링하여 속성 변경을 알릴 수있는 클래스 만들기 : 다음

public class PropertyChangedBase:INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 

    protected virtual void OnPropertyChanged(string propertyName) 
    { 
     Application.Current.Dispatcher.BeginInvoke((Action) (() => 
     { 
      PropertyChangedEventHandler handler = PropertyChanged; 
      if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); 
     })); 
    } 
} 

을,이에서 MyClass 상속이 있고 Count 속성이있을 때마다 제대로 속성 변경 알림을 인상 변경 :

public class MyClass: PropertyChangedBase 
{ 
    private int _count; 
    public int Count 
    { 
     get { return _count; } 
     set 
     { 
      _count = value; 
      OnPropertyChanged("Count"); //This is important!!!! 
     } 
    } 

    public void StartCounting() 
    { 
     while (Count != 3) 
     { 
      Count++; //No need to marshall this operation to the UI thread. Only the property change notification is required to run on the Dispatcher thread. 
     } 
    } 
} 
+0

대단히 고맙습니다. PropertyChangedBase 클래스는 제가 찾고있는 클래스입니다. – BJladu4

관련 문제