LiveBindings如何绑定一个对象

2024-09-06 14:38
文章标签 对象 绑定 livebindings

本文主要是介绍LiveBindings如何绑定一个对象,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、新建VCL工程加入TAdapterBingSource控件

二、定一个TPerson类 

MyPerson : TPerson;
复制代码
复制代码
 TPerson = classprivateFAge: Integer;FLastname: string;FFirstname: string;publicconstructor Create(const Firstname, Lastname : string; Age : Integer); virtual;property Firstname : string read FFirstname write FFirstname;property Lastname : string read FLastname write FLastname;property Age : Integer read FAge write FAge;end;
复制代码
复制代码

三、双击并加入事件代码

1.创建一个对象实列Person

2.创建一个BindSourceAdapter

  • self,   指定TObjectBindSource的归属
  • MyPerson,需要邦定对象实例
  • True,是否自动释放,如果否则False 默认值为True
复制代码
复制代码
procedure TForm4.AdapterBindSource1CreateAdapter(Sender: TObject;var ABindSourceAdapter: TBindSourceAdapter);
beginMyPerson :=TPerson.Create('test','test1', 13);ABindSourceAdapter := TObjectBindSourceAdapter<TPerson>.Create(Self, MyPerson, True);
end;
复制代码
复制代码

 

 

四、放一个TStringGrid对象 在Events LiveBindings点击BindVisually

点击运行

 

=====================================================

 

以下为原话

 

LiveBindings in XE3: TAdapterBindSource and binding to Objects

In the last post I introduced BindSources, a new set of classes in the LiveBinding system in RAD Studio XE3, and in particular, looked at TBindSourceDB. That’s fine if what you are binding to is a Dataset, but what happens if what you want to bind to is an object?

Binding to objects was possible in LiveBindings in XE2, and that approach will still work, however it doesn’t leverage all the LiveBinding Designer goodness.

Well, an easy answer would be “Do it the same way you did it in XE2″. Binding to objects was possible in LiveBindings in XE2, and that approach will still work, however it doesn’t leverage all the LiveBinding Designer goodness.

A better answer, if we want to both use the LiveBinding Designer and do the minimal amount of work, is to use another of the BindSource components: the TAdapterBindSource.

Whereas the TBindSourceDB acted as a gateway to allow us to connect the LiveBindings engine to fields in a dataset, a TAdapterBindSource allows us to connect it to elements in an Adapter. What’s an Adapter? Well, it’s a descendant of TBindSourceAdapter, who’s responsibility it is to take your custom data source (in this case an object) and make it available (ie. adapt it) to the TAdapterBindSource, and by extension, the LiveBinding engine.

An example is probably in order, then we’ll come back and drill in a bit further.

Create a new FireMonkey project (LiveBindings are available in VCL too), and in the form source define a new class like this:

typeTPerson = classprivateFAge: Integer;FLastname: string;FFirstname: string;publicconstructor Create(const Firstname, Lastname : string; Age : Integer); virtual;property Firstname : string read FFirstname write FFirstname;property Lastname : string read FLastname write FLastname;property Age : Integer read FAge write FAge;end;

The constructor, not surprisingly, is implemented like this:

constructor TPerson.Create(const Firstname, Lastname: string; Age : Integer);
beginFFirstname := Firstname;FLastname := Lastname;FAge := Age;
end;

Note, I didn’t have to use properties to make this work, it works just as well with Fields. Old habits die hard I guess.

Also, add a private field to your form like so:

MyPerson : TPerson;

Next, drop a TAdapterBindSource on the form and put the following code in its OnCreateAdapter event:

procedure TForm4.AdapterBindSource1CreateAdapter(Sender: TObject;var ABindSourceAdapter: TBindSourceAdapter);
beginMyPerson := TPerson.Create('Fred', 'Flintstone', 40);ABindSourceAdapter := TObjectBindSourceAdapter<TPerson>.Create(self, MyPerson, True);
end;

The first line is not that interesting: I’m creating an instance of our TPerson class. However it’s the second line where we encounter our first adapter. The OnCreateAdapter event has a var parameter of type TBindSourceAdapter called ABindSourceAdapter. I need to create an instance of a TBindSourceAdapter (usually of a descendant) and pass it back to the TAdapterBindSource via this var parameter.

That’s what the second line does. You can see we’re creating an instance of a generic TObjectBindSourceAdapter<T>, specifically a TObjectBindSourceAdapter<TPerson>. I’m passing the following values in to the constructor:

  • self, as the TObjectBindSource’s owner (it’s a TComponent descendant)
  • MyPerson, which is the instance of the TPerson I want to adapt.
  • True, indicating that I want to make the TObjectBindSourceAdapter responsible for freeing my TPerson instance (this is actually the default, but I included it here for completeness)

