Search code examples
c#wpfcomboboxbinding

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


I have several combo boxes in a Scheduling module that all have dropdown lists based on an "Active" field.

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>

The calendar's editing form must always display legacy information in its combo boxes, even if a particular item in a combo list has been deactivated. But if the drop-down is opened, it must only show those items in the list that are still active.

How would I accomplish this?

I have tried this, in the codebehind:

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");
}

Which displays the correct list in the dropdown, but de-selects the originally-selected Project. If the user does not select a new project, the combo box needs to retain its original selection when the dropdown is closed.


Solution

  • instead of changing ItemsSource, hide inactive elements via Visibility binding:

    <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>