phm
phm

Reputation: 1170

ListView Container in UWP

I am trying to get the container of the currently selected ListView item. ContainerFromItem returns always null and the compiler complains that the function may be obsolete.

Any idea?

Upvotes: 1

Views: 1350

Answers (1)

Sunteen Wu
Sunteen Wu

Reputation: 10627

ContainerFromItem returns always null.

ItemsControl.ContainerFromItem method can get the container for the specified item. For example, we can get a ListViewItem container from the selected item in a ListView. If you got null, maybe the item doesn't have a container exists or something wrong with your code.

I am trying to get the container of the currently selected ListView item.

Here is a complete demo for getting the container of the currenttly selected ListViewItem. XAML code:

<ListView
    Name="CListView"
    Margin="10"
    HorizontalAlignment="Center"         
    ItemsSource="{x:Bind categories}"
    SelectionChanged="CListView_SelectionChanged">
    <ListView.ItemTemplate>
        <DataTemplate x:DataType="local:Category">
            <StackPanel             
                Background="{x:Bind backgroundcolor}"
                Orientation="Horizontal">
                <TextBlock                           
                    FontSize="17"
                    FontWeight="Bold"
                    Text="{x:Bind Name}" />
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Code behind

  ObservableCollection<Category> categories = new ObservableCollection<Category> { };
  public ListViewContainer()
  {
      this.InitializeComponent();
      categories = new ObservableCollection<Category>
      {
          new Category {Name="name1",details="color1" ,backgroundcolor="#D90015"},
          new Category {Name="name2",details="color2" ,backgroundcolor="#DC1C17"},
          new Category {Name="name3",details="cplor3",backgroundcolor="#DE3A17" },
          new Category {Name="name3",details="color4",backgroundcolor="#E25819" }
      };
  } 
  private void CListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
  {
      var  container = CListView.ContainerFromItem(CListView.SelectedItem);
      ListViewItem item = container as ListViewItem;
      System.Diagnostics.Debug.WriteLine(item.ActualHeight);
  }

Upvotes: 1

Related Questions