Jacob Alley
Jacob Alley

Reputation: 834

Mvvm Unchecking a Checked Box in an underlying Listbox object

I have a listview that's item source is databound to an observable collection of a custom datatype. Each object in the list has the property DisplayName (string) and IsChecked (bool), among others. The data template essentially is :

<CheckBox VerticalAlignment="Center"
          Content="{Binding DisplayName}"
          IsChecked="{Binding IsChecked}"/>

When I check the boxes, I am able to determine, easily, the underlying items that now have been checked. However in the viewmodel, if i wish to uncheck an item, it does not seem to work going the other way.

I have NotifyProperty change implemented in the setter for the observable collection, but do i need to do something special for the bool?

In the Viewmodel, the following code is where I attempt to uncheck the checked checkboxes (as kind of a refresh after a command has run):

foreach (var bill in AllBills)
{
    bill.IsChecked = false;
}

Upvotes: 0

Views: 417

Answers (2)

I have NotifyProperty change implemented in the setter for the observable collection, but do i need to do something special for the bool?

Yes. When you give your collection property a new collection, you raise PropertyChanged for that property. What does that have to do with property values changing on an item in the collection? Nothing at all. When you set IsChecked on one of those items, is there any imaginable way for that code to hit the setter for your collection property? Nope.

Your items in the collection must themselves implement INotifyPropertyChanged, and the setter for IsChecked must raise PropertyChanged when the value of IsChecked changes. If you did that for the collection property, I expect you already know how. But shoot me a comment if you run into any snags.

One of the tough parts of the WPF learning curve is developing a reliable intuitive sense of the borderline between things that just happen by secret framework rainbow pony magic, and things you have to do yourself. One spot on that borderline is where you're standing right now.

Upvotes: 2

Ricardo Serra
Ricardo Serra

Reputation: 374

If you implement INotifyPropertyChanged in your viewmodel, and are firing the event in IsChecked property, then just change your checkbox to:

<CheckBox VerticalAlignment="Center"
      Content="{Binding DisplayName}"
      IsChecked="{Binding IsChecked, Mode=TwoWay}"/>

Upvotes: 0

Related Questions