数据绑定到 C# 中的对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/715346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 22:14:05  来源:igfitidea点击:

Data Binding to an object in C#

c#.netdata-binding

提问by Allen

Objective-c/cocoa offers a form of binding where a control's properties (ie text in a textbox) can be bound to the property of an object. I am trying to duplicate this functionality in C# w/ .Net 3.5.

Objective-c/cocoa 提供了一种绑定形式,其中控件的属性(即文本框中的文本)可以绑定到对象的属性。我正在尝试在带有 .Net 3.5 的 C# 中复制此功能。

I have created the following very simple class in the file MyClass.cs:

我在文件 MyClass.cs 中创建了以下非常简单的类:

class MyClass
{
    private string myName;

    public string MyName
    {
        get
        {
            return myName;
        }

        set
        {
            myName = value;
        }
    }

    public MyClass()
    {
        myName = "Allen";
    }
}

I also created a simple form with 1 textbox and 1 button. I init'd one instance of Myclass inside the form code and built the project. Using the DataSource Wizard in Vs2008, I selected to create a data source based on object, and selected the MyClass assembly. This created a datasource entity. I changed the databinding of the textbox to this datasource; however, the expected result (that the textbox's contents would be "allen") was not achieved. Further, putting text into the textbox is not updating the name property of the object.

我还创建了一个带有 1 个文本框和 1 个按钮的简单表单。我在表单代码中初始化了一个 Myclass 实例并构建了项目。使用Vs2008中的DataSource Wizard,我选择基于对象创建数据源,选择MyClass程序集。这创建了一个数据源实体。我将文本框的数据绑定更改为该数据源;但是,没有达到预期的结果(文本框的内容为“allen”)。此外,将文本放入文本框不会更新对象的 name 属性。

I know i'm missing something fundamental here. At some point i should have to tie my instance of the MyClass class that i initialized inside the form code to the textbox, but that hasn't occurred. Everything i've looked at online seems to gloss over using DataBinding with an object (or i'm missing the mark entirely), so any help is great appreciated.

我知道我在这里遗漏了一些基本的东西。在某些时候,我应该将我在表单代码中初始化的 MyClass 类的实例绑定到文本框,但这并没有发生。我在网上看到的所有内容似乎都掩盖了将 DataBinding 与对象一起使用(或者我完全没有标记),因此非常感谢任何帮助。

Edit:

编辑:

Utilizing what I learned by the answers, I looked at the code generated by Visual Studio, it had the following:

利用我从答案中学到的知识,我查看了 Visual Studio 生成的代码,它具有以下内容:

this.myClassBindingSource.DataSource = typeof(BindingTest.MyClass);

if I comment that out and substitute:

如果我将其注释掉并替换:

this.myClassBindingSource.DataSource = new MyClass();

I get the expected behavior. Why is the default code generated by VS like it is? Assuming this is more correct than the method that works, how should I modify my code to work within the bounds of what VS generated?

我得到了预期的行为。为什么VS生成的默认代码是这样的?假设这比有效的方法更正确,我应该如何修改我的代码以在 VS 生成的范围内工作?

采纳答案by Jason Coyne

You must assign the textbox's data source to be your new datasource. But additionally, you must assign the datasource's datasource to be an instance of your class.

您必须将文本框的数据源指定为新数据源。但此外,您必须将数据源的数据源分配为您的类的实例。

MyDataSource.DataSource = new MyClass();
TextBox1.DataSource = MyDataSource;

That should work for your first pass. As others have mentioned, you may need to implement additional interfaces on your class (INotifyPropertyChanged etc), if you are going to be modifying the class properties via any background processes.

这应该适用于您的第一次通过。正如其他人所提到的,如果您要通过任何后台进程修改类属性,您可能需要在您的类上实现额外的接口(INotifyPropertyChanged 等)。

If you are only updating the properties via the form, then you do not need this step.

如果您只是通过表单更新属性,则不需要此步骤。

回答by Frederik Gheysels

You should implement the INotifyPropertyChanged interface to your MyClass type:

您应该为 MyClass 类型实现 INotifyPropertyChanged 接口:

public class MyClass : INotifyPropertyChanged
{
   private string _myName;

   public string MyName
   {
       get { return _myName; }
       set
       {
          if( _myName != value )
          {
              _myName = value;
              OnPropertyChanged("MyName");
          }
       }
   }

   public event PropertyChangedEventHandler PropertyChanged;

   private void OnPropertyChanged(string propertyName)
   {
       if( PropertyChanged != null )
           PropertyChanged( this , new PropertyChangedEventArgs(propertyName) );
   }       
}

