一、增强功能说明:
1、toolStripSplitButton下拉项显示当项(勾选),并且其他的下拉项全部去掉勾
2、同步toolStripSplitButton与其下拉项
3、增加一事件 menuItemAdded ,当增加下拉MenuItem项后发生
4、增加方法:
SyncToButton: 同步按钮与其下拉菜单项
ButtonAddMenuItem :代码增加MenuItem
DoMenuItemClick : 选择当前项,去掉未选择项
二、代码如下
public partial class MyBindingNavigator : System.Windows.Forms.BindingNavigator
{
/// <summary>
/// 2、定义委托
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public delegate void CustomEventHandler(object sender, CustomEventArgs e);
/// <summary>
/// 1、定义事件参数
/// </summary>
public sealed class CustomEventArgs : EventArgs
{
private string menuItemText ;
public CustomEventArgs(string strmenuItemText)
{
this.menuItemText = strmenuItemText;
}
public string Flag
{
get { return menuItemText; }
}
}
/// <summary>
/// 3、定义事件
/// </summary>
[Browsable(true ) ,Description("当增加下拉MenuItem项后发生")]
public event CustomEventHandler menuItemAdded;
/// <summary>
/// 4、执行事件
/// </summary>
/// <param name="e"></param>
protected virtual void OnmenuItemAdded(CustomEventArgs e)
{
if (menuItemAdded != null)
{
menuItemAdded(this, e);
}
}
ToolStripSplitButton _toolSpButton;
public MyBindingNavigator()
{
InitializeComponent();
}
/// <summary>
/// 同步按钮与其下拉菜单项
/// </summary>
/// <param name="spButton"></param>
/// <param name="strButtonCaption"></param>
public void SyncToButton(ToolStripSplitButton spButton,string strButtonCaption )
{
_toolSpButton = spButton;
_toolSpButton.SyncToDeault(strButtonCaption);
InitializeComponent();
}
public virtual void ButtonAddMenuItem(object sender,EventArgs e,ToolStripSplitButton tspButton, ToolStripMenuItem itemMenu)
{
itemMenu.Click += new System.EventHandler(DoMenuItemClick);
tspButton.DropDownItems.Add(itemMenu);
// 5、触发事件
string testFlag = itemMenu.Text;
CustomEventArgs eArgs = new CustomEventArgs(testFlag);
OnmenuItemAdded (eArgs);
}
/// <summary>
/// 选择当前项,去掉未选择项
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public virtual void DoMenuItemClick (object sender, EventArgs e)
{
//去掉所有勾
foreach (ToolStripMenuItem it in ((ToolStripMenuItem)sender).Owner.Items)
{
if (it.Name == ((ToolStripItem)(((ToolStripMenuItem)sender))).Name)
{
((ToolStripMenuItem)(((ToolStripMenuItem)sender).Owner.Items[it.Name])).Checked = true;
}
else
{
((ToolStripMenuItem)(((ToolStripMenuItem)sender).Owner.Items[it.Name])).Checked = false;
}
}
}
}
/// <summary>
/// 同步类
/// </summary>
static class MenuExtend
{
public static void SyncToDeault(this ToolStripSplitButton button,string strButtonCaption)
{
Action<ToolStripSplitButton, ToolStripItem> synchanlder = (splitButton, item) =>
{
splitButton.DefaultItem = item;
splitButton.Text = strButtonCaption + item.Text;
splitButton.ToolTipText = strButtonCaption + item.ToolTipText;
};
if (button.DropDownItems.Count > 0)
{
synchanlder(button, button.DropDownItems[0]);
}
button.DropDownItemClicked += (sender, args) => synchanlder((ToolStripSplitButton)sender, args.ClickedItem);
}
}