【问题标题】:Winforms DataBindings.Add for "Current - 1" and "Current + 1" in addition to "Current"?Winforms DataBindings.Add 为“Current - 1”和“Current + 1”除了“Current”吗?
【发布时间】:2017-03-22 17:53:20
【问题描述】:

主题说明了一切。我的 GUI 基于 DataTable,布局如下:

(current - 1, gray)    label 1/4000    label ABC

                       [ Navigate Previous button ]
(current, black)       label 2/4000    label DEF
                       [ Navigate Next button     ]

(current + 1, gray)    label 3/4000    label GHI

DEF 由 currName.DataBindings.Add ("Text", mybindingsource, "cname"); 处理,但 ABC 和 GHI 是否可以使用这种方法绑定?

目前我的解决方法是在每次调用 mybindingsource_CurrentChanged 事件时手动设置 ABC 和 GHI 标签,但这似乎低于标准,因为它是如此手动,我失去了 DataBindings.Add 为您提供的自动格式化和 DBNull 处理免费。

我应该怎么做?

(是的,我知道 DataRepeater,我确实在其他表单上使用它,但它并不真正适合这种表单,原因是这里太长了,与问题无关.)

【问题讨论】:

  • DataBindings 可以有事件:Format 和 Parse。
  • 我相信您当前的解决方案很好,但是如果您想知道如何使用数据绑定来解决问题,作为一种选择,您可以使用不同的BindingSource 组件来绑定控件,然后在主绑定源的PositionChanged 事件中,根据主绑定源的位置设置它们的Position

标签: c# winforms data-binding


【解决方案1】:

我相信您当前的解决方案很好,但是如果您想知道如何使用数据绑定来解决问题,作为一种选择,您可以使用不同的BindingSource 组件来绑定控件,然后设置它们的Position基于主绑定源在PositionChanged 事件中的主绑定源位置。

示例

在下面的示例中,主绑定源是currentBScurrentTextBox 绑定到它。 previousTextBox 显示上一项,nextTextBox 显示下一项:

private void Form1_Load(object sender, EventArgs e)
{
    var t = new DataTable();
    var tc = t.Clone();
    t.Columns.Add("C1");
    t.Rows.Add("A");
    t.Rows.Add("B");
    t.Rows.Add("C");
    t.Rows.Add("D");
    t.Rows.Add("E");
    currentBS.PositionChanged += (x, y) =>
    {
        if (currentBS.Position == 0)
            previousBS.DataSource = tc;
        else
        {
            previousBS.DataSource = t;
            previousBS.Position = this.currentBS.Position - 1;
        }
        if (currentBS.Position == currentBS.Count - 1)
            nextBS.DataSource = tc;
        else
        {
            nextBS.DataSource = t;
            nextBS.Position = this.currentBS.Position + 1;
        }
    };
    previousBS.DataSource = tc;
    nextBS.DataSource = tc;
    currentBS.DataSource = t;
    this.previousTextBox.DataBindings.Add("Text", previousBS, "C1");
    this.currentTextBox.DataBindings.Add("Text", currentBS, "C1");
    this.nextTextBox.DataBindings.Add("Text", nextBS, "C1");
}

【讨论】:

  • 比程序方法干净得多。
猜你喜欢
  • 1970-01-01
  • 2021-05-07
  • 1970-01-01
  • 2015-04-15
  • 1970-01-01
  • 2012-05-05
  • 2022-01-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多