This interface is required for the DataBinding infrastructure if you want to support simple databinding. The INotifyPropertyChanged interface is used to notify a 'binding' that a property has changed, so the DataBinding infrastructure can act accordingly to it.

如果要支持简单数据绑定,则 DataBinding 基础结构需要此接口。INotifyPropertyChanged 接口用于通知“绑定”属性已更改,因此 DataBinding 基础结构可以对其进行相应操作。

Then, you can databind the MyName property to the Text Property of the textbox.

然后,您可以将 MyName 属性数据绑定到文本框的 Text 属性。

回答by C???

Looks like you probably need a Bindable attribute on your MyName property (and follow Frederik's suggestion as well):

看起来您可能需要 MyName 属性上的 Bindable 属性(并遵循 Frederik 的建议):

   [System.ComponentModel.Bindable(true)] 
   public string MyName
   {
       get { return _myName; }
       set
       {
          if( _myName != value )
          {
              _myName = value;
              OnPropertyChanged("MyName");
          }
       }
   }

Via: http://support.microsoft.com/kb/327413

通过:http: //support.microsoft.com/kb/327413

回答by Don Kirkby

I don't have any code in front of me, but I think the data source is kind of like a collection. You have to add an instance of MyClass to the data source, and that's what the form fields will bind to. There's also methods for navigating through the data source to multiple instances of MyClass, but it doesn't sound like you need that. Check the docs for DataSource.

我面前没有任何代码,但我认为数据源有点像一个集合。您必须将 MyClass 的实例添加到数据源,这就是表单字段将绑定到的内容。还有一些方法可以将数据源导航到 MyClass 的多个实例,但听起来您并不需要那样做。检查数据源的文档。

I don't think you need to implement any fancy interfaces. I seem to remember there's a method on the data source that lets you refresh or rebind the current item after you change some values.

我认为您不需要实现任何花哨的接口。我似乎记得数据源上有一种方法可以让您在更改某些值后刷新或重新绑定当前项目。

回答by Ron Maman

I get an error message in the DataBinding.Add("TEXT", myObject, myObjectProperty)method

我在DataBinding.Add("TEXT", myObject, myObjectProperty)方法中收到一条错误消息

This is probably because you're missing the explicit {get;set;} on the property declaration!

这可能是因为您在属性声明中遗漏了明确的 {get;set;}!

BAD:

坏的:

public string FirstName;    //<-- you will not be able to bind to this property!

GOOD:

好的:

public string FirstName { get; set; }

回答by Alastairgraeme

using System.Collections.Generic;

public class SiteDataItem
{ 
private string _text; 
private string _url; 
private int _id; 
private int _parentId;

public string Text
{  
    get 
    { 
        return _text; 
    }  
    set 
    { 
        _text = value;
    } 
}

public string Url 
{  
    get 
    { 
        return _url; 
    }  
    set 
    { 
        _url = value;
    } 
}
public int ID 
{  
    get 
    { 
        return _id;
    }  
    set 
    { 
        _id = value;
    } 
}
public int ParentID 
{  
    get 
    { 
        return _parentId;
    } 
    set 
    { 
        _parentId = value;
    } 
}
public SiteDataItem(int id, int parentId, string text, string url)
{  
    _id = id;
    _parentId = parentId;
    _text = text;
    _url = url;
}

public static List<SiteDataItem> GetSiteData() 
{  
    List<SiteDataItem> siteData = new List<SiteDataItem>();
    siteData.Add(new SiteDataItem(1, 0, "All Sites", ""));  
    siteData.Add(new SiteDataItem(2, 1, "Search Engines", ""));
    siteData.Add(new SiteDataItem(3, 1, "News Sites", ""));
    siteData.Add(new SiteDataItem(4, 2, "Yahoo", "http://www.yahoo.com"));
    siteData.Add(new SiteDataItem(5, 2, "MSN", "http://www.msn.com"));  
    siteData.Add(new SiteDataItem(6, 2, "Google", "http://www.google.com"));  
    siteData.Add(new SiteDataItem(7, 3, "CNN", "http://www.cnn.com"));  
    siteData.Add(new SiteDataItem(8, 3, "BBC", "http://www.bbc.co.uk"));  
    siteData.Add(new SiteDataItem(9, 3, "FOX", "http://www.foxnews.com"));
    return siteData; 
}
}

More detail you can read tutorial dapfor. com

更多细节你可以阅读教程 dapfor。电脑