win-universal-appitemscontrolwindows-10-universallistbox-control

UWP: Hide ItemsControl items


I have an ItemsControl inside another ItemsControl. This ItemsControl, contains a list of sold items.

I would like to display those items that sold below the cost (negative profit). But I am having problem collapsing the item (row).

<ItemsControl>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Grid>
                ...
                ...
                ...
                <ItemsControl ItemsSource="{Binding SoldItems}">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <Grid>  <!--If I hide the grid, it will create empty space.-->
                                ...
                                ...
                                ...
                                <TextBlock Text="{Binding Profit}"></TextBlock>
                            </Grid>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </Grid>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

If I tried to hide the grid, it displays empty row. It looks weird as it has empty gap there.

<Grid Visibility="{Binding Profit, Mode=OneWay, Converter={StaticResource ProfitVisibilityConverter}}">

Any idea how to hide the entire row?

Thanks


Solution

  • <ListView x:Name="MyListView">
        <ListView.ItemTemplate>
            <DataTemplate >
                <Grid Visibility="{Binding visible}"  Tag="{Binding ElementName=MyListView}" Loaded="Grid_Loaded"  >
                    <TextBlock Text="{Binding Name}"/>
                </Grid>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
    
    
    private void Grid_Loaded(object sender, RoutedEventArgs e)
    {
        Grid grid = sender as Grid;
        // For items control
        // ContentPresenter item = (ContentPresenter)(grid.Tag as ItemsControl).ContainerFromItem(grid.DataContext);
        ListViewItem item = (ListViewItem)(grid.Tag as ItemsControl).ContainerFromItem(grid.DataContext);
        // Or you can directly access listview
        // ListViewItem item = (ListViewItem)(MyListView as ItemsControl).ContainerFromItem(grid.DataContext);
        if ((grid.DataContext as Test).visible == Visibility.Collapsed)
        {
            if (item != null)
            {
                Binding binding = new Binding();
                binding.Mode = BindingMode.TwoWay;
                binding.Source = (grid.DataContext as your model class)
                binding.Path = new PropertyPath("givevisibilityproperty");
    
                // Attach the binding to the target.
                item.SetBinding(ListViewItem.VisibilityProperty, binding);
    
                // (item ).Visibility = Visibility.Collapsed;
            }
        }
    }