Search code examples
wpfxamldatatemplateselector

DataTemplateSelector without code-behind


Is it possible to use DataTemplateSelector in a XAML-only way, i.e. without code-behind?


Solution

  • You can't define the actual DataTemplateSelector class in XAML if that's what you are asking.

    Once you have defined a DataTemplateSelector class using C# or whatever your preferred programming language is you can use it in your XAML markup though:

    <Window ... xmlns:local="clr-namespace:SDKSample">
        <Window.Resources>
            <local:TaskListDataTemplateSelector x:Key="myDataTemplateSelector"/>
        </Window.Resources>
        <Grid>
            <ListBox Width="400" Margin="10"
             ItemsSource="{Binding Source={StaticResource myTodoList}}"
             ItemTemplateSelector="{StaticResource myDataTemplateSelector}"
             HorizontalContentAlignment="Stretch"/>
            ...
    

    Please refer to the documentation on MSDN for more information and a full example: https://msdn.microsoft.com/en-us/library/system.windows.controls.datatemplateselector(v=vs.110).aspx