原文:
Windows 10 UWP开发:如何去掉ListView默认的选中效果
开发UWP的时候,很多人会碰到一个问题,就是ListView在被数据绑定之后经常有个默认选中的效果,就像这样:
而且它不仅会选中,还会触发一次SelectionChanged事件,当然,我们要让ListView可点击,一种流行的做法确实是用SelectionChanged事件,就像这样:
private void StationsList_OnSelectionChanged(object sender, SelectionChangedEventArgs e) { var station = StationsList.SelectedItem as Station; if (null != station) { SelectedStationChanged?.Invoke(this, station); } StationsList.SelectedItem = null; }
但是因为数据绑定之后会被默认选中一项,所以这个事件被直接触发了,用户就会直接进入Item的子页面,ListView会一闪而过,为此我还写过workround:
private void StationSearchResultListControl_OnSelectedStationChanged(object sender, Station station) { if (selectedAllStationListCount > 0) { if (null != station) { Frame.Navigate(typeof(StationDetail), station); } } selectedAllStationListCount++; } // Work around, listview seems got default selected value. private int selectedAllStationListCount;
结果今天发现其实ListView的默认选中效果是可以去掉的,只要把SelectionMode设置为None:
SelectionMode="None"
现在就不会有默认选中项了:
然后把点击的事件从SelectionChanged换成ItemClick,而且一定记得要把IsItemClickEnabled打开:
<ListView x:Name="StationsList" ItemsSource="{Binding Source={StaticResource GroupedStations}}" Margin="-10,0,0,0" SelectionMode="None" HorizontalContentAlignment="Stretch" ItemClick="StationsList_OnItemClick" IsItemClickEnabled="True">
这样后台代码就可以用e.ClickedItem直接获得当前被点击的对象:
private void StationsList_OnItemClick(object sender, ItemClickEventArgs e) { var station = e.ClickedItem as Station; if (null != station) { SelectedStationChanged?.Invoke(this, station); } StationsList.SelectedItem = null; }
并且那个恶心的workround也能去掉了,代码更加有逼格了!