列表框在项模板选择器之间更改

本文关键字:选择器 之间 列表 | 更新日期: 2023-09-27 18:36:36

我在ApplicationListBox我用ItemTemplateSelector设计:

TemplateSelector templateSelector = new TemplateSelector();
templateSelector.SongTemplate = Resources["Template"] as DataTemplate;
templateSelector.SongTemplateCached = Resources["TemplateCached"] as DataTemplate;
HistoryList.ItemTemplateSelector = templateSelector;

它们之间的区别在于,如果歌曲是下载还是不下载。

这是列表框的视图模型:

    ObservableCollection<SongItem> songlist;
    public const int MAX_RECENT = 10000;
    public HistoryViewModel()
    {
        NotificationCenterManager.Instance.AddObserver(UpdateCache, AppConst.UPDATECACH);
        List<SongItem> tmpArr = SqlLiteManager.CreateInstance().LoadHistoryFromDatabase();
        songList = new ObservableCollection<SongItem>(tmpArr);
    }
    public ObservableCollection<SongItem> SongList
    {
        get { return songlist; }
    }
    public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
    private void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
    }
    private void UpdateCache(Notification p_notification)
    {
        RaisePropertyChanged("SomeName");
    }

当歌曲完成下载时,将调用UpdateCache方法,但列表框不会更新(将设计从歌曲模板模式更改为歌曲模板缓存)

我该如何解决?

编辑

XAML:

<ListBox ItemsSource="{Binding Path=VideoList}" Name="HistoryList" Style="{StaticResource myListboxStyle}" BorderThickness="0" 
             Template="{DynamicResource ListViewNewTemplate}" Margin="-2,0,0,0" MouseDoubleClick="Mouse_Double_Click" ScrollViewer.CanContentScroll="False">
        <ListBox.Resources>
            <!--Defines a context menu-->
            <ContextMenu x:Key="MyElementMenu">
                <MenuItem Header="Delete from history" Click="MenuItemDelete_Click"/>
            </ContextMenu>
            <!--Sets a context menu for each ListBoxItem in the current ListBox-->
            <Style TargetType="{x:Type ListBoxItem}">
                <Setter Property="ContextMenu" Value="{StaticResource MyElementMenu}"/>
            </Style>
        </ListBox.Resources>
    </ListBox>

选择器:

        public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        string filePath = ApplicationDataPaths.GetRootDataPath() + "''www''CachedContent''";
            string file = video.VideoId + "*.mp4";
            string[] listfiles = System.IO.Directory.GetFiles(filePath, file, System.IO.SearchOption.TopDirectoryOnly);
            if (listfiles.Length > 0)
            {
                return VideoTemplateCached;
            }
            else
            {
                return VideoTemplate;
            }
    }

列表框在项模板选择器之间更改

您更改了歌曲项的属性,但您有一个绑定到包含歌曲项的集合。不会通知它更新 UI,除非您在更改项目时引发CollectionChangedEvent

我想您必须实现像 ObservableCollection 和 Item PropertyChanged 这样的通知才能更新 UI。