I have a UserControl “SubjectListView”. The binding is set to “AllSubjects” which is an ObservableCollection inside the SubjectListViewModel. It is used to retrieve the name and execute the command. The name is retrieved, however the command which is also in the SubjectListViewModel is not executed on the button but works on the button which is not dynamically created outside the scope.
Is there a solution?
<StackPanel>
<ItemsControl ItemsSource="{Binding AllSubjects}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Button Width="100" Content="{Binding Name}" <!-- Is working-->
Command="{Binding InvasionCommand}" <!--Is NOT working--> />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Button Content="Check for Invasion" Width="120" Command="{Binding InvasionCommand}" <!-- Is working-->/>
</StackPanel>
The problem is, that
InvasionCommandis in your viewmodel (i think so), but you’re in the actual element of your ItemsSource..For that, I use
ElementSpy, but I think it will work if you use a RelativeSource..Here you have an overview of all possible Bindings: http://www.nbdtech.com/Free/WpfBinding.pdf
Or, if you give your StackPanel the name
Container, you could bind following:Binding ElementName=Container, Path=DataContext