打开下拉列表后,如何将WPF组合框绑定到其他列表? [英] How do I bind a WPF combo box to a different list when the dropdown is open?

查看:45
本文介绍了打开下拉列表后,如何将WPF组合框绑定到其他列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在计划模块中有几个组合框,每个组合框都有一个基于活动"字段的下拉列表.

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.

我该怎么做?

我已经在后面的代码中尝试过了

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.

推荐答案

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

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>

这篇关于打开下拉列表后,如何将WPF组合框绑定到其他列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