I’m getting an error where chkBox1 does not exist in the current context, anyone has a solution to this?
Here is the XAML:
<ListBox ItemsSource="{Binding Files}" Margin="0,42,0,115" Name="lstBox1">
<ListBox.ItemTemplate>
<DataTemplate >
<CheckBox IsChecked="{Binding IsChecked, Mode=TwoWay}" Content="{Binding FileName}" Name="chkBox1" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Here is the code that has the chkBox1 in it:
private void button2_Click(object sender, RoutedEventArgs e)
{
ViewDiskModel model = this.ContentPanel.DataContext as ViewDiskModel;
if (chkBox1.IsChecked == true)
{
model.DeleteSelectedFiles.Execute(null);
MessageBox.Show("Files Successfully Deleted.");
}
else
{
MessageBox.Show("Please select a file to delete.");
}
}
If there are many Files there will be many check boxes. How would you distinguish between these when you specify a single name?
Do not refer to the View (control) in the ViewModel. Replace the string collection (filename collection) with a collection of File. Make sure the File class has two properties: Name and IsSelected.
Then bind the content of the check box to the Name and the IsChecked Property to the IsSelected property.
That way you only have to check the IsSelected property in the ViewMODEL, not in the view.
Suggestion
XAML:
Then: