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

∥☆過路亽.° 提交于 2021-02-08 10:10:26

问题


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.


回答1:


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>



回答2:


This also works, and might provide better flexibility for those looking to do something similar:

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


来源:https://stackoverflow.com/questions/58920450/how-do-i-bind-a-wpf-combo-box-to-a-different-list-when-the-dropdown-is-open

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!