views:

1002

answers:

1

I have the following XAML:

<ListView x:Name="debitOrderItems" ItemsSource="{Binding DebitOrderItems}">
  <ListView.ItemTemplate>
    <DataTemplate>
      <CheckBox x:Name="checkbox" Content="{Binding}" IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}, Path=IsSelected}" />
    </DataTemplate>
  </ListView.ItemTemplate>
</ListView>

Binding a list of items works fine and I get a beautiful listview with checkboxes, but I would like to have them all selected immediately. There is a SelectAll() method on the ListView, but when can I call it? DataContextChanged does not work as I link it before I populat the DebitOrderItems on it.

+1  A: 

You can do this in the Loaded event:

public Window()
{
    InitializeComponent();
    Loaded += delegate
    {
        _listView.SelectAll();
    };
}

That said, I'd question your design. Normally you would have a view model for each item in the list, and you would bind the IsChecked property to a property on that view model.

HTH, Kent

Kent Boogaart
Thanks, although I was more hoping for a way to do it in XAML.
Mladen Mihajlovic
The way to do it in XAML is via a view model. Just have IsChecked bound to a property in your view model, and make sure that property defaults to true.
Kent Boogaart
Thanks Kent, I will look at my design and re-evaluate...
Mladen Mihajlovic
I'm a bit confused as to how I would do this with MVVM? I am using Prism and the presenter first model. I do have a model which is populated by the presenter and set on the view. How is this different to the MVVM model. And also what about collections of business entities like a Customer entity?
Mladen Mihajlovic