c# - ToolStripLabel 未使用 PropertyBinding 随应用程序设置进行更新

标签 c# winforms toolstrip toolstripitem

我可能有一个非常简单的问题,但找不到解决方案。我在绑定(bind)到 ToolStripLabel 的属性时遇到问题。 Label 与 App.Config 中的 COM 端口值绑定(bind)。

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

图中有 PropertyBindingApplicationSettings 的当前设置。

我已经尝试过:

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

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

您好, 萨莎

ApplicationSettings

Label Properties Settings

Example

最佳答案

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

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

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

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

    [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/

相关文章:

c# - 基于用户回发的动态控件

c# - 如果未选中某些复选框,则使用复选框将文本保存到文件需要它转到新行

c# - 格式化文件中的文本表,将每行两行合并为一行

winforms - 将 ToolStripProgressBar 锚定到 StatusBar(StatusStrip) 的右侧

c++ - 为什么我在工具条上得到一条垂直线?

WinForms : how to add toolStrip to a form already divided into left/right panes using a SplitContainer control

c# - 在流上生成 XOR 校验和的简单方法?

c# - Windows Azure 表存储帐户中如何拥有用户和角色信息以进行系统身份验证

c# - winform控件如何随着窗体展开等量展开

c# - Winforms/SQL Server 应用程序的会计系统