title: WinUI 3 How to Bind Command to ViewModel property when using a DataTemplate?
body: <p>I am using a <code>Grid</code> called <code>MainGrid</code> to position an <code>ItemsRepeater</code> whose <code>ItemsSource</code> is bound to an <code>ObservableCollection</code> within my <code>ViewModel</code>.</p>
  <pre><code>&lt;muxc:ItemsRepeater
      ItemsSource=&quot;{Binding Path=Molts}&quot;
      Layout=&quot;{StaticResource VerticalStackLayout}&quot;
      ItemTemplate=&quot;{StaticResource MoltTemplate}&quot;&gt;
  &lt;/muxc:ItemsRepeater&gt;
  </code></pre>
  <p>I have created a <code>DataTemplate</code></p>
  <pre><code>&lt;DataTemplate x:Key=&quot;MoltTemplate&quot;&gt;
      &lt;StackPanel Orientation=&quot;Horizontal&quot;&gt;
          &lt;TextBlock x:Name=&quot;text&quot; Text=&quot;{Binding ID}&quot;&gt;&lt;/TextBlock&gt;
          &lt;Button Command=&quot;{Binding DisplayAvailAIsCommand}&quot; CommandParameter=&quot;{Binding ElementName=text, Path=Text}&quot;&gt;Add&lt;/Button&gt;
      &lt;/StackPanel&gt;
  &lt;/DataTemplate&gt;
  </code></pre>
  <p>which has a <code>TextBox</code> and <code>Button</code>. I want the <code>Button</code> to fire a command in my <code>ViewModel</code> but items within the <code>ItemsRepeater</code> have their <code>DataContext</code> set to their <code>Model</code> class and not the <code>ViewModel</code>. <a href="https://www.kevindockx.com/mvvm-challenge-binding-to-a-command-from-inside-an-itemscontrol-datatemplate/" rel="nofollow noreferrer">I found this post</a> which states that I can change the <code>Command</code> of my <code>Button</code> to set the <code>DataContext</code> to my <code>ViewModel</code> by setting <code>ElementName</code> to a UI element that has as its <code>DataContext</code> the <code>ViewModel</code></p>
  <pre><code>&lt;Button Command=&quot;{Binding DataContext.DisplayAvailAIsCommand, ElementName=MainGrid}&quot; CommandParameter=&quot;{Binding ElementName=text, Path=Text}&quot;&gt;Add&lt;/Button&gt;
  </code></pre>
  <p>The constructor of my window sets the <code>DataContext</code> of the <code>MainGrid</code> like this</p>
  <pre><code>public MainWindow()
  {
      this.InitializeComponent();
      MainGrid.DataContext = new MoltViewModel();
  }
  </code></pre>
  <p>However, this does not work and the command does not fire. What am I doing wrong?</p>