LEO
LEO

Reputation: 1

WPF CheckBox IsChecked can't be reset when page(data source) is updated

I have question on the checkbox. First of all, I have a usercontrol which has a list box like this and this user control will be switched by 2 button and then the data source is changed and then the the displayed officer status will be changed:

When I check the checkbox, Officers[0].IsOnDuty will be changed to true. The problem is: When I click another button and switch to another data source, this checked check box is still checked but the Officers[0].IsOnDuty for this data source is false.

How to solve this?

Upvotes: 0

Views: 442

Answers (3)

bitbonk
bitbonk

Reputation: 49649

The problem with your approach is that once you change the ItemsSource (by switching to the next page) your chekcbox is still bound to the item of the first collection. I think this happens because you explicitly use an indexer for the binding Path=Officers[0].IsOnDuty

Your samplelist box xaml does not really make sense. the ItemsSoruce is a OfficerCollection and your ItemTemplate binds to a collection of Officers too. Depending on what you are trying to accomplish you should do one of the following:

If your are just interested in the first officer (as your sample suggest), add a DependencyProperty FirstOfficer (or a INotifyPropertyChanged) property to your collection and bind to it: IsChecked="{Binding Path=Officers.FirstOfficer, Mode=OneWay}"

If you however are interested in all Officers and want checkboxes for all of them you should create a DataTemplate for the Officer type and use this as the ItemTemplate.

Generally you can stay out of a lot of trouble if you stick with MVVM and really tailor your ViewModel objects very close to what the View needs so you can bind your View to the ViewModel in the simplest possible way. Think of the ViewModel as the View you want to build but without a visual representation.

Upvotes: 0

Timores
Timores

Reputation: 14589

The data context of the list box item is an item for your officers collection, not the collection itself. And using a one way binding is incorrect, as the data source (the officer) will not be updated. So change the DataTemplate to:

<CheckBox IsChecked="{Binding Path=IsOnDuty, Mode=TwoWay}" />

Upvotes: 1

LEO
LEO

Reputation: 1

*Here is the list box xaml:

<ListBox ItemsSource="{Binding OfficersCollection}">
<ListBox.ItemTemplate>             
<DataTemplate>                                           
<CheckBox IsChecked="{Binding Path=Officers[0].IsOnDuty, Mode=OneWay}" />

*

Upvotes: 0

Related Questions