Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wpf checkbox list not updating

I have the following ui items - one checkbox list and one checkbox with toggle all checkboxes in that list -

<DockPanel>
    <CheckBox
        Name="SelectCheckboxes"
        Command="{Binding ToggleCheckBoxes}"
        Content="Whatever"/>
</DockPanel>
<DockPanel>
    <ListBox Name="MyListBox"
             ItemsSource="{Binding Path=MyProperty, Mode=TwoWay}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <CheckBox Name="MyCheckBox"
                          Content="{Binding myvalue}"
                          Tag="{Binding mycode}"
                          IsChecked="{Binding Path=isChecked, Mode=TwoWay}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</DockPanel>

And here is the MyProperty property -

public ObservableCollection<SomeEntity> MyProperty
{
    get { return _someEntities; }
    set
    {
        if (value == _someEntities)
            return;

        _someEntities = value;
        base.OnPropertyChanged("MyProperty");
    }
}

And here is a command ToggleCheckBoxes -

public ICommand ToggleCheckBoxes
{
    get
    {
        if (_toggleCheckBoxesCommand == null)
        {
            _toggleCheckBoxesCommand = new RelayCommand(
                param => this.toggleCheckBoxes()
                );
        }
        return _toggleCheckBoxesCommand;
    }
}

void toggleCheckBoxes()
{
    foreach (var i in MyProperty)
    {
        if (i.isChecked)
            i.isChecked = false;
        else
            i.isChecked = true;
    }
}

When I click on the checkbox to toggle the checkboxes, I can look at the property in the code and see that the isChecked property is changed, but the ListBox does not update to reflect that all items are checked/unchecked.

Does anyone see anything that I am missing that might cause the ListBox not to update?

Thnaks for any thoughts.

like image 237
czuroski Avatar asked Jul 29 '11 13:07

czuroski


1 Answers

Make sure that your isChecked member is actually a property and that SomeEntity implements INotifyPropertyChanged. Something like:

public class SomeEntity : INotifyPropertyChanged {
    private bool _isChecked;
    public bool isChecked
    {
        get { return _isChecked; }
        set
        {
            if (value == _isChecked)
                return;

            _isChecked= value;
            this.NotifyPropertyChanged("isChecked");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(String info)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(info));
    }
}
like image 53
CodeNaked Avatar answered Oct 21 '22 03:10

CodeNaked