Wybierz element programowo w WPF ListView
Nie mogę dowiedzieć się, jak programowo wybrać element w ListView.
Próbuję użyć elementu ItemContainerGenerator listview, ale po prostu nie działa. Na przykład obj ma wartość null po następującej operacji:
//VariableList is derived from BindingList
m_VariableList = getVariableList();
lstVariable_Selected.ItemsSource = m_VariableList;
var obj =
lstVariable_Selected.ItemContainerGenerator.ContainerFromItem(m_VariableList[0]);
Próbowałem (na podstawie sugestii widocznych tutaj i innych miejsc) użyć zdarzenia StatusChanged ItemContainerGenerator, ale bezskutecznie. Wydarzenie nigdy nie wystrzeliwuje. Na przykład:
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]);
}
Sedno tego wszystkiego polega na tym, że chcę po prostu wybrać kilka elementów z mojego ListView.
W celu nie pozostawiania niczego, ListView używa pewnych szablonów i funkcjonalności Drag / Drop, więc włączam tutaj XAML. Zasadniczo ten szablon sprawia, że każdy element ma pole tekstowe z pewnym tekstem - a po wybraniu dowolnego elementu pole wyboru jest zaznaczone. Każdy element ma również pod sobą mały glif, aby wstawić nowe elementy (a to wszystko działa dobrze):
<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"/>
Więc czego mi brakuje? Jak programowo wybrać jeden lub więcej elementów w ListView?