I am using a Grid called MainGrid to position an ItemsRepeater whose ItemsSource is bound to an ObservableCollection within my ViewModel.
<muxc:ItemsRepeater
ItemsSource="{Binding Path=Molts}"
Layout="{StaticResource VerticalStackLayout}"
ItemTemplate="{StaticResource MoltTemplate}">
</muxc:ItemsRepeater>
I have created a DataTemplate
<DataTemplate x:Key="MoltTemplate">
<StackPanel Orientation="Horizontal">
<TextBlock x:Name="text" Text="{Binding ID}"></TextBlock>
<Button Command="{Binding DisplayAvailAIsCommand}" CommandParameter="{Binding ElementName=text, Path=Text}">Add</Button>
</StackPanel>
</DataTemplate>
which has a TextBox and Button. I want the Button to fire a command in my ViewModel but items within the ItemsRepeater have their DataContext set to their Model class and not the ViewModel. I found this post which states that I can change the Command of my Button to set the DataContext to my ViewModel by setting ElementName to a UI element that has as its DataContext the ViewModel
<Button Command="{Binding DataContext.DisplayAvailAIsCommand, ElementName=MainGrid}" CommandParameter="{Binding ElementName=text, Path=Text}">Add</Button>
The constructor of my window sets the DataContext of the MainGrid like this
public MainWindow()
{
this.InitializeComponent();
MainGrid.DataContext = new MoltViewModel();
}
However, this does not work and the command does not fire. What am I doing wrong?