作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这似乎是一件显而易见的事情,但我就是想不通。假设我有一个字符串列表。如何将它绑定(bind)到列表框,以便列表框随着列表数据的变化而更新?我正在使用 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")
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
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
界面。
关于.net - 数据绑定(bind) 101. 如何在 .Net 中进行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7348323/
我是一名优秀的程序员,十分优秀!