0

I have below code but can't cast to listviewitem. What is best way to cast listviewitem?

cs

using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;

namespace CastListView
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            listView.ItemsSource = new List<string> { "John", "Tom", "Smith" };
            //I'd like to below code but can't cast to listviewitem
            foreach (ListViewItem item in listView.Items)
            {
                item.Height = 100;
            }
        }
    }
}

xaml

<Window x:Class="CastListView.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:CastListView"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <ListView x:Name="listView"/>
    </Grid>
</Window>

And I know below code is possible. but i want to control with list object.

listView.Items.Add(new ListViewItem { Content= "John" });
listView.Items.Add(new ListViewItem { Content = "Tom" });
listView.Items.Add(new ListViewItem { Content = "Smith" });
Heal Song
  • 30
  • 4
  • Either use the ItemContainerGenerator, or add ListViewItems manually like `listView.ItemsSource = new List { "John", "Tom", "Smith" }.Select(i => new ListViewItem { Content = i });` – Clemens Dec 03 '21 at 07:05
  • Also consider using ListBox, the base class of ListView, unless you set the ListView's View property. – Clemens Dec 03 '21 at 07:06

1 Answers1

0

You could always do this in your XAML to set the height to 100 and still use a list of strings as your source:

<ListView x:Name="listView">
  <ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem">
      <Setter Property="Height" Value="100"></Setter>
    </Style>
  </ListView.ItemContainerStyle>
</ListView>

Or this in the code behind:

Style style = new Style();
style.TargetType = typeof(ListViewItem);
style.Setters.Add(new Setter(ListViewItem.HeightProperty, 200d));
listView.ItemContainerStyle = style;
DCAggie
  • 144
  • 8