Hello,
I have a list of string and checkboexes. It has two properties one is the ItemName and one is the CheckedStatus. I want this button to be able to check all the checkboxes.
<ItemsControl Name="IC" ItemsSource="{Binding ItemsSorted}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<CheckBox Name="Mycb" IsThreeState="False"
FontSize="12" Foreground="WhiteSmoke"
Content="{Binding ItemName}" IsChecked="{Binding IsChecked}"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Then I have here the button in the same Window but outside the ItemsControl of course
<Button Grid.Row="1" Content="Select All" Name="SelectAll" Style="{StaticResource ButtonStyle}" MinWidth="150" Margin="0,5,20,20" Click="SelectAll_Click"/>
Here is the WindowAViewModel.cs
public WindowAViewModel(string pageTitle, WindowBViewModel windowBViewModel)
{
PageTitle = pageTitle;
MyItems.Add(new MyCustomItemViewModel("Apple", windowBViewModel));
MyItems.Add(new MyCustomItemViewModel("Orange", windowBViewModel));
MyItems.Add(new MyCustomItemViewModel("Banana", windowBViewModel));
}
Here is MyCustomItemViewModel.cs
[ImplementPropertyChanged]
public class MyCustomItemViewModel
{
public string ItemName { get; set; }
public bool IsChecked { get; set; }
public WindowBViewModel WindowBViewModelObj { get; set; }
public MyCustomItemViewModel(string itemName, WindowBViewModel windowBViewModel)
{
ItemName = itemName;
WindowBViewModelObj = windowBViewModel;
}
private void OnIsCheckedChanged()
{
if (IsChecked)
WindowBViewModelObj.MyItems.Add(this);
else
WindowBViewModelObj.MyItems.Remove(this);
}
}
and here is the BaseWindowViewModel.cs
public class BaseWindowViewModel
{
public string PageTitle { get; set; }
private ObservableCollection<MyCustomItemViewModel> _myItems;
public ObservableCollection<MyCustomItemViewModel> MyItems
{
get
{
if (_myItems == null)
{
_myItems = new ObservableCollection<MyCustomItemViewModel>();
_myItemsSorted = CollectionViewSource.GetDefaultView(_myItems);
_myItemsSorted.SortDescriptions.Add(new SortDescription() { PropertyName = "ItemName" });
}
return _myItems;
}
}
private ICollectionView _myItemsSorted;
public ICollectionView MyItemsSorted { get { return _myItemsSorted; } }
}
What I have tried:
I have tried this:
private void SelectAll_Click(object sender, RoutedEventArgs e)
{
foreach (var currentItem in IC.Items)
{
var container = IC.ItemContainerGenerator.ContainerFromItem(currentItem) as FrameworkElement;
var checkBox = container.FindName("Mycb") as CheckBox;
{
checkBox.IsChecked = true;
}
}
}
but threw an exception "System.NullReferenceException: 'Object reference not set to an instance of an object.'"