65.9K
CodeProject 正在变化。 阅读更多。
Home

在 VB.NET 中将 Windows.Forms 控件绑定到索引对象属性

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.33/5 (5投票s)

2007年6月20日

CPOL

2分钟阅读

viewsIcon

31739

downloadIcon

209

概述一个允许将窗体控件绑定到 VB.NET 中具有索引器的属性的类。

引言

VB.NET(以及之前的 VB)的一个优点是创建索引属性的简易性。这意味着您可以编写如下形式的代码...

value = Object.Value(variable)

Object.Value(variable) = value

...而不是必须编写如下代码

select case variable

    case 0
    value = Object.ValuXe

    case 1
    value = Object.ValueY
     
    :
     
    case n

end select

这可以极大地简化使用该对象代码,而简单性(通常)意味着可靠性。然而,也存在一个缺点。无法直接将窗体控件绑定到索引属性。因此,复杂性会以需要从对象到控件再返回的代码形式重新出现,以及确保在正确的时间进行打包和解包所需的逻辑。

本文详细介绍了一个非常简单的类,BindingMap,它允许将控件绑定到索引属性,并希望我们能够回到更简单的客户端代码。BindingMap 类有一个构造函数和一个未索引的属性,MapValue。正是此属性绑定到控件。BindingMap 对象负责确保我们真正想要绑定的对象的正确属性值通过 MapValue 属性可用/设置。BindingMap 对象使用目标对象、其属性名称和要使用的索引值进行实例化。请注意,您一次只能将一个控件绑定到一个属性签名,但可以根据需要将控件重新绑定到不同的属性签名。

背景

如果您不熟悉对象和控件绑定,请快速查看窗体文本框控件的 DataBinding 属性。

使用代码

创建绑定映射很简单

' First the identify which indexed value of the 

' property you want to map to your control.

dim m as BindingMap = _
    new BindingMap(MyObject, "PropertyName", PropertyIndex)

' Now point the control data binding at the binding map...

b = new Binding("Text", m, "MapValue")
control.DataBindings.Add(b)

以下摘自示例项目,展示了它可能在实践中的使用方式。属性 Selectable 使用一个富有想象力地命名为 Index 的枚举进行索引。

' Instantiate our form level test object.

_test = new test

' First we have a standard binding to a run of the mill unindexed property...

dim b as Binding = new Binding("Text", _
    _test, _
    "Unadorned")
textboxA.DataBindings.Add(b)

' Now we bind an indexed property via our binding map.

b = new Binding("Text", _
    new BindingMap(_test, "Selectable", test.Index.Kappa), _
    "MapValue")
textboxK.DataBindings.Add(b)

'... and another to the 'b' index of the test::Selectable property

b = new Binding("Text", _
    new BindingMap(_test, "Selectable", test.Index.Beta), _
    "MapValue")
textboxB.DataBindings.Add(b)

如果希望单个控件表示索引属性的内容,并且根据用户输入更改所选属性,那么我们可以将绑定代码编写如下

sub Rebind(index as Object)
    textbox.DataBindings.Clear
    dim b as Binding = new Binding("Text", _
        new BindingMap(_test, "Selectable", index), _
        "MapValue")
    textbox.DataBindings.Add(b)
end sub

然后根据需要调用 Rebind 方法。

关注点

好吧,没有了。它只是一个解决一个令人恼火的小编码问题的直接解决方案。

历史

  • 2007.06.16 - 初稿
© . All rights reserved.