c# - 避免更新数据后TreeView的折叠效果

标签 c# wpf user-interface treeview prism

我有一个用于显示事件的 TreeView。它工作得很好,但是每次新事件进入并填充树时,树都会再次折叠到原始位置。当刷新时间小于 1 秒并且不允许用户与树中的项目交互时,这是非常烦人的。 有什么办法可以避免这种行为吗?

<TreeView Margin="1" BorderThickness="0" Name="eventsTree" ItemsSource="{Binding EventAlertContainers}" 
              Background="#00000000" ScrollViewer.VerticalScrollBarVisibility="Auto" FontSize="14" 
              VirtualizingStackPanel.IsVirtualizing="True">
    <TreeView.Resources>
        <HierarchicalDataTemplate DataType="{x:Type C:EventAlertContainer}" ItemsSource="{Binding EventAlerts}">
            <StackPanel Orientation="Horizontal">
                <Image Width="20" Height="20" Margin="3,0" Source="Resources\Process_info_32.png" />
                <TextBlock FontWeight="Bold" FontSize="16" Text="{Binding Description}" />
            </StackPanel>
        </HierarchicalDataTemplate>
        <HierarchicalDataTemplate DataType="{x:Type C:EventAlert}" ItemsSource="{Binding Events}">
            <StackPanel Orientation="Horizontal">
                <Image Width="20" Height="20" Margin="0,0" Source="Resources\clock2_32.jpg" />
                <TextBlock FontWeight="DemiBold" FontSize="14" Text="{Binding Name}" />
            </StackPanel>
        </HierarchicalDataTemplate>
        <HierarchicalDataTemplate DataType="{x:Type C:Event}">
            <StackPanel Orientation="Horizontal">
                <Image Width="20" Height="20" Margin="0,0" Source="Resources\Task_32.png" />
                <StackPanel Orientation="Vertical">
                    <TextBlock FontSize="12" Text="{Binding Name}" />
                </StackPanel>
            </StackPanel>
        </HierarchicalDataTemplate>
    </TreeView.Resources>
</TreeView>

最佳答案

如果刷新整个 EventAlertContainers 集合,就会发生这种情况。 WPF 不知道新集合中的项目与旧集合中的项目相同。

不要重新填充,而是保留相同的集合,并注意仅添加和删除已更改的项目。确保您的集合是 ObservableCollection 或支持 INotifyCollecitonChanged,并且仅根据需要进行最少的更改(添加、删除和更新)。

关于c# - 避免更新数据后TreeView的折叠效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8224537/

相关文章:

c# - CommandConverter 无法从 WPF 中的 System.String 转换

java - 更改面板的大小

javascript - 我可以只使用一个请求来填充同一个 html 元素吗?

c# - 如何限制网格列中的文本长度而不限制 Excel 导出中的相同文本

c# - 如何将使用 Activator.CreateInstance 创建的对象句柄解包到基类?

c# - 在数组循环的末尾插入句点

wpf - 默认转换器何时启动?

c# - 如何查看当前用户的密码,c#

c# - WPF+Caliburn.Micro : ComboBox and ListBox not updating with dictionary properly

php - HTML 无法在 Internet 上正确加载,但在 Dreamweaver 上可以正常加载