Friday 21 May 2010

Friday 14 May 2010

Working with Silverlight DataGrid RowDetailsTemplate

In this post I am going to show how we can use the Silverlight DataGrid RowDetails Template, Before I start I assume that you know basics of Silverlight and also know how you create a Silverlight Projects.

I have started with the Silverlight Application, and kept all the default options before I created a Silverlight Project.

After this I added a Silverlight DataGrid control to my MainForm.xaml page, using the DragDrop feature of Visual Studio IDE, this will help me to add the default namespace and references automatically.

Just to give you a quick look of what exactly I am going to do, I will show you in the screen below my final target, before I start explaining rest of my codes.

image

Before I start with the real code, first I have to do some ground work, as I am not getting the data from the DB, so I am creating a class where I will populate the dummy data.

EmployeeData.cs

public class EmployeeData
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Country { get; set; }

public EmployeeData()
{ }

public List<EmployeeData> GetEmployeeData()
{
List<EmployeeData> employees = new List<EmployeeData>();
employees.Add
(
new EmployeeData
{
Address = "#407, PH1, Foyer Appartment",
City = "Bangalore",
Country = "India",
FirstName = "Brij",
LastName = "Mohan",
State = "Karnataka"
});
employees.Add
(
new EmployeeData
{
Address = "#332, Dayal Niketan",
City = "Jamshedpur",
Country = "India",
FirstName = "Arun",
LastName = "Dayal",
State = "Jharkhand"
});
employees.Add
(
new EmployeeData
{
Address = "#77, MSR Nagar",
City = "Bangalore",
Country = "India",
FirstName = "Sunita",
LastName = "Mohan",
State = "Karnataka"
});
return employees;
}
}



The above class will give me some sample data, I think this will be good enough to start with the actual code. now I am giving below the XAML code from my MainForm.xaml



First I will put the Silverlight DataGrid,



<data:DataGrid x:Name="gridEmployee" CanUserReorderColumns="False" CanUserSortColumns="False"
RowDetailsVisibilityMode="VisibleWhenSelected"
HorizontalAlignment="Center" ScrollViewer.VerticalScrollBarVisibility="Auto"
Height="200" AutoGenerateColumns="False" Width="350" VerticalAlignment="Center">

Here, the most important property which I am going to set is

RowDetailsVisibilityMode="VisibleWhenSelected"


This will display the RowDetails only when we select the desired Row. Other option we have in this is Collapsed and Visible. Which will either make the row details always Visible or Always Collapsed. but to get the real effect I have selected VisibleWhenSelected.



Now I am going to put the rest of my XAML code.



            <data:DataGrid.Columns>
<!--Begin FirstName Column-->
<data:DataGridTextColumn Width="150"
Header="First Name"
Binding="{Binding FirstName}"/>
<!--End FirstName Column-->

<!--Begin LastName Column-->
<data:DataGridTextColumn Width="150"
Header="Last Name"
Binding="{Binding LastName}"/>
<!--End LastName Column-->
</data:DataGrid.Columns>

<
data:DataGrid.RowDetailsTemplate>
<!-- Begin row details section. -->
<DataTemplate>
<
Border BorderBrush="Black"
BorderThickness="1" Background="White">
<
Grid>
<
Grid.ColumnDefinitions>
<
ColumnDefinition Width="0.2*" />
<
ColumnDefinition Width="0.8*" />
</
Grid.ColumnDefinitions>
<
Grid.RowDefinitions>
<
RowDefinition />
<
RowDefinition />
<
RowDefinition />
<
RowDefinition />
</
Grid.RowDefinitions>
<!-- Controls are bound to FullAddress properties. -->
<TextBlock Text="Address : "
Grid.Column="0" Grid.Row="0" />
<
TextBlock Text="{Binding Address}"
Grid.Column="1" Grid.Row="0" />

<
TextBlock Text="City : "
Grid.Column="0" Grid.Row="1" />
<
TextBlock Text="{Binding City}"
Grid.Column="1" Grid.Row="1" />

<
TextBlock Text="State : "
Grid.Column="0" Grid.Row="2" />
<
TextBlock Text="{Binding State}"
Grid.Column="1" Grid.Row="2" />

<
TextBlock Text="Country : "
Grid.Column="0" Grid.Row="3" />
<
TextBlock Text="{Binding Country}"
Grid.Column="1" Grid.Row="3" />
</
Grid>
</
Border>
</
DataTemplate>
<!-- End row details section. -->
</data:DataGrid.RowDetailsTemplate>


 




In the code above, first I am declaring the simple dataGridTextColumn for FirstName and LastName, and after this I am creating the RowDetailTemplate, where we are just putting the code what we usually do to design the Grid. I mean nothing very much RowDetailTemplate Specific, most of the code which you will see inside the RowDetailsTemplate is plain and simple, where I am binding rest of the Address Column. And that,s it. Once we will bind the DataGrid, you are ready to go.




In the code below from MainForm.xaml.cs, I am just binding the DataGrid



public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
BindControls();
}

private void BindControls()
{
EmployeeData employees = new EmployeeData();
gridEmployee.ItemsSource = employees.GetEmployeeData();
}
}


Once you will run, you can see the output I have given in the screenshot above.




In this example I have just shown the very basic example, now it up to your creativity and requirement, you can put some other controls like checkbox, Images, even other DataGrid, etc inside this RowDetailsTemplate column.





