Benutzer:MovGP0/WinForms
Zur Navigation springen
Zur Suche springen
MovGP0 | Über mich | Hilfen | Artikel | Weblinks | Literatur | Zitate | Notizen | Programmierung | MSCert | Physik |
Windows Forms[Bearbeiten | Quelltext bearbeiten]INotifyPropertyChanged[Bearbeiten | Quelltext bearbeiten]
public partial class MyForm : Form
{
private readonly MyController _controller;
public MyForm()
{
InitializeComponent();
_controller = new MyController(action => Invoke(action)); // call Form.Invoke to update interface
currentTimeLabel.DataBindings.Add("Text", _controller, "Status");
}
private void OnClickUpdateButton(object sender, EventArgs e)
{
_controller.ChangeStatus();
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
_controller.SynchronousInvoker = null; // unregister delegate to prevent controller to invoke UI after it is closed
base.OnFormClosing(e);
}
}
class MyController : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
private readonly Timer _timer;
public Action<Action> SynchronousInvoker { get; set; }
private string _status;
public string Status
{
get { return _status; }
set
{
_status = value;
OnPropertyChanged();
}
}
public MyController(Action<Action> synchronousInvoker)
{
SynchronousInvoker = synchronousInvoker;
var startIn = TimeSpan.FromSeconds(1);
var repeatEvery = TimeSpan.FromSeconds(1);
_timer = new Timer(d => ChangeStatus(), null, startIn, repeatEvery);
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
SynchronousInvoker?.Invoke(() => PropertyChanged(this, new PropertyChangedEventArgs(propertyName)));
}
public void ChangeStatus()
{
Status = DateTime.Now.ToString(CultureInfo.CurrentUICulture);
}
}
Quellen[Bearbeiten | Quelltext bearbeiten]
|