简体   繁体   English

是否可以将动态属性绑定到 WinForms 控件属性?

[英]Is it possible to bind dynamic properties to WinForms control properties?

I'd like to bind dynamic properties to WinForms control properties.我想将动态属性绑定到 WinForms 控件属性。

In the following example I bind the IsAlive property of a thread to the Enabled of a button.在以下示例中,我将线程的 IsAlive 属性绑定到按钮的 Enabled。

using System;
using System.Windows.Forms;
using System.Threading;

namespace ThreadTest
{
  public partial class Form1 : Form
  {
    Thread thread;

    public Form1()
    {
      InitializeComponent();

      thread = new Thread(() =>
        {
          while (true)
            Thread.Sleep(125);
        }
      );

      button2.DataBindings.Add("Enabled", thread, "IsAlive");
    }

    private void buttonStart_Click(object sender, EventArgs e)
    {
      thread.Start();
    }

    private void buttonStop_Click(object sender, EventArgs e)
    {
      // ...
    }
  }
}

This only works on start up.这仅适用于启动。 The "Stop" button is disabled because the thread is not alive. “停止”按钮被禁用,因为线程不活动。 When I click on button "Start" I would expect to change button "Stop" to enabled.当我单击“开始”按钮时,我希望将“停止”按钮更改为启用。 But it does not.但事实并非如此。

Am I missing something or is this just not possible?我错过了什么还是这不可能?

Thread does not implement INotifyPropertyChanged , nor does it have an "IsAliveChanged" event, so there is no way for the data binding to recognize that IsAlive has changed. Thread没有实现INotifyPropertyChanged ,也没有“IsAliveChanged”事件,因此数据绑定无法识别IsAlive是否已更改。

This blog entry has some tips and tricks for making data binding work in WinForms. 此博客条目有一些提示和技巧,使数据绑定在WinForms中工作。 The main requirement is that the classes to which you're binding must be designed with data binding in mind if you want to support dynamic updates from the data source to the control. 主要要求是,如果要支持从数据源到控件的动态更新,则必须将要绑定的类设计为具有数据绑定。

Data binding in WinForms are rather broken, because automagically they only work in one way (when you change the UI, the object gets updated). WinForms中的数据绑定相当破碎,因为它们只能以一种方式自动运行(当您更改UI时,对象会更新)。 If you own the object used for binding, you should implement INotifyPropertyChanged interface on it. 如果您拥有用于绑定的对象,则应在其上实现INotifyPropertyChanged接口。 In your case you have to manually reset the bindings to make it work (so the binding is not giving you anything really) 在你的情况下,你必须手动重置绑定,使其工作(所以绑定不会给你任何东西)

Calling DataBindings broken is just not right.调用 DataBindings 损坏是不对的。 Broken means, something does not work as designed - but looking at the source, it works exactly the way it's designed.破碎的意思是,有些东西不像设计的那样工作 - 但从源头来看,它完全按照设计的方式工作。 And with tools like Fody's ProperyChanged weaver, you can make virtually every class using INotifyPropertyChanged使用 Fody 的 ProperyChanged weaver 等工具,您几乎可以使用 INotifyPropertyChanged 创建每个类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM