Skip to content

Instantly share code, notes, and snippets.

@Ball
Created August 16, 2013 13:39
Show Gist options
  • Save Ball/6250059 to your computer and use it in GitHub Desktop.
Save Ball/6250059 to your computer and use it in GitHub Desktop.
Cross-Threading binding updates with WPF for RPH. I have no idea if this is best practice, but it seems to work.
namespace MyApplication {
public partial class MainWindow
{
private readonly ViewModel _vm;
private bool _close;
public MainWindow()
{
InitializeComponent();
_vm = new ViewModel();
DataContext = _vm;
var thread = new Thread(SomeMethod);
thread.Start();
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Window.Closing"/> event.
/// </summary>
/// <param name="e">A <see cref="T:System.ComponentModel.CancelEventArgs"/> that contains the event data.</param>
protected override void OnClosing(CancelEventArgs e)
{
_close = true;
base.OnClosing(e);
}
private void SomeMethod()
{
for (var i = 0;! _close; i++)
{
Thread.Sleep(TimeSpan.FromSeconds(2));
_vm.SomeText = String.Format("{0} many times", i);
}
}
}
}
<Window x:Class="MyApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Label Content="{Binding SomeText}"/>
</Window>
namespace MyApplication {
public class ViewModel : INotifyPropertyChanged
{
private string _someText;
public string SomeText
{
get { return _someText; }
set
{
if (_someText != value)
{
_someText = value;
OnPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment