Pau*_*ett 20 .net c# wpf listview selecteditem
我无法弄清楚如何在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>
...
<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"/>
Run Code Online (Sandbox Code Playgroud)
那我错过了什么?如何以编程方式选择ListView中的一个或多个项目?
Ken*_*art 33
将IsSelected属性绑定ListViewItem到模型上的属性.然后,您只需要使用您的模型,而不是担心UI的复杂性,其中包括容器虚拟化的潜在危害.
例如:
<ListView>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="IsSelected" Value="{Binding IsGroovy}"/>
</Style>
</ListView.ItemContainerStyle>
</ListView>
Run Code Online (Sandbox Code Playgroud)
现在,只需使用模型的IsGroovy属性来选择/取消选择中的项目ListView.
其中 'this' 是 ListView 实例。这不仅会改变选择,还会将焦点设置在新选择的项目上。
private void MoveSelection(int level)
{
var newIndex = this.SelectedIndex + level;
if (newIndex >= 0 && newIndex < this.Items.Count)
{
this.SelectedItem = this.Items[newIndex];
this.UpdateLayout();
((ListViewItem)this.ItemContainerGenerator.ContainerFromIndex(newIndex)).Focus();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
47598 次 |
| 最近记录: |