获取ListBox中项目的高度

本文关键字:高度 项目 ListBox 获取 | 更新日期: 2023-09-27 18:18:26

我有一个列表框,里面有几个项目。我试图计算ListBox的高度,以便项目能够很好地适应ListBox。但是我不能访问每个listBoxItem的高度,来计算高度。

<ListBox x:Name="listBox" ItemsSource="{Binding Source={StaticResource myList}}" Height="100" Width="250">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Text="{Binding Path=Name}"/>
                        <TextBlock Text="{Binding Path=Description}"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

.

//Code Behind
public class ItemList : ObservableCollection<Items>
    {
        public ItemList() : base()
        {
        }
    }
    public class Items
    {
        private string name;
        private string description;
        public Items(string Name, string Description)
        {
            this.name = Name;
            this.description = Description;
        }
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        public string Description
        {
            get { return description; }
            set { description = value; }
        }
    }
public App1()
        {
            this.InitializeComponent();
            products = new List<Items>();
            products.Add(new Items("Product1", "This is Product1"));
            products.Add(new Items("Product2", "This is Product2"));
            products.Add(new Items("Product3", "This is Product3"));
            products.Add(new Items("Product4", "This is Product4"));
            listBox.ItemsSource = products;
            listBox.Height = listBox.Items.Count * ListBoxItem.Height;
        }

所以,我正在搜索"ListBoxItem"。高度",但我怎么能访问这个?

获取ListBox中项目的高度

您可以像这样设置列表框内每个条目的高度,

 <ListBox x:Name="listBox"  Height="100" Width="250">
            <ListBox.ItemContainerStyle>
                <Style TargetType="ListBoxItem">
                    <Setter Property="Height" Value="50" />
                </Style>
            </ListBox.ItemContainerStyle>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Text="{Binding Path=Name}"/>
                        <TextBlock Text="{Binding Path=Description}"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
  </ListBox>