相关疑难解决方法(0)

在WPF ListView中以编程方式选择项目

我无法弄清楚如何在ListView中以编程方式选择项目.

我正在尝试使用listview的ItemContainerGenerator,但它似乎不起作用.例如,在以下操作之后obj为null:

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

我已经尝试过(基于此处和其他地方的建议)使用ItemContainerGenerator的StatusChanged事件,但无济于事.事件永远不会发生.例如:

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]);
}
Run Code Online (Sandbox Code Playgroud)

这件事的关键在于我只想预先选择ListView中的一些项目.

为了不留下任何东西,ListView使用了一些模板和拖放功能,所以我在这里包含了XAML.本质上,此模板使每个项目成为带有一些文本的文本框 - 当选择任何项目时,将选中该复选框.并且每个项目下面都会有一个小字形以插入新项目(这一切都正常):

<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> …
Run Code Online (Sandbox Code Playgroud)

.net c# wpf listview selecteditem

20
推荐指数
2
解决办法
5万
查看次数

标签 统计

.net ×1

c# ×1

listview ×1

selecteditem ×1

wpf ×1