繁体   English   中英

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

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

我想将动态属性绑定到 WinForms 控件属性。

在以下示例中,我将线程的 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)
    {
      // ...
    }
  }
}

这仅适用于启动。 “停止”按钮被禁用,因为线程不活动。 当我单击“开始”按钮时,我希望将“停止”按钮更改为启用。 但事实并非如此。

我错过了什么还是这不可能?

Thread没有实现INotifyPropertyChanged ,也没有“IsAliveChanged”事件,因此数据绑定无法识别IsAlive是否已更改。

此博客条目有一些提示和技巧,使数据绑定在WinForms中工作。 主要要求是,如果要支持从数据源到控件的动态更新,则必须将要绑定的类设计为具有数据绑定。

WinForms中的数据绑定相当破碎,因为它们只能以一种方式自动运行(当您更改UI时,对象会更新)。 如果您拥有用于绑定的对象,则应在其上实现INotifyPropertyChanged接口。 在你的情况下,你必须手动重置绑定,使其工作(所以绑定不会给你任何东西)

调用 DataBindings 损坏是不对的。 破碎的意思是,有些东西不像设计的那样工作 - 但从源头来看,它完全按照设计的方式工作。 使用 Fody 的 ProperyChanged weaver 等工具,您几乎可以使用 INotifyPropertyChanged 创建每个类

暂无
暂无

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

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