只读(但投掷的)组合框 [英] Read-only (but droppable) ComboBox

查看:129
本文介绍了只读(但投掷的)组合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望建立一个Windows窗体组合框,具有正常颜色,并允许下拉列表中出现,但不允许的价值真正改变。据我所知,这是不是如何使组合框的重复的WinForms只读因为所有的意见似乎有走向禁用组合框的交互指挥。

I'm looking to build a Windows Forms combo box that has normal coloration, and allows the dropdown list to appear, but does not allow the value to actually change. As far as I can tell, this is not a duplicate of How to make Combobox in winforms readonly since all advice there seems to be directed toward disabling the combo box's interactivity.

我的理由:我有,所有的控件是只读的,而且由于我认为会有越来越困惑时,组合框的值不改变用户的风险的应用程序的性质的一种形式。我希望用户能够看到所有的,以该组合框绑定枚举的可能值。

My rationale: I have a form where all of the controls are read-only, and due to the nature of the application I think that there would be no risk of the user getting confused when the combo box's value does not change. I would like the user to be able to see all of the possible values of the enum to which the combo box is bound.

我至今是pretty的不好黑客:

What I have so far is a pretty bad hack:

public partial class ReadOnlyComboBox : ComboBox
{
    int prevIndex = -1;

    public ReadOnlyComboBox()
    {
        InitializeComponent();
    }

    private void ReadOnlyComboBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (prevIndex <= 0)
            prevIndex = SelectedIndex;
        else
            SelectedIndex = prevIndex;
    }
}

在实际上,这忽略杂散0的值从框架内,并采取从绑定源获得的第一个非零值。立即缺点是该值只能设置一次,并且绑定枚举必须从1开始。

In effect, this ignores spurious "0" values from the framework, and takes the first non-zero value acquired from a binding source. Immediate disadvantages are that the value may only be set once, and that the bound enum must start at 1.

在清理这一行动将受到欢迎任何意见。谢谢你。

Any advice on cleaning this up would be welcome. Thanks.

推荐答案

使用DropDownClosed事件

Use DropDownClosed event

public class ReadOnlyComboBox : ComboBox
{
    bool afterDropDown ;
    int prevIndex;

    public ReadOnlyComboBox()
    {
        this.SelectedIndexChanged+=new EventHandler(ReadOnlyComboBox_SelectedIndexChanged);
        this.DropDownClosed += new EventHandler(ReadOnlyComboBox_DropDownClosed);
    }

    void ReadOnlyComboBox_DropDownClosed(object sender, EventArgs e)
    {
        afterDropDown = true;
    }

    private void ReadOnlyComboBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (afterDropDown)
        {
            afterDropDown = false;
            SelectedIndex = prevIndex;
        }
        else
        {
            prevIndex = SelectedIndex;
        }
    }
}

这篇关于只读(但投掷的)组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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