2

我可能有一个非常简单的问题,但找不到解决方案。我对 ToolStripLabel 的属性绑定有疑问。标签绑定到 App.Config 中的 COM 端口值。

如果我为System.Windows.Forms.Label标签绑定属性,则通过更改 COM 端口来更新 Text-Property 可以正常工作。但是,当标签为 IN ToolStrip ( System.Windows.Forms.ToolStripLabel) 时,不会通过在运行时更改 COM 端口的值来更新标签。
只有重新启动应用程序才会更改它。

图中有PropertyBindingto的当前设置ApplicationSettings

我已经尝试过:

  • 应用程序.DoEvents()
  • 工具条更新()
  • toolStrip.Refresh()
  • toolStrip.Invalidate()

没有什么不同。有谁知道问题可能是什么?

问候,萨沙

应用程序设置

标签属性设置

例子

4

1 回答 1

2

ToolStripLabel组件没有像标签控件那样实现 DataBindings(这就是为什么您可以看到标签控件在当前设置更改时更新其文本的原因)。当您通过设计器添加PropertyBindingsText属性时,文本只是设置为Properties.Default选定的设置(您可以在文件中看到Designer.cs)。

您可以构建自己的实现IBindableComponent的 ToolStripLabel ,用ToolStripItemDesignerAvailability标志装饰它,允许 ToolStrip 或 StatusStrip 确认此自定义组件的存在,因此您可以直接从选择工具中添加它。

将 a 添加PropertyBinding到 Text 属性,现在,当 Setting 更改时,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;
        }
    }
}
于 2021-01-05T14:32:30.373 回答