title: Updating Main UI from a usercontrol in WPF with databinding and multithreading
body: <p>I'm just starting with WPF and still don't have all the facts about it clear.</p>
  
  <p>Right now I'm messing around with data binding and threading to update data and represent it on a time basis. I have a mainwindow with 2 textboxs and an usercontrol defined with a thread that starts to run when I click it. In this thread I make calls to 2 properties set in the main window in which I have binded to the textboxes, one by code and another one by xaml.</p>
  
  <p>The problem is that the data binding made by code works while the one made by xaml only works when I update the textbox directly. I have been wondering why, and with some change I made it to work, but I doubt this solution is "correct".</p>
  
  <p>The code is this</p>
  
  <p>MainWindow.xaml</p>
  
  <pre><code>&lt;Window x:Class="WpfApplication1.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" Loaded="Window_Loaded" xmlns:my="clr-namespace:WpfApplication1.Elements"&gt;
      &lt;Grid&gt;
          &lt;TextBox Name="Textbox1" Height="23" HorizontalAlignment="Left" Margin="188,50,0,0" VerticalAlignment="Top" Width="120" Background="White" Text="{Binding Source=my:MainWindow, Path=datavalue}" /&gt;
          &lt;TextBox Name="textBox2" Background="White" Height="23" HorizontalAlignment="Left" Margin="188,101,0,0"  Text="{Binding Path=datavalue2, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}} }" VerticalAlignment="Top" Width="120" /&gt;
  
          &lt;Label Content="Label" Height="28" HorizontalAlignment="Left" Margin="202,152,0,0" Name="label1" VerticalAlignment="Top" /&gt;
          &lt;my:Test Margin="81,138,346,92" x:Name="test1" /&gt;
      &lt;/Grid&gt;
  &lt;/Window&gt;
  </code></pre>
  
  <p>MainWindow.xaml.cs</p>
  
  <pre><code>namespace WpfApplication1
  {
      /// &lt;summary&gt;
      /// Interaction logic for MainWindow.xaml
      /// &lt;/summary&gt;
      public partial class MainWindow : Window, INotifyPropertyChanged
      {
          public MainWindow()
          {
              InitializeComponent();
          }
  
          public event PropertyChangedEventHandler PropertyChanged;
          private int MydataValue;
  
          public int datavalue
          {
              get
              {
                  return MydataValue;
              }
              set
              {
                  MydataValue = value;
  
                  if (PropertyChanged != null)
                  {
                      PropertyChanged(this,
                          new PropertyChangedEventArgs(
                          "datavalue"));
                  }
               }   
          }
  
          private int mydatavalue2;
  
          public int datavalue2
          {
              get
              {
                  return mydatavalue2;
              }
              set{
                  mydatavalue2 = value;
              }
          }
  
  
  
          private void Window_Loaded(object sender, RoutedEventArgs e)
          {
              datavalue2 = 10;
              datavalue = 15;
              Binding bind = new Binding();
              bind.Source = this;
              bind.Mode = BindingMode.TwoWay;
              bind.Path = new PropertyPath("datavalue");
              Textbox1.SetBinding(TextBox.TextProperty, bind);
          } 
      }
  
  }
  </code></pre>
  
  <p>And this is the usercontrol</p>
  
  <p>test.xaml.cs</p>
  
  <pre><code>namespace WpfApplication1.Elements
  {
      /// &lt;summary&gt;
      /// Interaction logic for Test.xaml
      /// &lt;/summary&gt;
      public partial class Test : UserControl
      {
          private Thread t;
          private int resolution;
          private Stopwatch sw,sw2;
          private delegate void changeIconDelegate(long ib);
          private ImageBrush b;
          private Boolean end=false;
          private int count = 0;
  
          public Test()
          {
              InitializeComponent();
              sw = new Stopwatch();
              sw2 = new Stopwatch();
              b = new ImageBrush();
              resolution = 100;
          }
  
          private void UserControl_Loaded(object sender, RoutedEventArgs e)
          {
              b.ImageSource = new BitmapImage(new Uri("pack://application:,,,/DataBinding;component/Images/249137482.png", UriKind.Absolute));
              this.Background = b;
          }
  
          private void UserControl_MouseUp(object sender, MouseButtonEventArgs e)
          {
              t = new Thread(new ThreadStart(ThreadTask));
              t.Start();
          }
  
          private void ThreadTask()
          {
              while (!end)
              {
                  count = count + 1;
                  Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate()
                  {
                      Application.Current.Windows.OfType&lt;MainWindow&gt;().First().datavalue = count;
                      Application.Current.Windows.OfType&lt;MainWindow&gt;().First().datavalue2 = count;
                  });
  
                  Thread.Sleep((resolution - sw.Elapsed.TotalMilliseconds) &gt; 0 ? TimeSpan.FromMilliseconds(resolution - sw.Elapsed.TotalMilliseconds):TimeSpan.FromMilliseconds(1));
                  sw.Reset();
                  sw.Start();
              }
          }
      }
  }
  </code></pre>
  
  <p>If I start the application, as soon as I click on the control, textbox1 begins to update, while textbox2 doesnt, but if I alter textbox2 directly, it throws the notification that it changed, so the data binding is doing properly or so I think.</p>
  
  <p>The questions are:</p>
  
  <ul>
  <li><p>Why does it work if modified directly but not with the the call at the usercontrol's thread? I think its related to the declaration of the textbox2 in the xaml file as it searchs for ancestors, while the usercontrol is a child, but I'm not sure how to approach this.</p></li>
  <li><p>The propertychanged event works for every property of the class, but isnt possible if doing multi-threading that it takes the incorrect value and mistakes an event for another one?</p></li>
  <li><p>I'm sure that i'm not using correctly the specifications of WPF and maybe that's affecting the code in someway, for example when calling mainwindow from the usercontrol :S</p></li>
  </ul>
  
  <p>Sorry for the big quantity of code and questions but I'm starting to like WPF and I get somewhat frustrasted when I don't get things working. I seached for similar questions, but only found people having problems when they had to update the control properties from the Main UI, not the other way, like me</p>