uwp - 将 ItemsSource 更新为 ItemsControl 时,SelectedItem 选择丢失

标签 uwp winui winui-3

我有一个自定义的 RibbonGallery 控件,就像在 Excel、MSWord 和 Outlook 中一样。

enter image description here

请引用下面的 Excel RibbonGallery 图片,正常选择仍然存在。

enter image description here

并且我保留了两个ItemsSource,一个用于RibbonGallery View,一个用于Popup,并在RibbonGallery 和Popup View 中排列项目。

当我在 RibbonGallery 中选择一个项目时,SelectedItem(对象)的选择将被更新。如果我打开一个弹出窗口,我从 RibbonGallery 中清除了 ItemsSource(为了避免元素已经添加了另一个元素的子元素问题)并将它重新分配给 Popup ItemsControl。但是打开/关闭弹出窗口后,所选项目的选择被清除。

 private void UpdateItemsSource()
    {
        if (!this.IsDropDownOpen)
        {
            this.popupGalleryItemsControl.ItemsSource = null;
            this.ribbonGalleryItemsControl.ItemsSource = this.ItemsSource;
        }
        else
        {
            this.ribbonGalleryItemsControl.ItemsSource = null;
            this.popupGalleryItemsControl.ItemsSource = this.ItemsSource;
        }
    }



    <ItemsControl x:Name="RibbonGalleryItemsControl"
                                 ItemContainerStyle="{TemplateBinding ItemContainerStyle}"
                                 ItemTemplate="{TemplateBinding ItemTemplate}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <ItemsWrapGrid Orientation="Horizontal" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

<ItemsControl x:Name="PopupItemsControl"
                             ItemContainerStyle="{TemplateBinding ItemContainerStyle}"
                             ItemTemplate="{TemplateBinding ItemTemplate}">
<ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
        <ItemsWrapGrid Orientation="Horizontal" />
    </ItemsPanelTemplate>
</ItemsControl.ItemsPanel>

SelectedItemItemsControl Tapped 事件更新。

任何人请告诉我如何在将新集合更新到控件时保留选择(RibbonGallery 弹出和弹出到 RibbonGallery)?

最佳答案

ItemsControl 无法选择项目,只能显示集合。只有一个Selector或者它的后代之一可以选择项目。没有带有 ItemsControl 的 SelectedItem 的概念。

对于 Selector ,清除itemsource后,SelectedItem已经变为null,例如listView,DataGrid。所以在清除itemsource之前需要先保存之前的SelectedItem,然后将SelectedItem设置为之前的SelectedItem。

关于uwp - 将 ItemsSource 更新为 ItemsControl 时,SelectedItem 选择丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66260186/

相关文章:

c# - 如何在Windows Phone 10中检测电话挂断

c++ - Microsoft Visual C++、Visual Studio,如何修复错误 : identifier "GetAsyncKeyState" is undefined

c# - 桌面上的 UWP 全局 MessageDialog

c# - WinUI 3 调用 ApplicationData.Current() 抛出 System.TypeInitializationException

vb.net - Visual Studio "No certificate found with the supplied thumb print"

c# - 内容对话框不显示 WINUI3

c# - WinUI ProgressRing 在 WASM 上不显示(Uno 2.4)

excel - C# WinUI 3 我无法使用 FileSavePicker 对话框中指定的文件来创建 Excel 报告文件

c# - WinUI 3.0 桌面 - C# 页面导航到现有页面实例