2014-02-18 2 views
1

Я пытаюсь связать WPF. Я написал небольшое приложение, но у меня проблема, мой пользовательский интерфейс не обновляется. Вот мой код:Почему интерфейс не обновляется (WPF)?

<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> 

И фоновый код:

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

}

чем проблема. И я написал это правильно, есть ли лучшие способы сделать это?

+4

'MyClass' необходимо реализовать' INotifyPropertyChanged' –

+0

возможный дубликат [Переход от Windows Forms в WPF] (http://stackoverflow.com/questions/15681352/transition ing-from-windows-forms-to-wpf) –

ответ

3

Для поддержки двустороннего WPF DataBinding ваш класс данных должен быть Implement the INotifyPropertyChanged interface.

Прежде всего, создать класс, который может сообщить об изменениях свойств на сортировочных их в поток пользовательского интерфейса:

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

Смежные вопросы