数据绑定101.如何在.Net中完成
发布时间:2020-12-17 07:15:46 所属栏目:百科 来源:网络整理
导读:这似乎是一个显而易见的事情,但我无法弄明白.假设我有一个字符串列表.如何将其绑定到列表框,以便列表框随着列表数据的更改而更新?我正在使用vb.net. 到目前为止我已经尝试过了.我设法显示数据,但不改变它: Public Class Form1 Private mycountries As New
这似乎是一个显而易见的事情,但我无法弄明白.假设我有一个字符串列表.如何将其绑定到列表框,以便列表框随着列表数据的更改而更新?我正在使用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,"") 解决方法
您需要使用支持数据源更改通知的集合.从普通列表中删除项目时,它不会告诉任何人.
以下是使用 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"); } 通常,数据绑定都是关于更改通知的.如果需要绑定到自定义对象,请查看 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |