ToolStripLabel组件没有像标签控件那样实现 DataBindings(这就是为什么您可以看到标签控件在当前设置更改时更新其文本的原因)。当您通过设计器添加PropertyBindings
到Text
属性时,文本只是设置为Properties.Default
选定的设置(您可以在文件中看到Designer.cs
)。
您可以构建自己的实现IBindableComponent的 ToolStripLabel ,用ToolStripItemDesignerAvailability标志装饰它,允许 ToolStrip 或 StatusStrip 确认此自定义组件的存在,因此您可以直接从选择工具中添加它。
将 a 添加PropertyBinding
到 Text 属性,现在,当 Setting 更改时,Text 会更新。您可以在Designer.cs
文件中看到已添加 DataBinding。
![可绑定工具条标签](https://i.stack.imgur.com/FzuOm.png)
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.Design;
[ToolStripItemDesignerAvailability(
ToolStripItemDesignerAvailability.ToolStrip |
ToolStripItemDesignerAvailability.StatusStrip),
ToolboxItem(false)
]
public class ToolStripDataLabel : ToolStripLabel, IBindableComponent
{
private BindingContext m_Context;
private ControlBindingsCollection m_Bindings;
public ToolStripDataLabel() { }
public ToolStripDataLabel(string text) : base(text) { }
public ToolStripDataLabel(Image image) : base(image) { }
public ToolStripDataLabel(string text, Image image) : base(text, image) { }
// Add other constructors, if needed
[Browsable(false)]
public BindingContext BindingContext {
get {
if (m_Context == null) m_Context = new BindingContext();
return m_Context;
}
set => m_Context = value;
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public ControlBindingsCollection DataBindings {
get {
if (m_Bindings == null) m_Bindings = new ControlBindingsCollection(this);
return m_Bindings;
}
}
}