在VirtualizingStackPanel.IsVirtualizing =“False”时,ItemContainerGenerator.ContainerFromItem()返回null

时间:2013-04-24 05:39:47

标签: c# wpf combobox null itemcontainergenerator

我遇到this question的类似问题,但VirtualizingStackPanel.IsVirtualizing="False"没有解决我的问题。有没有人面临同样的问题?

问题是我有一个自定义组合框,

<Style TargetType="{x:Type MultiSelectionComboBox}"  >
    <Setter Property="VerticalContentAlignment" Value="Center"/>
    <Setter Property="ItemsPanel">
        <Setter.Value>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Vertical"
                VerticalAlignment="Center"
                HorizontalAlignment="Center"
                VirtualizingStackPanel.IsVirtualizing="False"/>
            </ItemsPanelTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="ItemTemplate">
        <Setter.Value>
            <DataTemplate>
                <StackPanel Orientation="Horizontal" x:Name="ItemStack" VirtualizingStackPanel.IsVirtualizing="False">
                    <CheckBox x:Name="CheckBoxItem"
                        Command="{Binding SelectItem, RelativeSource={RelativeSource AncestorType={x:Type MultiSelectionComboBox}}}"
                        CommandParameter="{Binding Key}"
                              >
                    </CheckBox>
                    <TextBlock Text="{Binding DisplayText}"></TextBlock>
                </StackPanel>
            </DataTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ComboBox}">
                <Grid x:Name="Placement" SnapsToDevicePixels="true">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="Auto"/>
                    </Grid.ColumnDefinitions>
                    <Border BorderThickness="1" BorderBrush="Black">
                        <TextBox IsReadOnly="True" Grid.Column="0" 
                                 Text="{Binding Text, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource AncestorType={x:Type MultiSelectionComboBox}}}">
                        </TextBox>
                    </Border>
                    <Popup x:Name="PART_Popup" 
                               Grid.Column="0"
                               Focusable="False"
                               Grid.ColumnSpan="2"
                               IsOpen="{Binding IsDropDownOpen, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}"
                               Placement="Bottom"
                               VerticalOffset="-1"
                               PlacementTarget="{Binding ElementName=LayoutRoot}">
                        <Popup.Resources>
                            <Style TargetType="{x:Type ScrollBar}" BasedOn="{StaticResource {x:Type ScrollBar}}">
                                <Style.Triggers>
                                    <Trigger Property="Orientation" Value="Vertical">
                                        <Setter Property="BorderThickness" Value="0"/>
                                    </Trigger>
                                </Style.Triggers>
                            </Style>
                        </Popup.Resources>
                        <ScrollViewer x:Name="DropDownScrollViewer"
                                          Background="{StaticResource Background}"
                                          BorderBrush="{TemplateBinding BorderBrush}"
                                          BorderThickness="{TemplateBinding BorderThickness}"
                                          MinWidth="{Binding ActualWidth, ElementName=LayoutRoot}"
                                          MaxHeight="{TemplateBinding MaxDropDownHeight}">
                            <ItemsPresenter KeyboardNavigation.DirectionalNavigation="Contained"/>
                        </ScrollViewer>
                    </Popup>
                    <ToggleButton IsEnabled="{Binding IsEnabled, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource AncestorType={x:Type MultiSelectionComboBox}}}" Grid.Column="1" IsChecked="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}" Style="{StaticResource ComboBoxToggleButton}"/>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</ResourceDictionary>

然而我无法引用via,

中的复选框
this.ItemContainerGenerator.ContainerFromItem(this.Items[0]) as ComboBoxItem;

有什么建议吗?

我真正想要实现的是,

我想更改复选框缺陷属性,这取决于可在运行时更改的其他对象。我不能使用绑定,因为整个项目的当前状态,此时我无法改变。所以基本上一旦创建了新的MultiSelectionComboBox,我想做类似的事情,

foreach (object item in this.Items)
{
    ComboBoxItem comboBoxItem = this.ItemContainerGenerator.ContainerFromItem(item) as ComboBoxItem;
    if (comboBoxItem == null)
        continue;
    FrameworkElement element = comboBoxItem.ContentTemplate.LoadContent() as FrameworkElement;
    CheckBox checkBox = element.FindName("CheckBoxItem") as CheckBox;
    checkBox.IsChecked = this.SelectedItem.Contains(item);
}

3 个答案:

答案 0 :(得分:12)

尝试在UpdateLayout()

之前执行this.ItemContainerGenerator.ContainerFromItem(item)

答案 1 :(得分:2)

使用ComboBox中的ItemContainerGenerator.StatusChanged事件,如下所示:

myComboBox.ItemContainerGenerator.StatusChanged += ItemContainerGenerator_StatusChanged;

void ItemContainerGenerator_StatusChanged(object sender, System.EventArgs e)
{
    if (myComboBox.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
    {
        foreach (var item in myComboBox.Items)
        {
            var container = (ComboBoxItem)LanguageComboBox.ItemContainerGenerator.ContainerFromItem(item);
        }
    }
}

答案 2 :(得分:0)

由于我的逻辑在SelectionChanged事件中,我想知道为什么ItemContainerGenerator.ContainerFromItem方法总是返回null,即使Listbox.SelectedItem不为空,甚至更奇怪,虚拟化被关闭了!查看ItemContainerGenerator.Status我看到它是Primitives.GeneratorStatus.NotStarted然后我在ItemContainerGenerator.Status == Primitives.GeneratorStatus.ContainersGenerated上添加了一个简单的测试,最后以这种方式解决了这个问题,并且不需要加入到Status_Changed事件中。