c# - WinForms:响应正在应用的 BindingSource

标签 c# winforms events data-binding binding

当数据源已应用于其绑定(bind)控件时,我是否可以锁定一个事件以得到通知?

或者是否有另一个事件,我可以保证数据源已被应用?


我正在使用 WinForms(来自 WPF)并使用带有数据绑定(bind)值的标签来确定我正在使用的控件类型。许多控件可能具有相同的标签值,我必须检索具有所需标签的控件才能执行业务逻辑。

问题是我不知道何时搜索标签值。我试图在调用后立即搜索标签值:

myBindingSource.DataSource = OutputFunctions.Instance;
//Yes... I'm binding to a singleton with a list of properties.
//Its not the best method, but works.

在我的 Form.Load 事件处理程序中。但是,在搜索过程中,我发现标签值没有设置。刚刚设置数据源怎么会这样呢?

从我的表单的内部管理代码隐藏可以看出,我已经通过设计器的属性窗口正确设置了值:

this.textBoxDTemp.DataBindings.Add(new System.Windows.Forms.Binding(
    "Tag",
    this.myBindingSource,
    "KNOB_DRIVER_TEMP",
    true));

我查看了 BindingComplete,老实说,它看起来很有前途,除了它不会在绑定(bind)初始化期间触发,即使值应该是从数据传播的-源到目标控件。

编辑: 根据请求,首先在表单的内部代码隐藏中设置数据源,如下所示:

this.myBindingSource.DataSource = typeof(OutputFunctions);

这里是单例,以防有帮助。

public class OutputFunctions
{
    private static OutputFunctions instance;

    public static OutputFunctions Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new OutputFunctions();
            }
            return instance;
        }
    }

    private OutputFunctions() { }

    public string KNOB_DRIVER_TEMP { get { return "KNOB_DRIVER_TEMP"; } }
    public string KNOB_PASSENGER_TEMP { get { return "KNOB_PASSENGER_TEMP"; } }
    public string KNOB_FAN { get { return "KNOB_FAN"; } }
}

最佳答案

数据绑定(bind)应该在您的表单加载事件之前已经激活。您遇到的问题是因为由于数据绑定(bind)基础结构优化,不可见控件在第一次变得可见之前不会发生绑定(bind)。这可能是因为 WF 的设计者认为数据绑定(bind)将仅用于绑定(bind)数据属性(如 Text 等)并且对不可见控件执行此操作没有意义。

如果您不害怕使用一些内部机制(或者像用户 HighCore 所说的 hack),那么以下帮助程序将有助于解决您的问题(我们多年来一直在使用类似的东西):

public static class ControlUtils
{
    static readonly Action<Control, bool> CreateControlFunc = (Action<Control, bool>)Delegate.CreateDelegate(typeof(Action<Control, bool>),
        typeof(Control).GetMethod("CreateControl", BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(bool) }, null));
    public static void CreateControls(this Control target)
    {
        if (!target.Created)
            CreateControlFunc(target, true);
        else
            for (int i = 0; i < target.Controls.Count; i++)
                target.Controls[i].CreateControls();
    }
}

然后放在表单加载事件处理程序的开头

this.CreateControls();

关于c# - WinForms:响应正在应用的 BindingSource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33307160/

相关文章:

c# - Windows Phone 8.1 Assembly.GetExecutingAssembly 不可用

c# - 在列表框中插入具有特定颜色的项目

python - 使用虚拟 ListCtrl 在 wxpython 中复制并粘贴行

ios - 确定是否在 `touch` 回调线程上,ios

c# - 错误 : Could not load file or assembly 'System.Net.Http.Primitives, Version=1.5.0.0...'

c# - 模拟 NLog 的记录器并读取记录的消息

c# - .NET 2.0 (WinForms) 的组件应用程序 block - 有哪些新版本?

c# - WinForms TabOrder 工具 : Broken or just confusing?

javascript - 动态创建的元素上的事件绑定(bind)?

c# - 在 C# 中使用字节数组