I am attaching my sample source code with this post. I have used Silverlight 3 and Visual Studio 2008, but this is fully compatible with you Silverlight 4 and Visual Studio 2010. you may just need to Upgrade the attached Sample.




You can download from here. Also you can find the better formatted version of the post here.

Share:

Thursday 13 May 2010

Simple Preferred time control using Silverlight.

Here I am going to show you a simple preferred time control, where you can select the day of the week and the time of the day. This can be used in lots of place where you may need to display the users preferred times. Sample screenshot is attached below.

image

This control is developed using Silverlight 3 and VS2008, I am also attaching the source code with this post. This is a very basic example. You can download and customize if further for your requirement if you want.

I am trying to explain in few words how this control works and what are the different ways in which you can customize it further.

File: PreferredTimeControl.xaml, in this file I have just hardcoded the controls and their positions which you can see in the screenshot above. In this example, to change the start day of the week and time, you will have to go and change the design in XAML file, its not controlled by your properties or implementation classes. You can also customize it to change the start day of the week, Language, Display format, styles, etc, etc.

File: PreferredTimeControl.xaml.cs, In this control using the code below, first I am taking all the checkbox from my form and store it in the Global Variable, which I can use across my page.

List<CheckBox> checkBoxList;

#region Constructor
public PreferredTimeControl()
{
InitializeComponent();
GetCheckboxes();//Keep all the checkbox in List in the Load itself
}
#endregion

#region
Helper Methods
private List<CheckBox> GetCheckboxes()
{
//Get all the CheckBoxes in the Form
checkBoxList = new List<CheckBox>();
foreach (UIElement element in LayoutRoot.Children)
{
if (element.GetType().ToString() == "System.Windows.Controls.CheckBox")
{
checkBoxList.Add(element as CheckBox);
}
}

return checkBoxList;
}



Then I am exposing the two methods which you can use in the container form to get and set the values in this controls.



/// <summary>
///
Set the Availability on the Form, with the Provided Timings
/// </summary>
/// <param name="selectedTimings">
Provided timings comes from the DB in the form 11,12,13....37
/// Where 11 refers to Monday Morning, 12 Tuesday Morning, etc
/// Here 1, 2, 3 is for Morning, Afternoon and Evening respectively, and for weekdays
/// 1,2,3,4,5,6,7 where 1 is for Monday, Tuesday, Wednesday, Thrusday, Friday, Saturday and Sunday respectively
/// So if we want Monday Morning, we can can denote it as 11, similarly for Saturday Evening we can write 36, etc
/// </param>
public void SetAvailibility(string selectedTimings)
{
foreach (CheckBox chk in checkBoxList)
{
chk.IsChecked = false;
}
if (!String.IsNullOrEmpty(selectedTimings))
{
string[] selectedString = selectedTimings.Split(',');
foreach (string selected in selectedString)
{
foreach (CheckBox chk in checkBoxList)
{
if (chk.Tag.ToString() == selected)
{
chk.IsChecked = true;
}
}
}
}
}

/// <summary>
///
Gets the Availibility from the selected checkboxes
/// </summary>
/// <returns>
String in the format of 11,12,13...41,42...31,32...37</returns>
public string GetAvailibility()
{
string selectedText = string.Empty;
foreach (CheckBox chk in GetCheckboxes())
{
if (chk.IsChecked == true)
{
selectedText = chk.Tag.ToString() + "," + selectedText;
}
}

return selectedText;
}


In my example I am using the matrix format for Day and Time, for example Monday=1, Tuesday=2, Wednesday=3, Thursday = 4, Friday = 5, Saturday = 6, Sunday=7. And Morning = 1, Afternoon =2, Evening = 3. So if I want to represent Morning-Monday I will have to represent it as 11, Afternoon-Tuesday as 22, Morning-Wednesday as 13, etc. And in the other way to set the values in the control I am passing the values in the control in the same format as



preferredTimeControl.SetAvailibility("11,12,13,16,23,22"); 



So this will set the checkbox value for Morning-Monday, Morning-Tuesday, Morning-Wednesday, Morning-Saturday, Afternoon of Tuesday and Afternoon of Wednesday.



To implement this control, first I have to import this control in xmlns namespace as



xmlns:controls="clr-namespace:PreferredTimeControlApp"



and finally put in your page wherever you want,



<Grid x:Name="LayoutRoot" Style="{StaticResource LayoutRootGridStyle}">

<
Border x:Name="ContentBorder" Style="{StaticResource ContentBorderStyle}">
<
controls:PreferredTimeControl x:Name="preferredTimeControl"></controls:PreferredTimeControl>
</
Border>

</
Grid>



And in the code behind you can just include this code:



private void InitializeControl()
{
preferredTimeControl.SetAvailibility("11,12,13,16,23,22");
}



And you are ready to go. For more details you can refer to my code attached.





I know there can be even simpler and better way to do this. Let me know if any other ideas.





Sorry, Guys Still I have used Silverlight 3 and VS2008, as from the system I am uploading this is still not upgraded, but still you can use the same code with Silverlight 4 and VS2010 without any changes. May be just it will ask you to upgrade your project which will take care of rest. You can also refer to a better formatted version of this post here.





Download Source Code.



 



Thanks



~Brij

Share:

Monday 10 May 2010