积极答复者
如何使工具栏中的自定义控件具有系统预设的显示效果?

问题
答案
-
把以下代码加到你的继承自button的自定义控件中即可:
protected override void OnInitialized(EventArgs e) { if (this.Style == null && this.Parent is ToolBar) { this.Style = (Style)FindResource(ToolBar.ButtonStyleKey); } base.OnInitialized(e); }
Toolbar在添加控件时,会自动检查控件的类型,如果是Button(精确),会自动给Button应用ToolBarButtonStyle,虽然你的自定义控件是继承自Button的,但是在检查时是无法跟Button类型匹配的(typeof(你的控件) != typeof(Button)),所以Toolbar不能自动更改控件的Style。所以只能在代码里手动更改了。
全部回复
-
把以下代码加到你的继承自button的自定义控件中即可:
protected override void OnInitialized(EventArgs e) { if (this.Style == null && this.Parent is ToolBar) { this.Style = (Style)FindResource(ToolBar.ButtonStyleKey); } base.OnInitialized(e); }
Toolbar在添加控件时,会自动检查控件的类型,如果是Button(精确),会自动给Button应用ToolBarButtonStyle,虽然你的自定义控件是继承自Button的,但是在检查时是无法跟Button类型匹配的(typeof(你的控件) != typeof(Button)),所以Toolbar不能自动更改控件的Style。所以只能在代码里手动更改了。