当数据源已应用于其绑定(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/