获取ListBox中项目的高度

时间:2014-08-17 14:16:58

标签: c# listbox windows-runtime windows-store win-universal-app

我有一个带有几个项目的ListBox。我试图计算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.Height”,但我如何才能访问它?

1 个答案:

答案 0 :(得分:1)

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

 <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>