The ItemTemplate ListBox is copied to the ContentTemplate from the ListBoxItem during user interface creation. This means that your code is equivalent to the following.
<ListBox> <ListBox.ItemTemplate> <DataTemplate> <DockPanel> <TextBlock><ContentPresenter /></TextBlock> </DockPanel> </DataTemplate> </ListBox.ItemTemplate> <ListBoxItem Content="Hello" /> <ListBoxItem Content="World" /> </ListBox>
However, you add ListBoxItems directly, so this is not 100% true.
(ItemTemplate and ItemTemplateSelector are ignored for items that already exist in the ItemsControl container: Type = 'ListBoxItem')
Find out why Visual Studio crashes. Firstly, it crashes only after filling out the ListBox, so this only happens when you add the ListBoxItem directly to Xaml (your application will still crash, but not VS). ContentPresenter is where the template for the ListBox inserts the ContentTemplate. So, if we have this
<Style TargetType="ListBoxItem"> <Setter Property="ContentTemplate"> <Setter.Value> <DataTemplate> <TextBlock><ContentPresenter /></TextBlock> </DataTemplate> </Setter.Value> </Setter> </Style>
and we donβt change the template to look something like this (shortend version)
<Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ListBoxItem"> <ContentPresenter/> </ControlTemplate> </Setter.Value> </Setter>
We'll get
<ContentPresenter/> -> <TextBlock><ContentPresenter /></TextBlock> -> <TextBlock><TextBlock><ContentPresenter /></TextBlock></TextBlock>
etc. It never stops and Visual Studio crashes. If we change the template to this
<Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ListBoxItem"> <TextBlock Text="No ContentPresenter Here"/> </ControlTemplate> </Setter.Value> </Setter>
we are not getting a failure because ContentPresenter is never used.
(I think I broke Studio a dozen times trying to do this :)
So, in your case, you should use a template instead of a ContentTemplate.
<ListBox> <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ListBoxItem}"> <DockPanel> <TextBlock><ContentPresenter /></TextBlock> </DockPanel> </ControlTemplate> </Setter.Value> </Setter> </Style> </ListBox.ItemContainerStyle> <ListBoxItem Content="Hello" /> <ListBoxItem Content="World" /> </ListBox>