Monday, March 26, 2007

Object binding with WPF

It took me some time to find a good sample of doing object binding with WPF. I decided to publish my sample.

I created a class called patient.

public class Patient
{
private int _id;
private string _name;
private string _picture;

public string Picture
{
get { return _picture; }
set { _picture = value; }
}

public Patient(int id, string name , string picture)
{
_id = id;
_name = name;
_picture = Picture;
}

public string Name
{
get { return _name; }
set { _name = value; }
}
public int ID
{
get { return _id; }
set { _id = value; }
}
}

This patient class is filled with data by an engine class. This engine class is called PatientEngine.

public class PatientsEngine
{
public static List GetPatients()
{
List pList = new List();
Patient p1 = new Patient(1, "Jack", "Images/Jack.png");
Patient p2 = new Patient(2, "Jim", "Images/Jim.png");
Patient p3 = new Patient(3, "Johny", "Images/Johny.png");
pList.Add(p1);
pList.Add(p2);
pList.Add(p3);
return pList;
}
}

This class has a static method to fill the generic list of patients.

To call the engine you need to

  1. Create a new windows XAML application
  2. Open the window1 file
  3. Add in the window tag the namespace declaration where your engine is located, in my case in "WindowsApplication4" do this by adding this line.
    xmlns:src="clr-namespace:WindowsApplication4"
  4. Add the ObjectDataProvider in the element
    <objectdataprovider key="patients" objecttype="{x:Type src:PatientsEngine}" methodname="GetPatients"></objectdataprovider>
  5. Create a data template



    <DataTemplate x:Key="patientFormating" DataType="Patient">
    <StackPanel Orientation="Vertical">
    <TextBlock>
    <TextBlock.Text>
    <Binding Path="Name" />
    </TextBlock.Text>
    </TextBlock>
    <Image>
    <Image.Source>
    <Binding Path="Picture" />
    </Image.Source>
    </Image>
    </StackPanel>
    </DataTemplate>
  6. Add the code to display a listview in a DockPanel


    <DockPanel DataContext="{Binding Source={StaticResource patients}}" Grid.Column="0" Grid.Row="0">
    <ListView x:Name="listView1" ItemsSource="{Binding }" ItemTemplate="{DynamicResource patientFormating}" IsSynchronizedWithCurrentItem="True" DockPanel.Dock="Left" />
    </DockPanel />


3 comments:

Stephen said...

Nice article, it has helped me understand the WPF prinicipals and get a list view working in a similar manner.

There is just one typo:

public Patient(int id, string name , string picture)
{
_id = id;
_name = name;
_picture = Picture;
}

The Picture should be lowercase picture, otherwise as I found out the picture property is never actually set.

Stephen

Anonymous said...

would you like to give full example code?

rhyous said...

You so need to learn to post your code with proper tags to keep the formatting. Blogspot surely must have such formatting capabilities.