I have a listbox which binds to a observable collection in my view model (the user controls data context).
DeviceDetector driveDetector;
public DriveSelector()
{
InitializeComponent();
driveDetector = DeviceDetector.Instance;
DataContext = driveDetector;
}
This is my code for my listbox
<ListBox Style="{StaticResource ListBoxStyle}" ItemsSource="{Binding DriveCollection}">
<ListBox.ItemTemplate>
<DataTemplate>
<Button Width="70" Style="{StaticResource DriveButtonStyle}" Command="{Binding SimpleMethod}">
<StackPanel>
<Image Source="{Binding Image}" Style="{StaticResource DriveImageStyle}"/>
<Label Content="{Binding Name}" Style="{StaticResource DriveLabelStyle}"/>
</StackPanel>
</Button>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
I have implemented ICommand and when i bind to the command outside of the listbox like so:
<Button Command="{Binding SimpleMethod}"/>
Everything is fine. However when i try to bind the command to the button's inside the listbox's datatemplate i get this error:
System.Windows.Data Error: 40 : BindingExpression path error: 'SimpleMethod' property not found on 'object' ''DriveInfo' (HashCode=6377350)'. BindingExpression:Path=SimpleMethod; DataItem='DriveInfo' (HashCode=6377350); target element is 'Button' (Name=''); target property is 'Command' (type 'ICommand')
I can see that the datacontext of the button is to the model and so the method 'SimpleMethod' cannot be found. Is there a way that i can bind the command to the datacontext of the listbox itself?