title: (WPF/C#) Binding to an object inside a method
body: <p>In my quest to understand DataContext and bindings better, I have tried to make an example where a TextBlock displays a property of an object, where the property value is decided by a DispatcherTimer. However, the TextBlock will not display any values.</p>
  
  <p>MainWindow.xaml:</p>
  
  <pre><code>&lt;Window x:Class="SfGauge.MainWindow"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      mc:Ignorable="d"
      Title="MainWindow" Height="350" Width="525"&gt;
  &lt;Grid DataContext="{Binding myObj, Mode=TwoWay}"&gt;
      &lt;TextBlock Text="{Binding RandomVal}"&gt;
      &lt;/TextBlock&gt;
  &lt;/Grid&gt;
  </code></pre>
  
  <p></p>
  
  <p>MainWindow.xaml.cs</p>
  
  <pre><code>public partial class MainWindow : Window
  {
      randomValue myObj = new randomValue();
      public MainWindow()
      {
          InitializeComponent();
  
          DispatcherTimer aTimer;
          aTimer = new DispatcherTimer();
  
          aTimer.Interval += TimeSpan.FromSeconds(1);
  
          aTimer.Tick += Timer_Tick;
  
          aTimer.Start();
  
  
      }
   private void Timer_Tick(object sender, EventArgs e)
          {
              Dispatcher.Invoke(() =&gt;
              {
  
                  myObj.giveRandom();
              });   
         }
  
  }
  public class randomValue : ObservableObject
  {
      Random r = new Random();
      private int randomval;
      public int RandomVal { get
          {
              return randomval;
          }
          set
          {
              SetProperty(ref randomval, value);
          }
     }
      public void giveRandom()
      {
          RandomVal = r.Next(0, 100);
      }
      public randomValue()
      {
          RandomVal = 0;
      }
  }
  </code></pre>
  
  <p>ObservableObject.cs</p>
  
  <pre><code>public class ObservableObject : INotifyPropertyChanged
  {
      public event PropertyChangedEventHandler PropertyChanged;
   
      protected void OnPropertyChanged([CallerMemberName] string propName = null)
      {
          var handler = PropertyChanged;
          if (handler != null)
          {
              handler(this, new PropertyChangedEventArgs(propName));
          }
      }
   
      protected bool SetProperty&lt;T&gt;(ref T storage, T value,
          [CallerMemberName] String propertyName = null)
      {
          if (Equals(storage, value)) return false;
          storage = value;
          OnPropertyChanged(propertyName);
          return true;
      }
  }
  </code></pre>