Posts Tagged ‘bidirectional’

How to implement bidirectional binding in Flex

// March 12th, 2008 // No Comments » // Tips & Tricks

In this post I’ll show you how to implement a bidirectional binding between a DataGrid and a Form in such a way that any change in the Form will automatically affect data displayed in the DataGrid.

To obtain such a bidirectional binding we have to:

  • define a model object
  • define a binding between Form fields and object properties
  • define a binding between DataGrid and the model object

Here is the simplified code to realize all this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?xml version="1.0" encoding="utf-8"?>
<mx:Application
  xmlns:mx="http://www.adobe.com/2006/mxml"
  xmlns:wg="com.webgriffe.samples.*">
  <mx:ArrayCollection id="employees">
    <wg:Person>
      <wg:name>Christina Coenraets</wg:name>
      <wg:phone>555-219-2270</wg:phone>
      <wg:email>ccoenraets@fictitious.com</wg:email>
    </wg:Person>
    <wg:Person>
      <wg:name>Joanne Wall</wg:name>
      <wg:phone>555-219-2012</wg:phone>
      <wg:email>jwall@fictitious.com</wg:email>
    </wg:Person>
   <wg:Person>
     <wg:name>Maurice Smith</wg:name>
     <wg:phone>555-219-2012</wg:phone>
     <wg:email>maurice@fictitious.com</wg:email>
   </wg:Person>
  </mx:ArrayCollection>  <wg:Person id="per"
    name="{inName.text}"
    phone="{inPhone.text}"
    email="{inEmail.text}" />
    <mx:Panel title="DataGrid e Form - binding bidirezionale">
    <mx:Label text="Select a row in the DataGrid control."/>
    <mx:DataGrid id="dg" dataProvider="{employees}"
      itemClick="per=Person(event.currentTarget.selectedItem);">
      <mx:columns>
        <mx:DataGridColumn
            dataField="name"
            headerText="Name"/>
        <mx:DataGridColumn
            dataField="phone"
            headerText="Phone"/>
        <mx:DataGridColumn
            dataField="email"
            headerText="Email"/>
      </mx:columns>
    </mx:DataGrid>
    <mx:Form>
      <mx:FormItem label="Name">
        <mx:TextInput id="inName" text="{per.name}"/>
      </mx:FormItem>
      <mx:FormItem label="Phone">
        <mx:TextInput id="inPhone" text="{per.phone}"/>
      </mx:FormItem>
      <mx:FormItem label="Email">
        <mx:TextInput id="inEmail" text="{per.email}"/>
      </mx:FormItem>
    </mx:Form>
  </mx:Panel>
</mx:Application>