Reputation: 59
I have a treeview and each time I switch among the nodes, I load a DataTemplate in order to show properly data. This is an example of by DataTemplate:
<DataTemplate x:Key="dataFlexBCR" DataType="{x:Type cls:cFlexBcr}">
<Grid HorizontalAlignment="Stretch" x:Name="grdDataFlexBcr" VirtualizingStackPanel.VirtualizationMode="Recycling" ScrollViewer.CanContentScroll="True" VirtualizingStackPanel.IsVirtualizing="True">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="Desc" />
<ColumnDefinition Width="Auto" SharedSizeGroup="vActive" />
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Content="Modalità indentificazione: " Style="{StaticResource labelStyle2}" />
<ComboBox Grid.Column="1" Width="Auto" ItemsSource="{Binding Path=ConfigObject.Bcrs}" Style="{StaticResource popModeStyle}" SelectionChanged="Combo_SelectionChanged" Typography.Capitals="AllPetiteCaps" SelectedValue="{Binding ConfigObject.ActiveId, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" SelectedValuePath="Key" DisplayMemberPath="Value" />
</Grid>
</DataTemplate>
<local:FlexconfigTemplateSelector dataFlexBCR="{StaticResource dataFlexBCR}" dataFlexBCRs="{StaticResource dataFlexBCRs}" x:Key="flexconfigTemplateSelector" />
The problem is that my SelectTemplate method (below) is called for each rows present in the datagrid defined in the template. So if I have 20 rows, the template is called 20 times.
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
LeafInfo li = item as LeafInfo;
if (li == null) return null;
if (li.ConfigObject is cFlexBcrSingle)
return dataFlexBCR;
if (li.ConfigObject is cFlexBcr)
return dataFlexBCRs;
return null;
}
Code behind of my FleconfigTemplateSelector:
public class FlexconfigTemplateSelector : DataTemplateSelector
{
public DataTemplate dataFlexBCR { get; set; }
public DataTemplate dataFlexBCRs { get; set; }
/// <summary>
/// template
/// </summary>
/// <param name="item"></param>
/// <param name="container"></param>
/// <returns></returns>
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
LeafInfo li = item as LeafInfo;
if (li == null) return null;
if (li.ConfigObject is cFlexBcr)
return dataFlexBCRs;
if (li.ConfigObject is cFlexBcrSingle)
return dataFlexBCR;
return null;
}
}
Why this behaviour? Shouldn't the template called once?
Upvotes: 0
Views: 206
Reputation: 169420
This is the expected behaviour. The SelectTemplate
method is called for each item in an ItemsControl
and the returned DataTemplate
is then applied to the corresponding object in its ItemsSource
collection.
It you only want to call it once for all objects, you might as well use an ItemTemplate
.
Upvotes: 1