WPF Datatemplating the ItemsControl

I have an ItemControl whose ItemsSource is bound to an ObservableCollection <

Component> at runtime. I have defined a data template for the Component type, which works fine.

The component now has an ObservableCollection <

Control> and I want to add another ItemsControl inside my Component Datatemplate to display all the controls. The control here is my own custom object, not associated with the wpf control.

There are different types of controls, so I am trying to use the ItemTemplateSelector to select the correct template for each type. In the example below, to keep it small, I've only shown one of the "RWString" templates that I found using FindResource in MyControlTemplateSelector overriding SelectTemplate. But the SelectTemplate is never called (using a checkpoint for validation). Is there something wrong with my xaml?

<ItemsControl.Resources>
    <src:MyControlTemplateSelector x:Key="XSelector" />
    <DataTemplate DataType="{x:Type src:Component}"  >
        <Expander Visibility="{Binding Path=Show}">
                <ItemsControl ItemsSource="{Binding Path=Contrls}" 
                          ItemTemplateSelector="{StaticResource XSelector}">
                <ItemsControl.Resources>
                    <DataTemplate x:Key="RWstring" >
                        <TextBlock Text="{Binding Path=Label}"/>
                    </DataTemplate>
                </ItemsControl.Resources>
                <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate><WrapPanel /></ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
            </ItemsControl>
        </Expander>
    </DataTemplate>
</ItemsControl.Resources>

      

Update: Contrls is not a typo, only I am using a silly naming system. Contrls is a Component property of type ObservableCollection. Also the reason I am trying to use the ItemsTemplateSelector is because the ObservableCollection <

Control> contains objects of generic types such as Control <

int> Control <

string> etc. Everything derives from Control, and apparently you cannot create data tables that reference generic types.

Update3: Removed update 2 as it is unrelated . I got the ItemTemplateSelector to work by changing the StaticResource to DynamicResource. But I don't know why this works ...

+1


source to share


2 answers


My guess is that this doesn't work with StaticResource, since the Resource is inside an ItemsControl, which probably wasn't created at load time when the StaticResources are evaluated.

DynamicResources are evaluated at load time into an expression at load time and then evaluated on the correct value when requested.



Try moving the resource outside of the ItemsControl.

+1


source


In the line where you bind the nested ItemsControl, is the Path correct? Is it currently "Contrls" if it's "Controls"?



0


source







All Articles