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
{
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
xmlns:src="clr-namespace:WindowsApplication4"
<objectdataprovider key="patients" objecttype="{x:Type src:PatientsEngine}" methodname="GetPatients"></objectdataprovider>
<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>
<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:
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
would you like to give full example code?
You so need to learn to post your code with proper tags to keep the formatting. Blogspot surely must have such formatting capabilities.
Post a Comment