Note that there are some explanatory texts on larger screens.

plurals
  1. POWPF: Dynamically change ListBox's ItemTemplate based on ListBox Items Size
    primarykey
    data
    text
    <p>I need to change the DataTemplate of my ListBox, based on the ListBox items count. I have come up with the following XAML:</p> <pre><code>&lt;Window.Resources&gt; &lt;DataTemplate x:Key="DefaultTemplate"&gt; &lt;StackPanel Orientation="Horizontal"&gt; &lt;TextBlock Text="{Binding Path=Text}"/&gt; &lt;TextBlock Text="default template" /&gt; &lt;/StackPanel&gt; &lt;/DataTemplate&gt; &lt;DataTemplate x:Key="OtherTemplate"&gt; &lt;StackPanel Orientation="Horizontal"&gt; &lt;TextBlock Text="{Binding Path=Text}"/&gt; &lt;TextBlock Text="other template" /&gt; &lt;/StackPanel&gt; &lt;/DataTemplate&gt; &lt;/Window.Resources&gt; &lt;ListBox Name="listBox1" ItemsSource="{Binding Path=Items}"&gt; &lt;ListBox.Style&gt; &lt;Style TargetType="{x:Type ListBox}"&gt; &lt;Setter Property="ItemTemplate" Value="{StaticResource DefaultTemplate}" /&gt; &lt;Style.Triggers&gt; &lt;DataTrigger Binding="{Binding Path=Items.Count}" Value="1"&gt; &lt;Setter Property="ItemTemplate" Value="{StaticResource OtherTemplate}"/&gt; &lt;/DataTrigger&gt; &lt;/Style.Triggers&gt; &lt;/Style&gt; &lt;/ListBox.Style&gt; &lt;/ListBox&gt; </code></pre> <p>With the above XAML, once I added two or more items to the bound list, the data template changed as expected (from other to default). However, if I remove the first item in the list with more than two items, the entire listbox just becomes empty (I verified that the bound list is non-empty). Removing the second item in a two items list works fine though (i.e. template changed from default to other).</p> <p>Any ideas why this is happening? Or perhaps I went about the wrong way to solve this problem?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload