NullableComboBox

介绍 这是一个组合框,可以绑定到业务对象并显示空值(空)。 背景 组合框的问题在于,在将数据绑定到它之后,就不可能显示空文本属性。也不可能删除已经选择的值。这个组合框可以同时做这两件事。它被设计成可以将业务对象绑定到它,但是我认为(从未尝试过)它也应该可以与. net DataTables一起工作。 使用的代码 我把我做的这个小技巧称为“惰性绑定”。我的意思是,当你设置数据源时,我没有在第一时间绑定数据。我一直等到用户真正尝试下拉组合框。这样就可以使用户在开始时看到一个空的组合框。删除已经选中的项的工作原理与此类似。在这种情况下(如果用户按下DEL或BACK按钮),我删除了对组合框的数据绑定(但仍然记得数据源)。代码本身非常简单: 惟一有趣的方法是执行数据绑定的方法:Hide。收缩,复制Code

public void SetDataBinding(IList dataSource, object objectToModify, 
                                      string propertyName, string displayMember)
{
    // init combo box and delete all databinding stuff
    this.DisplayMember = String.Empty;
    this.Items.Clear();
    this.ValueMember = String.Empty;
    this.Text = String.Empty;

    // init private fields
    this.mDataSource = dataSource;
    this.mObjectToModify = objectToModify;
    this.mPropertyName = propertyName;
    this.mProperty = 
      this.mObjectToModify.GetType().GetProperty(this.mPropertyName);
    this.mDisplayMember = displayMember;
    this.mNullableMode = true;
    
    // get selected item
    object selectedItem = 
      this.mProperty.GetValue(this.mObjectToModify, null);

    // if not null, bind to it
    if (selectedItem != null)
    {
        this.DataSource = this.mDataSource;
        this.SelectedItem = selectedItem;
    }
    // do nothing and set datasource to null
    else
        this.DataSource = null;
}

下拉事件:Hide复制Code

protected override void OnDropDown(EventArgs e)
{
    // if no datasource is set, set it
    if (this.mNullableMode && this.mDataSource 
           != null && this.DataSource == null)
        this.DataSource = this.mDataSource;

    base.OnDropDown(e);
}

还有按键关闭事件:隐藏复制Code

protected override void OnKeyDown(KeyEventArgs e)
{
    // if DEL or BACK is pressed set property to null and data source to null
    if (this.mNullableMode && (e.KeyCode == 
             Keys.Delete || e.KeyCode == Keys.Back))
    {
        // next line is very important:
        // without you may get an OutOfRangeException
        this.DroppedDown = false;
        this.DataSource = null;
    }

    base.OnKeyDown(e);
}

本文转载于:http://www.diyabc.com/frontweb/news247.html

posted @ 2020-08-04 10:12  Dincat  阅读(125)  评论(0编辑  收藏  举报