Ben*_*ers 3 c# textbox datasource
我通常使用 C++ 进行编程,因此所有这些 DataSource/DataSet/Binding 内容都让我感到困惑。希望你们能帮忙。
基本上,我正在为基于 XML 的文件格式(特别是用于金融数据的 OFX)编写一个编辑器。我在我的架构上使用 xsd.exe 将加载的文件反序列化为漂亮的、普通的旧类。我发现了 DataGridView,它非常棒,我可以将其 DataSource 属性设置为我感兴趣的集合之一(特别是事务列表),当我浏览这些值时,这些更改会反映在加载的值中反序列化的文件,然后我可以在保存时将其序列化。但是,当我只想将一个简单的字符串“映射”到文本框(例如帐号)时,我无法在文本框似乎没有数据源成员的情况下使用这种聪明的方法...使用它们的“文本”属性仅设置文本一次,不会将更改反映回底层对象,因此保存必须首先从控件中获取值。我希望它像 DataGridView 一样是自动的。
我尝试摆弄 DataBindings,但我不知道使用什么作为 propertyName 或 dataMember,所以我不确定这是否是我要使用的:
accountNumberTextBox.DataBindings.Add(new Binding("???", myDocument.accountNumber, "???");
Run Code Online (Sandbox Code Playgroud)
我是否遗漏了一些非常明显的东西?但愿如此!
您缺少的是strings 在 .NET 中是不可变的。因此,为了使绑定有意义,该string值需要用其他东西封装。然后,当用户输入值时,数据绑定系统将现有字符串替换为新字符串。
封装的其他东西string可以是DataTable包含更改通知的普通旧类。提供此更改通知的最佳方法是实现该INotifyPropertyChanged接口。
例如:
public class Document : INotifyPropertyChanged
{
private string _accountNumber;
public string AccountNumber
{
get { return _accountNumber; }
set
{
if (_accountNumber != value)
{
_accountNumber = value;
//this tells the data binding system that the value has changed, so the interface should be updated
OnPropertyChanged("AccountNumber");
}
}
}
//raised whenever a property value on this object changes. The data binding system attaches to this event
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged:
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Run Code Online (Sandbox Code Playgroud)
因此,您的数据绑定连接将如下所示:
var document = ...; //get document from somewhere
//bind the Text property on the TextBox to the AccountNumber property on the Document
textBox1.DataBindings.Add("Text", document, "AccountNumber");
Run Code Online (Sandbox Code Playgroud)