【发布时间】:2014-01-24 06:04:56
【问题描述】:
我有一个ListView,在 XAML 中将 SelectionMode 设置为 Single,并希望在代码隐藏中以编程方式取消选择所选项目,我试图通过 MenuFlyout->Closed 事件处理程序中的这一行来完成(每个ListViewItem 都附有一个MenuFlyout):
NotationListView->SelectedIndex = -1;
很遗憾,这不起作用并且应用程序崩溃了。任何其他值都有效并选择相应的ListViewItem,但-1 并没有达到我的预期。
我该怎么做?
编辑:我目前的解决方法
ListView 的 XAML 定义(缩短):
<ListView x:Name="NotationListView"
SelectionMode="None"
IsItemClickEnabled="True"
ItemClick="NotationListView_ItemClicked"/>
NotationListView_ItemClicked() 的 C++/CX 定义(缩写):
ListViewItem^ item = (ListViewItem^) ((TextBlock^) e->ClickedItem)->Parent;
item->Foreground = ref new SolidColorBrush(Colors::Green);
Flyout::ShowAttachedFlyout(item);
selectedItem = item;
selectedItem 只是在存储所选项目的 xaml.h 文件中声明的变量。这样,我可以在MenuFlyoutItems 的 Click-EventHandlers 中轻松使用它。
现在您可能会注意到,我没有任何方法可以访问我迫切需要的单击项目的索引。但是因为所有ListViewItems 都是以编程方式创建的,所以我可以将其添加到创建的末尾:
auto items = NotationListView->Items;
Box<unsigned int>^ indexBox = ref new Box<unsigned int>(items->Size);
item->Tag = indexBox;
items->Append(item);
现在我只需使用该行即可获得每个项目的索引
unsigned int i = ((Box<unsigned int>^)selectedItem->Tag)->Value;
NotationFlyout_Closed()的C++/CX定义:
这很简单。
if (selectedItem){
selectedItem->Foreground = ref new SolidColorBrush(Colors::Black);
selectedItem = nullptr;
}
【问题讨论】:
标签: windows windows-8 windows-store-apps winrt-xaml c++-cx