ControlTemplate在运行时不使用ContentTemplateSelector

时间:2015-07-16 13:49:43

标签: c# wpf runtime custom-controls controltemplate

我有一个自定义控件CheckableItemsControl,我把它放在一起,它没有外观,没有自己的依赖属性,只是派生自ItemsControl

按照Rachel在这个问题中的回答:How can I overwrite my ListBox's ItemTemplate and still keep the DisplayMemberPath?我已经设法在Generic.xaml中提出以下样式:

<Style x:Key="{x:Type controls:CheckableItemsControl}" TargetType="{x:Type controls:CheckableItemsControl}"
       BasedOn="{StaticResource {x:Type ItemsControl}}">
    <Setter Property="ItemTemplate">
        <Setter.Value>
            <DataTemplate>
                <CheckBox IsChecked="{Binding IsChecked}" Content="{TemplateBinding ContentPresenter.Content}" 
                          ContentTemplateSelector="{TemplateBinding ContentPresenter.ContentTemplateSelector}"
                          Margin="5" />
            </DataTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type controls:CheckableItemsControl}">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto" />
                        <RowDefinition />
                    </Grid.RowDefinitions>

                    <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Bottom"
                                Grid.Row="0"
                                Margin="0,0,0,3">
                        <Button x:Name="PART_SelectAllButton" Content="Select All" Width="60" Margin="5,0,5,0" />
                        <Button x:Name="PART_InvertButton" Content="Invert" Width="60" Margin="5,0,5,0" />
                    </StackPanel>

                    <Border Grid.Row="1" BorderBrush="{x:Static SystemColors.ActiveBorderBrush}" BorderThickness="1">
                        <ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto">
                            <ItemsPresenter />
                        </ScrollViewer>
                    </Border>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

使用它是这样的:

<controls:CheckableItemsControl ItemsSource="{Binding Reports}" DisplayMemberPath="ReportName" />

现在,这在设计时效果很好,设计师正确呈现了将ReportName显示为文本的项目。

然而,在运行时,它只是像没有内容模板一样呈现类型名称。

我无法弄清楚为什么会在运行时失败。

1 个答案:

答案 0 :(得分:0)

发现它归结为:

wpf debug error output System.WIndows.Data Error 25

最终ContentTemplateSelector被忽略,因为我使用ContentTemplate隐式采用了DisplayMemberPath

解决方案可能会添加自定义依赖项属性以手动提取值。

更多信息

来自MSDN上的ContentControl.ContentTemplateSelector Property页:

  

如果同时设置了ContentTemplateSelectorContentTemplate属性,则忽略此属性。

相关问题