如何更改 UWP 项目中 ListView 的 SelectedItem 的 DataTemplate ?我尝试使用 DataTemplateSelector ,但问题是 SelectTemplateCore 只被调用一次。
这就是我的尝试:
MyTemplateSelector类
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;
}
}
页面资源
<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>
答案 0 :(得分:4)
一种方法是使用RegisterPropertyChangedCallback
来监控IsSelected
属性的更改,然后手动更新ContentTemplateSelector
的{{1}} -
ListViewItem