title: Simple, generic way to get a value from a WPF DataContext in code
body: <p>Let's say I have a WPF control that was bound to some DataContext. Now let's say I have some UI code that needs to get some value from the DataContext. How do I do that?</p>
  
  <hr>
  
  <p>I am aware of the following workarounds:</p>
  
  <ol>
  <li><p>Cast the DataContext to its original type, e.g.</p>
  
  <pre><code>var myValue = ((MyViewModel)myControl.DataContext).SomeProperty;
  </code></pre>
  
  <p>or</p>
  
  <pre><code>var myValue = ((DataRowView)myControl.DataContext).Item("SomeDatabaseField");
  </code></pre>
  
  <p>I don't like this, because it means that <em>in my UI code</em> I need information about the type of the underlying data source.</p></li>
  <li><p>Bind the required value to some UI field and extract it from there, e.g.</p>
  
  <pre><code>&lt;Button Click="..." Tag="{Binding SomeProperty}" /&gt;
  </code></pre>
  
  <p>and in code</p>
  
  <pre><code>var myValue = (TypeOfMyValue)myButton.Tag;
  </code></pre></li>
  </ol>
  
  <hr>
  
  <p>Is there some <em>generic</em> way to extract a value from a DataContext, i.e., do whatever <code>Binding</code> does to get the value? I'm looking for something like this:</p>
  
  <pre><code>var myValue = SomeGenericExtractMethod(myControl.DataContext, "SomeProperty");
  </code></pre>
  
  <p>I'm pretty sure that something like this exists (after all, <code>Binding</code> works like this), I just cannot find it...</p>