如何去掉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;
}
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;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询