I have a Boolean list that is bound to, displaying a list of checkboxes.
I now want to update a Label showing how many of the checkboxes are checked. This must update whenever any checkbox is checked.
I'm struggling as I don't know what to bind the checkbox to, so that I can update the string the label is bound to.
To do this, I think I need to bind each checkbox to a Command, which is working. However, I can't work out how to update the label. If there's a simpler way to do this (I'm sure there is) please let me know.
public class CheckBoxBoolean : INotifyPropertyChanged
{
public bool CheckBoxChecked
{
get { return _isChecked; }
set
{
_isChecked = value;
OnPropertyChanged("CheckBoxChecked");
}
}
public CheckBoxBoolean(bool isChecked)
{
_isChecked = isChecked;
}
private bool _isChecked = false;
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
<StackPanel Grid.Row="0" Grid.Column="1">
<ItemsControl ItemsSource="{Binding Path=Patterns1}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Path=CheckBoxChecked, Mode=TwoWay}" Command="{Binding Path=DataContext.CheckBoxChanged, RelativeSource={RelativeSource AncestorType=ItemsControl}}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
private ICommand _checkBoxChanged;
public string Percentage1 { get; set; }
public ICommand CheckBoxChanged
{
get
{
if(_checkBoxChanged == null)
{
_checkBoxChanged = new CheckBoxChanging(Patterns1);
}
return _checkBoxChanged;
}
}
public class CheckBoxChanging : ICommand
{
public event EventHandler CanExecuteChanged;
private readonly ObservableCollection<CheckBoxBoolean> _Patterns;
public CheckBoxChanging(ObservableCollection<CheckBoxBoolean> items)
{
_Patterns = items;
}
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
int i = 0;
foreach (CheckBoxBoolean chk in _Patterns)
{
if (chk.CheckBoxChecked)
i++;
}
Debug.WriteLine("UPD - Pattern 1 % = " + i / 16d);
}
}