How to Data Bind an Object to ListBox Control using C#.NET / Data Templates in C# Windows Phone Application
My director friend Kee Ran was pestering for an App that provides a list of Girivalam (a circumambulation) dates for his assistance. Attempted the same using Silverlight Data Template (Listbox) . The original grid as shown below:
It's been quite sometime since we had used a databinding (
How to Bind an Object to TextBox) First things first, let us create a class that will hold this data
public class GirivalamDates
{
public string GirivalamMonth { get; set; }
public string GirivalamStartDt { get; set; }
public string GirivalamStartTime { get; set; }
public string GirivalamStartDay { get; set; }
public string GirivalamEndDt { get; set; }
public string GirivalamEndTime { get; set; }
public string GirivalamEndDay { get; set; }
}
}
Once the class is created, create some objects of this type and it to a List.
gDates = new List();
gDates.Add(new GirivalamDates
{
GirivalamMonth = "Mon",
GirivalamStartDt = "Start",
GirivalamStartTime = "Date",
GirivalamStartDay = " ",
GirivalamEndDt = "End ",
GirivalamEndTime = "Date",
GirivalamEndDay = " "
});
Add more to the List and then, create the XAML for the same
<StackPanel x:Name="ContentPanel" Margin="12,0" Grid.Row="1">
<ScrollViewer HorizontalScrollBarVisibility="Visible">
<ListBox
Name
="myItemsControl" VerticalAlignment="Top">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<TextBlock
Grid.Column="0" Text="{Binding GirivalamMonth}"
FontSize="{StaticResource PhoneFontSizeMedium}"
/>
<TextBlock
Grid.Column="1" Text="{Binding GirivalamStartDt}"
FontSize="{StaticResource PhoneFontSizeMedium}"
/>
<TextBlock
Grid.Column="2" Text="{Binding GirivalamStartTime}"
FontSize="{StaticResource PhoneFontSizeMedium}"
/>
<TextBlock
Grid.Column="3" Text="{Binding GirivalamStartDay}"
FontSize="{StaticResource PhoneFontSizeMedium}"
/>
<TextBlock
Grid.Column="4" Text="{Binding GirivalamEndDt}"
FontSize="{StaticResource PhoneFontSizeMedium}"
/>
<TextBlock
Grid.Column="5" Text="{Binding GirivalamEndTime}"
FontSize="{StaticResource PhoneFontSizeMedium}"
/>
<TextBlock
Grid.Column="6" Text="{Binding GirivalamEndDay}"
FontSize="{StaticResource PhoneFontSizeMedium}"
/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ListBox>
</
ScrollViewer>
</StackPanel>
The TextBlock's Text attribute is bound to the appropriate property of the GirivalamDates class.
Finally bind the ListBox control to the gDates object.
myItemsControl.ItemsSource = gDates;