This is actually enough to get started. If you drop a Grid down on the form, drag a link between the * field in the AdapterBindSource to the * in the Grid in the LiveBindings Designer (see the bottom of the screenshot below) and run your app you should see the values of our Person instance in the Grid.

That’s useful as far as it goes, but there is a problem: I can’t see the Firstname, Lastname and Age properties in the LiveBindings Designer, which makes it a manual process to bind one of those values to say an Edit box or Label. We’ve cheated by using the * property of the AdapterBindSource but unless we’re happy using a grid to display a single TPerson, we’re going to need to solve this. (We’ll come back to collections of objects later, I promise)

To get the fields of my object to show up in the LiveBindings designer, we can leverage another new component in XE3, a TDataGeneratorAdapter.

To get the fields of my object to show up in the LiveBindings designer, we can leverage another new component in XE3, a TDataGeneratorAdapter. This is another TBindSourceAdapter descendant, and in fact this one is installed on the component palette (I did mention before that TBindSourceAdapters were TComponents). A TDataGeneratorAdapter allows you to define one or more fields in your adapter, along with an accompanying generator that will generate some format of values for your field, at both design time and run time if you like. Drop one onto your form and then bring up the property editor for the TDataGeneratorAdapter.FieldDefs property and have a look:

As you can see, there is a Booleans generator that will generate random boolean values, random currency generators, date generators for both TDate types and also strings containing date values. Scroll further down and there are even String and TStrings generators that will fill return Lorem Ipsum text.

Let’s create three fields to match the name and type of our TPerson object like so:

Now select your AdapterBindSource and set its Adapter property to point to our DataGeneratorAdapter component. Make sure the DataGeneratorAdapter is set to Active and at design time you should see something like this:

Not only do we have design-time data in our grid (courtesy of our generators), but we also now have the fields showing up in the LiveBinding Designer so we can start easily binding their values to other controls.

Because we still have the OnCreateAdapter event setup, and further, because the names of the fields we created in our DataGeneratorAdapter match the field names in our TPerson class, if we run the app now our DataGeneratorAdapter will be replaced as the adapter for the AdapterBindSource by our TObjectBindSourceAdapter, giving us an easy design-time experience while still giving us data from our object at runtime. If we removed this event, the AdapterBindSource would continue to use the DataGeneratorAdapter at runtime as well.

A few things to note here:

  • The DataGeneratorAdapter is creating these field values on the fly as requested, but once created they behave like a dataset. ie. you can edit them, post them, navigate around and they retain their values.
  • You could just as easily use the DataGeneratorAdapter when binding to a dataset. Let’s say you need to prototype a form for a table that does not yet exist. Use the DataGeneratorAdapter as above, show the prototype to the customer, and once they sign off on it then go ahead and build out the actually database table and datasets later. In fact there is another component included in XE3 called TPrototypeBindSource which is basically a combination of the TAdapterBindSource and the TDataGeneratorAdapter to make this scenario even easier. I plan on posting about this component in a future article, but in the meantime there is a tutorial available in the Help.

Now that we have fields showing up in the LiveBindings Designer, you can go ahead and replace the grid with components more appropriate for displaying a single object instance if you wish. You can do this either by adding the component to the form and dragging in the designer to create the link, or right-click on the fields in the designer and select “Bind to new control…”. (check out the previous article if you need a refresher)

However I’m going to leave the grid there, as I want to come good on the promise I made earlier: to look at binding to a collection of objects.

Let’s change the MyPerson field that we added to our form earlier to look like:

  MyPeople : TObjectList<TPerson>;

Then, go back into the source in your AdapterBindSource1.OnCreateAdapter event and change it to look like this:

procedure TForm4.AdapterBindSource1CreateAdapter(Sender: TObject;var ABindSourceAdapter: TBindSourceAdapter);
beginMyPeople := TObjectList<TPerson>.Create;MyPeople.Add(TPerson.Create('Fred', 'Flintstone', 40));MyPeople.Add(TPerson.Create('Wilma', 'Flintstone', 41));MyPeople.Add(TPerson.Create('Barney', 'Rubble', 40));MyPeople.Add(TPerson.Create('Betty', 'Rubble', 39));ABindSourceAdapter := TListBindSourceAdapter<TPerson>.Create(self, MyPeople, True);
end;

