当下拉列表打开时,如何将 WPF 组合框绑定到不同的列表?

How do I bind a WPF combo box to a different list when the dropdown is open?

我在调度模块中有几个组合框,它们都有基于 "Active" 字段的下拉列表。

public class Project
{
    public int ProjectID { get; set; }
    public int ProjectTitle { get; set; }
    public bool Active { get; set; }
}

<ComboBox
    Name="ProjectComboBox"
    ItemsSource="{Binding AllProjects}"
    SelectedItem="{Binding Project, Mode=TwoWay}">
</ComboBox>

日历的编辑表单必须始终在其组合框中显示遗留信息,即使组合列表中的特定项目已被停用。但是如果打开下拉菜单,它必须只显示列表中仍然有效的项目。

我该如何完成?

我已经在代码隐藏中尝试过:

private void ProjectComboBox_DropDownOpened(object sender, EventArgs e)
{
    ProjectComboBox.SetBinding(ItemsControl.ItemsSourceProperty, "ActiveProjects");
}

private void ProjectComboBox_DropDownClosed(object sender, EventArgs e)
{
    ProjectComboBox.SetBinding(ItemsControl.ItemsSourceProperty, "AllProjects");
}

它在下拉列表中显示了正确的列表,但是取消了 select 最初 selected 的项目。如果用户没有 select 新项目,组合框需要在下拉列表关闭时保留其原始 selection。

不更改 ItemsSource,而是通过可见性绑定隐藏非活动元素:

<BooleanToVisibilityConverter x:Key="boolToVisibility"/>

<ComboBox Name="ProjectComboBox" 
          ItemsSource="{Binding AllProjects}"
          DisplayMemberPath="ProjectTitle"
          SelectedItem="{Binding Project, Mode=TwoWay}">
    <ComboBox.ItemContainerStyle>
        <Style TargetType="ComboBoxItem">
            <Setter Property="Visibility" 
                    Value="{Binding Active, Converter={StaticResource boolToVisibility}}"/>
        </Style>
    </ComboBox.ItemContainerStyle>
</ComboBox>

这也有效,并且可能为那些希望做类似事情的人提供更好的灵活性:

<ComboBox.ItemContainerStyle>
    <Style TargetType="ComboBoxItem">
        <Setter Property="Visibility" Value="Visible"/>
        <Style.Triggers>
            <DataTrigger Binding="{Binding Active}" Value="False">
                <Setter Property="Visibility" Value="Collapsed"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</ComboBox.ItemContainerStyle>