我可能有一个非常简单的问题,但找不到解决方案。我在绑定(bind)到 ToolStripLabel 的属性时遇到问题。 Label 与 App.Config 中的 COM 端口值绑定(bind)。
如果我绑定(bind) System.Windows.Forms.Label
标签的属性,则通过更改 COM 端口来更新 Text-Property 可以正常工作。但是,当标签位于 IN ToolStrip (System.Windows.Forms.ToolStripLabel
) 中时,不会通过在运行时更改 COM 端口的值来更新标签。
仅当应用程序重新启动时才会更改。
图中有 PropertyBinding
到 ApplicationSettings
的当前设置。
我已经尝试过:
- Application.DoEvents()
- toolStrip.Update()
- toolStrip.Refresh()
- toolStrip.Invalidate()
没有什么区别。 有谁知道问题可能是什么?
您好, 萨莎
最佳答案
ToolStripLabel组件不像标签控件那样实现数据绑定(bind)(这就是为什么您可以看到标签控件在当前设置更改时更新其文本)。当您通过设计器将 PropertyBindings
添加到 Text
属性时,Text 只是设置为所选的 Properties.Default
设置(您可以看到在 Designer.cs
文件中)。
您可以构建自己的 ToolStripLabel 来实现 IBindableComponent ,用 ToolStripItemDesignerAvailability 装饰它允许 ToolStrip 或 StatusStrip 确认此自定义组件存在的标志,以便您可以直接从选择工具添加它。
将 PropertyBinding
添加到 Text 属性,现在,当设置更改时,文本也会更新。您可以在 Designer.cs
文件中看到已添加 DataBinding。
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;
}
}
}
关于c# - ToolStripLabel 未使用 PropertyBinding 随应用程序设置进行更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65576853/