You can see we’re creating a TObjectList, we’re adding a few instances to it, and then rather than creating a TObjectBindSourceAdapter, we’re creating a TListBindSourceAdapter. That’s all we need to do.

Run your app, and you should see the four TPerson instances we created in the grid. Further, if you right-click on the AdapterBindSource at designtime and add a Navigator, at runtime you can click the Insert button in the Navigator and it will add a new TPerson instance to our list, ready for editing.

That’s enough for this post, but we’re not quite done with this topic. Next post I want to look at editing the data in your objects, as using the Adapters in the way we just have raises a couple of interesting issues that aren’t immediately obvious (or at least they weren’t to me).

这篇关于LiveBindings如何绑定一个对象的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1142293

相关文章

在java中如何将inputStream对象转换为File对象(不生成本地文件)

《在java中如何将inputStream对象转换为File对象(不生成本地文件)》:本文主要介绍在java中如何将inputStream对象转换为File对象(不生成本地文件),具有很好的参考价... 目录需求说明问题解决总结需求说明在后端中通过POI生成Excel文件流,将输出流(outputStre

基于@RequestParam注解之Spring MVC参数绑定的利器

《基于@RequestParam注解之SpringMVC参数绑定的利器》:本文主要介绍基于@RequestParam注解之SpringMVC参数绑定的利器,具有很好的参考价值,希望对大家有所帮助... 目录@RequestParam注解:Spring MVC参数绑定的利器什么是@RequestParam?@

C#原型模式之如何通过克隆对象来优化创建过程

《C#原型模式之如何通过克隆对象来优化创建过程》原型模式是一种创建型设计模式,通过克隆现有对象来创建新对象,避免重复的创建成本和复杂的初始化过程,它适用于对象创建过程复杂、需要大量相似对象或避免重复初... 目录什么是原型模式?原型模式的工作原理C#中如何实现原型模式?1. 定义原型接口2. 实现原型接口3

Java实现将byte[]转换为File对象

《Java实现将byte[]转换为File对象》这篇文章将通过一个简单的例子为大家演示Java如何实现byte[]转换为File对象,并将其上传到外部服务器,感兴趣的小伙伴可以跟随小编一起学习一下... 目录前言1. 问题背景2. 环境准备3. 实现步骤3.1 从 URL 获取图片字节数据3.2 将字节数组

Javascript访问Promise对象返回值的操作方法

《Javascript访问Promise对象返回值的操作方法》这篇文章介绍了如何在JavaScript中使用Promise对象来处理异步操作,通过使用fetch()方法和Promise对象,我们可以从... 目录在Javascript中,什么是Promise1- then() 链式操作2- 在之后的代码中使

MyBatis的配置对象Configuration作用及说明

《MyBatis的配置对象Configuration作用及说明》MyBatis的Configuration对象是MyBatis的核心配置对象,它包含了MyBatis运行时所需的几乎所有配置信息,这个对... 目录MyBATis配置对象Configuration作用Configuration 对象的主要作用C

SpringBoot实现导出复杂对象到Excel文件

《SpringBoot实现导出复杂对象到Excel文件》这篇文章主要为大家详细介绍了如何使用Hutool和EasyExcel两种方式来实现在SpringBoot项目中导出复杂对象到Excel文件,需要... 在Spring Boot项目中导出复杂对象到Excel文件,可以利用Hutool或EasyExcel

Springboot控制反转与Bean对象的方法

《Springboot控制反转与Bean对象的方法》文章介绍了SpringBoot中的控制反转(IoC)概念,描述了IoC容器如何管理Bean的生命周期和依赖关系,它详细讲解了Bean的注册过程,包括... 目录1 控制反转1.1 什么是控制反转1.2 SpringBoot中的控制反转2 Ioc容器对Bea

Java对象和JSON字符串之间的转换方法(全网最清晰)

《Java对象和JSON字符串之间的转换方法(全网最清晰)》:本文主要介绍如何在Java中使用Jackson库将对象转换为JSON字符串,并提供了一个简单的工具类示例,该工具类支持基本的转换功能,... 目录前言1. 引入 Jackson 依赖2. 创建 jsON 工具类3. 使用示例转换 Java 对象为

Java中对象的创建和销毁过程详析

《Java中对象的创建和销毁过程详析》:本文主要介绍Java中对象的创建和销毁过程,对象的创建过程包括类加载检查、内存分配、初始化零值内存、设置对象头和执行init方法,对象的销毁过程由垃圾回收机... 目录前言对象的创建过程1. 类加载检查2China编程. 分配内存3. 初始化零值4. 设置对象头5. 执行