Note that there are some explanatory texts on larger screens.

plurals
  1. POData-based template selection in WPF
    primarykey
    data
    text
    <p>I have this simple XAML example:</p> <pre><code>&lt;Window x:Class="DynTemplateTest.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"&gt; &lt;Window.Resources&gt; &lt;DataTemplate x:Key="ItemTemplate"&gt; &lt;ItemsControl ItemsSource="{Binding}"&gt; &lt;ItemsControl.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;Rectangle Width="30" Height="30" Fill="Red"&gt;&lt;/Rectangle&gt; &lt;/DataTemplate&gt; &lt;/ItemsControl.ItemTemplate&gt; &lt;ItemsControl.ItemsPanel&gt; &lt;ItemsPanelTemplate&gt; &lt;Canvas /&gt; &lt;/ItemsPanelTemplate&gt; &lt;/ItemsControl.ItemsPanel&gt; &lt;ItemsControl.ItemContainerStyle&gt; &lt;Style&gt; &lt;Setter Property="Canvas.Left" Value="{Binding Position}"&gt;&lt;/Setter&gt; &lt;/Style&gt; &lt;/ItemsControl.ItemContainerStyle&gt; &lt;/ItemsControl&gt; &lt;/DataTemplate&gt; &lt;/Window.Resources&gt; &lt;DockPanel LastChildFill="True"&gt; &lt;ContentPresenter Content="{Binding Path=Items}" ContentTemplate="{StaticResource ItemTemplate}" &gt; &lt;/ContentPresenter&gt; &lt;/DockPanel&gt; &lt;/Window&gt; </code></pre> <p>It is rendering my items in the observable collection in MVVM style. Each item is having its horizontal position in a property. Each item also has a property IsSpecial which tells if it wants to be rendered in some special way. I want ordinary items (IsSpecial=false) render as red squares (already in the code) and special items as blue circles with "special" text inside.</p> <p>What I do not know is how to adjust the XAML code to do the template selection for the items. Is there a way to do that without coding my own ItemTemplateSelector? Will it still work with the canvas positioning based on binding. I think that the solution is to extract the item template to a separate template, create one more template for special items and then somehow play with triggers ... but it is not very easy for me as I am a WPF beginner at the moment.</p> <p>The other thing is that I quite dislike the way how the Position is passed to the items. Is there some other way?</p> <p>Are there any other recommendations how to improve the code?</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