gpt4 book ai didi

c# - UWP:DataTemplateSelector 和 SelectedItem

转载 作者:行者123 更新时间:2023-11-30 15:18:17 25 4
gpt4 key购买 nike

如何更改 UWP 项目中 ListViewSelectedItemDataTemplate?我正在尝试使用 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>

最佳答案

一种方法是使用 RegisterPropertyChangedCallback监控 IsSelected 的变化属性,然后更新 ContentTemplateSelectorListViewItem手动 -

protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
{
if (container is ListViewItem cont)
{
if (cont.Tag != null && long.TryParse(cont.Tag.ToString(), out var token))
{
cont.UnregisterPropertyChangedCallback(ListViewItem.IsSelectedProperty, token);
}

cont.Tag = cont.RegisterPropertyChangedCallback(ListViewItem.IsSelectedProperty, (s, e) =>
{
cont.ContentTemplateSelector = null;
cont.ContentTemplateSelector = this;
});

if (cont.IsSelected)
{
return SelectedItemTemplate;
}

return DefaultTemplate;
}

return DefaultTemplate;
}

关于c# - UWP:DataTemplateSelector 和 SelectedItem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44249232/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com