title: WPF: Binding to MainWindow Property
body: <p>I am having an issue with binding to a parent MainWindow property, MainContentVisibility.  I have the following code:</p>
  
  <p><strong>MainWindow.xaml</strong></p>
  
  <pre><code>&lt;Window x:Class="CallTracker.WPF.MainWindow"
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:v="clr-namespace:MyProgram.WPF.Views"
          DataContext="{Binding MainPageViewModel, Source={StaticResource Locator}}"&gt;
  
          &lt;StackPanel&gt;
              &lt;v:CompanyInfoUserControl Width="800" Visibility="{Binding MainContentVisibility, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}" /&gt;
              &lt;v:MainContentUserControl Width="800" Visibility="{Binding Path=MainContentVisibility, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}" /&gt;
          &lt;/StackPanel&gt;   
  &lt;/Window&gt;
  </code></pre>
  
  <p>Currently my two user controls are nothing more than a stack panel with a text block until I figure out this Visibility issue.</p>
  
  <p>I can use Snoop to check my MainPageViewModel and I can see that the property MainContentVisibilty is set to "Collapsed" but the CompanyInfoUserControl shows an issue with its Visibility binding:</p>
  
  <blockquote>
    <p>System.Windows.Data Error: 40 : BindingExpression path error:
    'MainContentVisibility' property not found on 'object' ''MainWindow'
    (Name='')'. BindingExpression:Path=MainContentVisibility;
    DataItem='MainWindow' (Name=''); target element is
    'CompanyInfoUserControl' (Name=''); target property is 'Visibility'
    (type 'Visibility')</p>
  </blockquote>
  
  <p>Can someone explain what I am doing wrong here?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>I tried paul's suggestion and now I get this as the binding error from Snoops:</p>
  
  <blockquote>
    <p>System.Windows.Data Error: 40 : BindingExpression path error:
    'MainContentVisibility' property not found on 'object'
    ''MainPageViewModel' (HashCode=63642613)'.
    BindingExpression:Path=MainContentVisibility;
    DataItem='MainPageViewModel' (HashCode=63642613); target element is
    'CompanyInfoUserControl' (Name=''); target property is 'Visibility'
    (type 'Visibility')</p>
  </blockquote>
  
  <p><strong>SOLUTION</strong></p>
  
  <p>I wasn't actually binding to my data model but rather the XAML object (in this case MainWindow.xaml)  In order to bind to the data I had to add the reference 'DataContext' as follows:</p>
  
  <pre><code>&lt;v:CompanyInfoUserControl Visibility="{Binding DataContext.MainContentVisibility, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" /&gt;
  </code></pre>