当前位置 : 主页 > 编程语言 > c语言 >

数据绑定101.如何在.Net中完成

来源:互联网 收集:自由互联 发布时间:2021-06-24
这似乎是一个显而易见的事情,但我无法弄明白.假设我有一个字符串列表.如何将其绑定到列表框,以便列表框随着列表数据的更改而更新?我正在使用vb.net. 到目前为止我已经尝试过了
这似乎是一个显而易见的事情,但我无法弄明白.假设我有一个字符串列表.如何将其绑定到列表框,以便列表框随着列表数据的更改而更新?我正在使用vb.net.

到目前为止我已经尝试过了.我设法显示数据,但不改变它:

Public Class Form1

    Private mycountries As New List(Of String)

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        mycountries.Add("Norway")
        mycountries.Add("Sweden")
        mycountries.Add("France")
        mycountries.Add("Italy")
        mycountries.Sort()
        ListBox1.DataSource = mycountries 'this works fine

    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        mycountries.RemoveAt(0)
        ListBox1.DataSource = mycountries 'this does not update
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        MsgBox(mycountries(0))
    End Sub
End Class

我也试过这个:

ListBox1.DataBindings.Add("items", mycountries, "Item")

但项目是只读的,所以它不起作用.

另外,如果我想将按钮的enabled属性绑定到布尔值,我该怎么做?
我试过这个,但我不知道为最后一个参数添加什么.

Dim b As Boolean = True
Button3.DataBindings.Add("Enabled", b, "")
您需要使用支持数据源更改通知的集合.从普通列表中删除项目时,它不会告诉任何人.

以下是使用BindingList的示例:

Public Class Form1

    Private mycountries As New BindingList(Of String)

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        mycountries.Add("Norway")
        mycountries.Add("Sweden")
        mycountries.Add("France")
        mycountries.Add("Italy")
        ' BindingList doesn't have a Sort() method, but you can sort your data ahead of time
        ListBox1.DataSource = mycountries 'this works fine

    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        mycountries.RemoveAt(0)
        ' no need to set the DataSource again here
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        MsgBox(mycountries(0))
    End Sub
End Class

对于第二个问题,在添加数据绑定时不会绑定到变量.绑定到对象(充当数据源),然后在该对象上指定一个属性,该属性将为您提供要绑定的值.

所以,对于一个按钮,你想要这样的东西(为C#道歉,但你会得到这个想法):

public class SomeModel
{
    public bool ButtonEnabled { get; set; }
}
public class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        SomeModel model = new SomeModel();

        // first parameter - button's property that should be bound
        // second parameter - object acting as the data source
        // third parameter - property on the data source object to provide value
        button1.DataBindings.Add("Enabled", model, "ButtonEnabled");
}

通常,数据绑定都是关于更改通知的.如果需要绑定到自定义对象,请查看INotifyPropertyChanged界面.

网友评论