日期:2014-05-18  浏览次数:21330 次

ComboBox点击事件
一直在写asp.net,现在要做个桌面程序
//将系统字体绑定给comboBox
foreach   (FontFamily   oneFontFamily   in   FontFamily.Families)
              combo.Items.Add(oneFontFamily.Name);  
1.     我用取到用户点击项的值,但第一次点击combobox后取到SelectedText= " ",第二次点击取到的才是第一次点击时的值(DropDownClosed和SelectedIndexChanged都是如此)。怎么解决。
2.     因为将系统字体绑定给comboBox,我希望字体所对应的样式在combobox的item上反应出来,这样用户在点击下拉框时就知道所选择的字体的实际样式是怎样的。这种效果可以作出来吗?


------解决方案--------------------
忘了说明我的控件是 ToolStripComboBox不是ComboBox
----->
那不是一个道理么?
你继承一下ToolStripComboBox就好了啊
在ToolStripComboBox里面可以访问到combobox

具体参考
http://community.sgdotnet.org/forums/thread/23252.aspx
------解决方案--------------------
ToolStripComboBox和ComboBox稍有一点点不一样,可以参考下面的:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.toolStripComboBox1.Items.Clear();
this.toolStripComboBox1.ComboBox.DrawMode = DrawMode.OwnerDrawFixed;
this.toolStripComboBox1.Items.AddRange(new InstalledFontCollection().Families);
this.toolStripComboBox1.ComboBox.DrawItem += new DrawItemEventHandler(comboBox1_DrawItem);

}
private void button1_Click(object sender, EventArgs e)
{
if (this.toolStripComboBox1.SelectedIndex != -1)
{
FontFamily fontFamily = this.toolStripComboBox1.Items[this.toolStripComboBox1.SelectedIndex] as FontFamily;
if (fontFamily != null)
{
MessageBox.Show(fontFamily.ToString());
}
}
}

private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
FontStyle style = FontStyle.Regular;
FontFamily fontFamily = this.toolStripComboBox1.Items[e.Index] as FontFamily;
if (fontFamily != null)
{
if (!fontFamily.IsStyleAvailable(style))
{
style = FontStyle.Italic;
if (!fontFamily.IsStyleAvailable(style))
{
return;
}
}
using (Font font = new Font(fontFamily, 10, style))
{
using (SolidBrush brush = new SolidBrush(e.ForeColor))
{
e.DrawBackground();
e.Graphics.DrawString(fontFamily.Name, font, brush, e.Bounds);
}
}
}
}
}