Combobox自定义模板会影响分组显示的坑
wpf吧
全部回复
仅看楼主
level 4
在对Combobox进行自定义模板时,如果完全按照微软官方文档进行操作,会遇到一个坑,即:进行视图分组时,无法正确显示视图的项目。
例子如下:
<Style TargetType="ComboBox">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ComboBox">
<Grid>
<ToggleButton Content="{TemplateBinding SelectionBoxItem}"
IsChecked="{Binding IsDropDownOpen, Mode=TwoWay,RelativeSource={RelativeSource TemplatedParent}}"
x:Name="ToggleButton"></ToggleButton>
<Popup IsOpen="{TemplateBinding IsDropDownOpen}" Placement="Bottom" AllowsTransparency="True" PopupAnimation="Slide" >
<Grid MinWidth="{TemplateBinding ActualWidth}" MaxHeight="{TemplateBinding MaxDropDownHeight}">
<Border BorderThickness="1" BorderBrush="#ececec" Background="WhiteSmoke" Margin="0,0,4,4">
<ScrollViewer HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Auto">
<StackPanel IsItemsHost="True"></StackPanel>
</ScrollViewer>
<Border.Effect>
<DropShadowEffect Color="#FF585858" Opacity="0.6" BlurRadius="4" ShadowDepth="4"/>
</Border.Effect>
</Border>
</Grid>
</Popup>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
以上是完全参照官方文档进行自定义ComboBox的代码(稍微进行了简化)。
如果此时,对应用了该样式的Combobox绑定如下数据:
public struct testItem
{
public string name { get; set; }
public string groupe { get; set; }
}
并用以下代码对数据项进行分组显示
var l = new System.Collections.ObjectModel.ObservableCollection<testItem>()
{
new testItem(){name="a",groupe="1"},
new testItem(){name="b",groupe="2"},
new testItem(){name="c",groupe="1"},
new testItem(){name="d"},
};
TestCombobox.DataContext = l;
TestCombobox.Items.GroupDescriptions.Add(new PropertyGroupDescription("groupe"));
那么,实际展示时,Combobox将只会显示分组名,而不会显示分组项。
原理不明。解决方法很简单。
Combobox的Popup中的子项容器 StackPanel,改用ItemsPresenter
<ItemsPresenter KeyboardNavigation.DirectionalNavigation="Contained" ></ItemsPresenter>
以上。
2022年09月02日 07点09分 1
1