I have an ListBox with a few items. I tried to calculate the height of the ListBox, so that the items are fitting well in the ListBox. But I can't access the height of each listBoxItem, to calculate the height.
<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;
}
So, I am searching the "ListBoxItem.Height", but how I can access this?
You can set the height for each item inside the listbox like this,
<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>