Search code examples
c#xamlwinrt-xamlwinui-3winui

Handle SwapChainPanel in ListView


I have my xaml code

<ListView x:Name="ListVideo"
              ItemsSource="{x:Bind ScreenList}"
              VerticalAlignment="Stretch"
              FlowDirection="LeftToRight"
              Grid.Row="1"
              ScrollViewer.VerticalScrollBarVisibility="Hidden"
              ScrollViewer.HorizontalScrollBarVisibility="Hidden">
        <ListView.ItemsPanel>
            <ItemsPanelTemplate>
                <controls:UniformGrid></controls:UniformGrid>
            </ItemsPanelTemplate>
        </ListView.ItemsPanel>
        <ListView.ItemTemplate>
            <DataTemplate>
                <Grid Background="White"
                      BorderBrush="White"
                      BorderThickness="1">
                    <SwapChainPanel x:Name="swapChain"
                                    
                                    VerticalAlignment="Stretch"
                                    HorizontalAlignment="Stretch"/>
                </Grid>
            </DataTemplate>
        </ListView.ItemTemplate></ListView>

with ScreenList is type of ObservableCollection. So the question is how can I add new SwapChainPanel in the ListView?.

I intend to add SwapChainPanel item, and with each item I use DirectX to render video, so i want to get the object SwapChainPanel item in code-behind to process then.

Thanks.


Solution

  • So the question is how can I add new SwapChainPanel in the ListView

    You have placed SwapChainPanel in the Listview DataTemplate, and current listview ItemsSource is ObservableCollection. So you just need add new item into ObservableCollection, the listview will render new item automatically.

    so i want to get the object SwapChainPanel item in code-behind

    You could get itemContainer with ContainerFromItem method, and find swapChain with name in ContentTemplateRoot.

    var container = MyList.ContainerFromItem(MyList.Items[0]) as ListViewItem;
    var swapChain = (container.ContentTemplateRoot as Grid).FindName("swapChain");
    

    Update

    As the Hoka Biu comment below, you could also get swapChain instance within SwapChainPanel Loaded event.

    <SwapChainPanel Loaded="swapChain_Loaded"/>
    
    private void swapChain_Loaded(object sender, RoutedEventArgs e)
    {
        var swapChain = sender as SwapChainPanel;         
    }