How can I change the DataTemplate for the SelectedItem of ListView in UWP project? I'm trying to use the DataTemplateSelector but the problem is that SelectTemplateCore is called only one time.
This what I have tried:
MyTemplateSelector class
public class MyTemplateSelector : DataTemplateSelector
{
public DataTemplate DefaultTemplate { get; set; }
public DataTemplate SelectedItemTemplate { get; set; }
protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
{
var cont = container as ListViewItem;
if (cont != null)
{
FrameworkElement elemnt = container as FrameworkElement;
if (cont.IsSelected)
{
return SelectedItemTemplate;
}
else
{
return DefaultTemplate;
}
}
else
return DefaultTemplate;
}
}
Resources of the page
<Page.Resources>
<DataTemplate x:Key="DefaultTemplate">
<Grid Height="44">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="44" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<SymbolIcon Grid.Column="0" Symbol="{Binding Icon, Mode=OneWay}" Foreground="Black"
Height="40" Width="40" Margin="2"/>
<TextBlock Grid.Column="1" Text="{Binding Name, Mode=OneWay}" FontSize="16" VerticalAlignment="Center" Foreground="Black" />
</Grid>
</DataTemplate>
<DataTemplate x:Key="SelectedItemTemplate">
<Grid Height="44" Background="Black">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="44" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<SymbolIcon Grid.Column="0" Symbol="{Binding Icon, Mode=OneWay}" Foreground="Black"
Height="40" Width="40" Margin="2"/>
<TextBlock Grid.Column="1" Text="{Binding Name, Mode=OneWay}" FontSize="16" VerticalAlignment="Center" Foreground="Black" />
</Grid>
</DataTemplate>
<local:DefaultTemplateSelector x:Key="TemplateSelector"
DefaultTemplate="{StaticResource DefaultTemplate}"
SelectedItemTemplate="{StaticResource SelectedItemTemplate}"/>
</Page.Resources>
ListView
<ListView x:Name="MyListView" ItemContainerStyle="{StaticResource DefaultStyle}" ItemTemplateSelector="{StaticResource TemplateSelector}">
</ListView>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…