How to collapse child control in listviewitem UWP

前端 未结 1 581
旧时难觅i
旧时难觅i 2021-01-15 23:57

Universal Windows Platform, C#

How can I collapse/expand the child listview of item MainListView listitem from code behind? I have not found anything that works. I\'

1条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-16 00:47

    Here is how i would do it.

    I would create two DataTemplates one to show when selected (Expanded), another when not expanded.

    Below is my ViewModel.

    public class MyViewModel
    {
        public MyViewModel()
        {
            myItems = new ObservableCollection();
            for(int i=1;i<=10;i++)
            {
                MyItems item = new MyItems();
                item.Name = "Main Item " + i.ToString();
                ObservableCollection subItems = new ObservableCollection();
                for (int j=1;j<=5;j++)
                {
                    subItems.Add(new MySubItems() { Title = "Sub Item " + j.ToString() });
                }
                item.Data = subItems;
                myItems.Add(item);
            }
        }
    
        public ObservableCollection myItems { get; set; }
    }
    
    public class MyItems
    {
        public string Name { get; set; }
        public ObservableCollection Data { get; set; }
    }
    
    public class MySubItems
    {
        public string Title { get; set; }
    }
    

    Below is my MainPage.xaml as requested

    
        
            
        
    
        
            
                
                    
                        
                        
                    
                    
                
            
            
                
                    
                        
                        
                    
                    
                    
                        
                            
                                
                            
                        
                    
                
            
        
    
        
            
                
                    
                
            
        
    
    

    And Below is how my SelectionChanged Event Looks like.

    private int PreviousIndex;
    private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ListView lv = sender as ListView;
    
        if (PreviousIndex >=0)
        {
            ListViewItem prevItem = (lv.ContainerFromIndex(PreviousIndex)) as ListViewItem;
            prevItem.ContentTemplate = Resources["NoSelectDataTemplate"] as DataTemplate;
        }
    
        ListViewItem item = (lv.ContainerFromIndex(lv.SelectedIndex)) as ListViewItem;
        item.ContentTemplate = Resources["SelectDataTemplate"] as DataTemplate;
    
        PreviousIndex = lv.SelectedIndex;
    }
    

    Here is the Output

    0 讨论(0)
提交回复
热议问题