0

I have a checkbox inside a listview. The listview is bound to an observable collection. When I use the context menu to try to select all Checkboxes, they do not show as checked. What am I doing wrong?

<ListView Grid.Row="1" Grid.Column="0" ItemsSource="{Binding AvailableModels}"
           HorizontalAlignment="Stretch" VerticalAlignment="Stretch" 
           SelectionMode="Extended">
    <ListView.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Select All Models" Command="{Binding 
                      SelectAllModelsAction}" />
            <MenuItem Header="Deselect All Models" Command="{Binding 
                      DeselectAllModelsAction}" />
        </ContextMenu>
    </ListView.ContextMenu>
    <ListView.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <CheckBox IsChecked="{Binding DataContext.IsSelected, 
                          RelativeSource={RelativeSource 
                          FindAncestor, AncestorType={x:Type 
                          ListViewItem}}}" VerticalAlignment="Center" />
                <Label Content="{Binding Name}" Margin="2,0,0,0" />
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

ViewModel

public ObservableCollection<ListItems> AvailableModels
{
    get
    {
        return this.availableModels;
    }

    set
    {
        this.availableModels = value;

        this.NotifyPropertyChanged(m => m.AvailableModels);
    }
}

Context Menu Action

private void SelectAllModels()
{
    foreach (var model in this.AvailableModels)
    {
        model.IsSelected = true;
    }

    this.NotifyPropertyChanged(m => m.AvailableModels);
}

ListItems Object

public class ListItems
{
    public string Name
    {
        get;

        set;
    }

    public object Value
    {
        get;

        set;
    }

    public bool IsSelected
    {
        get;

        set;
    }
}

1 Answer 1

0

ListItems isn't implementing INotifyPropertyChanged so changing IsSelected isn't updating the UI.

Calling NotifyPropertyChanged in SelectAllModels() is unnecessary since the collection itself isn't changed. The NotifyProperyChanged() call in the AvailableModels setter updates the UI when a new collection is set. And ObservableCollection will handle when the collection is modified (items added/removed). However changes to the properties within the ListItems does not update the UI unless they call NotifyPropertyChanged in the setters.

1
  • It worked. Thank you for the explanation. It helped me understand it better, to hopefully not make that mistake again. May 20, 2015 at 0:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.