views:

5726

answers:

2

Oh, man. I'm feeling the WPF pain this week. So for my next trick, I'm now unable to figure out how to select an item programmatically in a ListView.

I'm attempting to use the listview's ItemContainerGenerator, but it just doesn't seem to work. For example, obj is null after the following operation:

//VariableList is derived from BindingList
m_VariableList = getVariableList();
lstVariable_Selected.ItemsSource = m_VariableList;
var obj = 
    lstVariable_Selected.ItemContainerGenerator.ContainerFromItem(m_VariableList[0]);

I've tried (based on suggestions seen here and other places) to use the ItemContainerGenerator's StatusChanged event, but to no avail. The event never fires. For example:

m_VariableList = getVariableList();
lstVariable_Selected.ItemContainerGenerator.StatusChanged += new EventHandler(ItemContainerGenerator_StatusChanged);
lstVariable_Selected.ItemsSource = m_VariableList;

...

void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)
{
    //This code never gets called
    var obj = lstVariable_Selected.ItemContainerGenerator.ContainerFromItem(m_VariableList[0]);
}

The crux of this whole thing is that I simply want to pre-select a few of the items in my ListView.

In the interest of not leaving anything out, the ListView uses some templating and Drag/Drop functionality, so I'm including the XAML here. Essentially, this template makes each item a textbox with some text - and when any item is selected, the checkbox is checked. And each item also gets a little glyph underneath it to insert new items (and this all works fine):

<DataTemplate x:Key="ItemDataTemplate_Variable">
<StackPanel>
    <CheckBox x:Name="checkbox"
        Content="{Binding Path=ListBoxDisplayName}"
        IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}, Path=IsSelected}" />
    <Image ToolTip="Insert Custom Variable" Source="..\..\Resources\Arrow_Right.gif" 
        HorizontalAlignment="Left" 
        MouseLeftButtonDown="OnInsertCustomVariable"
        Cursor="Hand" Margin="1, 0, 0, 2" Uid="{Binding Path=CmiOrder}" />
</StackPanel>
</DataTemplate>

...

<ListView Name="lstVariable_All" MinWidth="300" Margin="5"
   SelectionMode="Multiple"
   ItemTemplate="{StaticResource ItemDataTemplate_Variable}"
   SelectionChanged="lstVariable_All_SelectionChanged"
   wpfui:DragDropHelper.IsDropTarget="True" 
   wpfui:DragDropHelper.IsDragSource="True"
   wpfui:DragDropHelper.DragDropTemplate="{StaticResource ItemDataTemplate_Variable}"
       wpfui:DragDropHelper.ItemDropped="OnItemDropped"/>

So what am I missing? How do I programmatically select one or more of the items in the ListView?

Many thanks for your time.

A: 

Here would be my best guess, which would be a much simpler method for selection. Since I'm not sure what you're selecting on, here's a generic example:

var indices = new List<int>();

for(int i = 0; i < lstVariable_All.Items.Count; i++)
{
  // If this item meets our selection criteria 
  if( lstVariable_All.Items[i].Text.Contains("foo") )
    indices.Add(i);
}

// Reset the selection and add the new items.
lstVariable_All.SelectedIndices.Clear();

foreach(int index in indices)
{
  lstVariable_All.SelectedIndices.Add(index);
}

What I'm used to seeing is a settable SelectedItem, but I see you can't set or add to this, but hopefully this method works as a replacement.

Will Eddins
+4  A: 

Bind the IsSelected property of the ListViewItem to a property on your model. Then, you need only work with your model rather than worrying about the intricacies of the UI, which includes potential hazards around container virtualization.

For example:

<ListView>
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Setter Property="IsSelected" Value="{Binding IsGroovy}"/>
        </Style>
    </ListView.ItemContainerStyle>
</ListView>

Now, just work with your model's IsGroovy property to select/deselect items in the ListView.

HTH, Kent

Kent Boogaart
But of course. Databinding. Don't all problems in WPF boil down at some point to databinding? Thanks, Kent.
Paul Prewett