【发布时间】:2015-07-16 13:49:42
【问题描述】:
我有一个自定义控件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 显示为文本。
然而,在运行时,它只是像您期望的那样呈现类型名称,没有内容模板。
我不知道为什么这会在运行时失败。
【问题讨论】:
-
看看输出窗口,看看有没有错误发生。
-
@CalebB 谢谢!我收到了
Both 'ContentTemplate' and 'ContentTemplateSelector' are set; 'ContentTemplateSelector' will be ignored. ContentPresenter:'ContentPresenter' (Name=''),但我没有设置 ContentTemplate... -
@CalebB 找到了原因! stackoverflow.com/questions/15654935/…
-
干杯,很高兴您找到了解决方案。 :)
-
@CalebB 只是烦人,因为这意味着我需要添加自己的方式来提升价值而不设置
ContentTemplatesigh
标签: c# wpf runtime custom-controls controltemplate