1

我正在使用一个包含 2 个项目列表的组合框,由分隔符分隔。我这样构造它:

public static ObservableCollection<object> Merge<T, U>(IEnumerable<T> collection1, IEnumerable<U> collection2, bool includeSeparator = true)
{
    if (collection1 == null || collection2 == null)
    {
        throw new ArgumentNullException(collection1 == null ? "collection1" : "collection2");
    }

    List<object> tmp = new List<object>();

    tmp.AddRange(collection1.Cast<object>());

    if (includeSeparator)
    {
        tmp.Add(string.Empty);
    }

    tmp.AddRange(collection2.Cast<object>());

    var ret = new ObservableCollection<object>(tmp);
    return ret;
}

在 xaml 中:

<ComboBox 
    ItemsSource="{Binding Path=AllValues}" 
    SelectedValue="{Binding Path=SelectedId, Mode=TwoWay, ValidatesOnDataErrors=True}" 
    SelectedValuePath="Id"
    ItemTemplate="{StaticResource CustomItemTemplate}">

    <ComboBox.ItemContainerStyle>
        <Style TargetType="{x:Type ComboBoxItem}" BasedOn="{StaticResource {x:Type ComboBoxItem}}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding}" Value="">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="{x:Type ComboBoxItem}">
                                <Separator HorizontalAlignment="Stretch" IsEnabled="False"/>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ComboBox.ItemContainerStyle>
</ComboBox>

它按预期工作,我在列表中插入了一个分隔符。问题是,当SelectedId为 null 时,组合框会打开,并在顶部显示分隔符(即滚动条滚动到列表顶部有分隔符),如下图所示。

在此处输入图像描述

你知道有什么方法可以让列表在顶部打开吗?

提前致谢。

4

1 回答 1

2

最简单的解决方案是将分隔项值更改为将返回非空但无效的 Id 选择的值,例如在匿名类型中使用 int.MinValue:

tmp.Add(new { Id = int.MinValue }); 

为此,您还需要将 DataTrigger 更改为:

<DataTrigger Binding="{Binding Id}" Value="{x:Static System:Int32.MinValue}">
于 2012-07-30T04:06:11.917 回答