ToolStripLabel 未使用 PropertyBinding 更新应用程序设置

问题描述

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

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

图中有PropertyBindingApplicationSettings的当前设置。

我已经试过了:

  • Application.DoEvents()
  • toolStrip.Update()
  • toolStrip.Refresh()
  • toolStrip.Invalidate()

没什么区别。 有没有人知道可能是什么问题?

您好, 莎莎

ApplicationSettings

Label Properties Settings

Example

解决方法

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

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

PropertyBinding 添加到 Text 属性,现在,当设置更改时,文本会更新。您可以在 Designer.cs 文件中看到已添加数据绑定。

Bindable ToolStripLabel

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,e.g.
    public ToolStripDataLabel(string text,Image image,bool isLink) : base(text,image,isLink,null) { }

    [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;
        }
    }
}