WPF SelectTemplate多次调用

时间:2018-11-08 11:18:20

标签: wpf templates

我有一个树形视图,每次在节点之间切换时,我都会加载一个DataTemplate以便正确显示数据。 这是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" />

问题在于,为模板中定义的datagrid中存在的每一行调用了我的SelectTemplate方法(如下)。因此,如果我有20行,则该模板将被调用20次。

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;
}

我的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;
    }
}

为什么这种行为?模板不应该调用一次吗?

1 个答案:

答案 0 :(得分:1)

这是预期的行为。为SelectTemplate中的每个项目调用ItemsControl方法,然后将返回的DataTemplate应用于其ItemsSource集合中的相应对象。

如果您只想为所有对象调用一次,则不妨使用ItemTemplate