A lot of people including me has encounter a problem where on UWP apps, if a ListView control is being data binded, it will get a default selected item like this:
It not only will display as selected item, it also fires SelectionChanged event. However, if we want to make ListView clickable, a popular way is to write the SelectionChanged event handler like this:
private void StationsList_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var station = StationsList.SelectedItem as Station;
if (null != station)
{
SelectedStationChanged?.Invoke(this, station);
}
StationsList.SelectedItem = null;
}
But because of this "default selection" behaviour, it will fire our event right after the data bind and take the user away from the page. I've even wrote a workround for this:
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;
Fortunately, I discovered that the default selection behaviour of the ListView can be easily removed. You only need to set SelectionMode to None:
SelectionMode="None"
Now there won't be any item selected by default:
Then, change your SelectionChanged event handler to ItemClick, and enable IsItemClickEnabled in the ListView:
<ListView x:Name="StationsList"
ItemsSource="{Binding Source={StaticResource GroupedStations}}"
Margin="-10,0,0,0"
SelectionMode="None"
HorizontalContentAlignment="Stretch"
ItemClick="StationsList_OnItemClick"
IsItemClickEnabled="True">
Now, we can get the clicked object by ClickedItem event:
private void StationsList_OnItemClick(object sender, ItemClickEventArgs e)
{
var station = e.ClickedItem as Station;
if (null != station)
{
SelectedStationChanged?.Invoke(this, station);
}
StationsList.SelectedItem = null;
}
cjw
ListBox怎么破