Saturday, July 30, 2011

WPF ItemsControl with alternating item and hover effect

Introduction

In this short article, we are going to see a few tricks about WPF ItemsControl. ItemsControl is one of the simplest yet powerful controls in WPF. ItemsControl is just like the Repeater control in ASP.NET. It supports Binding and supports custom templates to display data. For a detail study about the power of ItemsControl, please read the MSDN documentation here. In this article, we are going to focus on how to display the alternating items in an ItemsControl and apply a few effects on the items of an ItemsControl.

ItemsControlAlternatingItem

Use Alternating Item Style

ItemsControl can be used to display data both via populating the ItemsControl.Items collection or by specifying a an ItemsSource in the ItemControl.ItemsSource property. In this example, we are going to use an ItemsSource to display our data. Let's assume we have a custom class called Country and we want to display the information about Country in an ItemsControl. Shown below is a simple code listing to get the total idea.

public partial class Window1 : Window
{
public Window1()
{
loadDemoData();
this.DataContext = this;
}

public static readonly DependencyProperty DataListProperty =
DependencyProperty.Register(
"DataList", typeof(ObservableCollection), typeof(Window1));

private void loadDemoData()
{
ObservableCollection data = new ObservableCollection();
Country c1 = new Country { ID = "1", Name = "Bangladesh",
Capital = "Dhaka", Continent = "Asia" };
Country c2 = new Country { ID = "2", Name = "India",
Capital = "Delhi", Continent = "Asia" };
Country c3 = new Country { ID = "3", Name = "U.S.A",
Capital = "Washington", Continent = "North America" };
Country c4 = new Country { ID = "4", Name = "Australia",
Capital = "Canbarra", Continent = "Australia" };
Country c5 = new Country { ID = "5", Name = "Kenya",
Capital = "", Continent = "Africa" };
data.Add(c1);
data.Add(c2);
data.Add(c3);
data.Add(c4);
data.Add(c5);
this.SetValue(Window1.DataListProperty, data);
}

public class Country
{
public string ID { get; set; }
public string Name { get; set; }
public string Continent { get; set; }
public string Capital { set; get; }
}
}

In a few examples available in the online community, I have seen that ItemsControl is not directly used to display the idea of alternating items, rather a list box, or perhaps a more higher level control is shown to display alternating items. In this section, we will see how we can add styles in the items and alternating items of an ItemsControl just by using a simple DataTemplate. When we use the ItemsControl, the items of ItemsControl are generally rendered inside a ContentPresenter, which has only a few basic properties, and we can not assign the background or foreground.


Using a DataTemplate and the smart use of styles on a DataTemplate might just solve our problem. Below is a complete code listing of how to do the intended effect.

<Window x:Class="WPFDemo.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="ItemsControl" MinHeight="350"
MinWidth="550" Background="#f5f5f5">
<Window.Resources>
<Style x:Key="alternatingWithTriggers"
TargetType="{x:Type ContentPresenter}">
<Setter Property="Height" Value="25"></Setter>
</Style>
<DataTemplate x:Key="MyItemTemplate">
<Border x:Name="yahoo">
<StackPanel Orientation="Horizontal">
<Label Content="{Binding Name}"></Label>
<Label Content="is in"></Label>
<Label Content="{Binding Continent}"></Label>
</StackPanel>
</Border>
<DataTemplate.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="0">
<Setter Property="Background" Value="#e9e9e9"
TargetName="yahoo"></Setter>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="#d9d9d9"
TargetName="yahoo"></Setter>
</Trigger>
</DataTemplate.Triggers>
</DataTemplate>
</Window.Resources>
<Grid MinHeight="350" MinWidth="550">
<ItemsControl ItemsSource="{Binding DataList}"
ItemContainerStyle="{StaticResource alternatingWithTriggers}"
AlternationCount="2"
ItemTemplate="{StaticResource MyItemTemplate}"/>
</Grid>
</Window>

In the above code listing, we have not done any style changes in the item container styles; rather, we override the item template and use the item templates style in such a way that it shows the alternate items style. The main engine to do this trick is the AlternatingItemIndex property of ItemsControl. In the data template, we used a trigger to check the index of the item and then apply the style to the DataTemplates of one of the inner elements.


Hover Effect


Applying a hover effect is now easy since we know how to apply styles using a trigger. But, in this case, we won't use AlternatingItemIndex. We want to apply a mouse over effect regardless of whether it is an item or alternating item. Below is a code snippet showing the hover effect on items.

<Style x:Key="onmouseover" TargetType="{x:Type StackPanel}"> 
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Yellow">
</Setter>
</Trigger>
</Style.Triggers>
</Style>
<DataTemplate x:Key="MyItemTemplate">
<Border x:Name="yahoo">
<StackPanel Orientation="Horizontal"
Style="{StaticResource onmouseover}">
<Label Content="{Binding Name}"></Label>
<Label Content="is in"></Label>
<Label Content="{Binding Continent}"></Label>
</StackPanel>
</Border>
<DataTemplate.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="0">
<Setter Property="Background" Value="#e9e9e9"
TargetName="yahoo"></Setter>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="#d9d9d9"
TargetName="yahoo"></Setter>
</Trigger>
</DataTemplate.Triggers>
</DataTemplate>

In the above code snippet, you can see that we have applied the style on a StackPanel. The style of hover on border on the parent control of the data template will not work, since we have already added styles using a trigger in the data template. So, we define a separate style for the StackPanel and apply to it. And, that concludes our mission.


Summary


In this short article, we saw how we can display alternating items using the ItemsControl. In this demonstration, we used AlternatingItemCount as 2; we can set it to greater than two, but to get the alternating item effect, it must be larger than 1. The styles must be modified to support AlternatingItemCount. For more details on ItemsControl, please visit the links in the References section below.


References



Friday, July 29, 2011

Tooltip service and tooltip facility of WPF

Introduction

Tooltip is a very important part of any modern software. It helps and suggests what to do with any user interaction item control or what a particular content or legends means. In this article, I am going to discuss about a small yet interesting feature of WPF, the “ToolTipService”. Using tooltip service, we can do a good amount of customization on how we can display tooltip.

Let us put down a small example how we can define a tooltip of any content in XAML markup.

<Button Width="100" Height="30" Content="Click Me!"
ToolTip="Click here to do some thing"></Button>

WPF has two default events to help developers do some level of customization, the events are ToolTipOpening and ToolTipClosing.


Customizing the Tooltip


In almost all the technology that exists except WPF, tooltip is not that customizable. But in WPF, almost all the gates are opened. We can customize tooltip in such a way that we can put any content in a tooltip, event a data grid! Just kidding, no scenario can be that bizarre. But no kidding, we can put almost anything in a tooltip content. Enough talk, let's put an example and see actually how pretty handy it is.

<Button Width="100" Height="30" Content="Click Me!">
<Button.ToolTip>
<Border Margin="-4,0,-4,-3" Padding="10" Background="Silver">
<Border.BitmapEffect>
<OuterGlowBitmapEffect></OuterGlowBitmapEffect>
</Border.BitmapEffect>
<Label>This is a simple customization of tooltip</Label>
</Border>
</Button.ToolTip>
</Button>

In the above example, we have added a border as a content of the tooltip and also applied few changes on the look and feel of the border. And the effect after running the application looks like the following image:


tooltip1


Using the Tooltip Service


So we now know that tooltip is a very good level of customizable in WPF. Now let's explore a service that is evolved around tooltip - the “ToolTipService”. Normally a tooltip is displayed exactly where the mouse pointer is. If we want to display the tooltip always at a particular position, we can just modify the markup a little using ToolTipService and set the ToolTipService.Placement property to our desired location. The code below is given to show a tooltip always at the bottom of a button element:

<Button Width="100" Height="30" Content="Click Me!" 
ToolTipService.Placement="Bottom">
<Button.ToolTip>
<Border Margin="-4,0,-4,-3" Padding="10" Background="Silver">
<Border.BitmapEffect>
<OuterGlowBitmapEffect></OuterGlowBitmapEffect>
</Border.BitmapEffect>
<Label>This is a simple customization of tooltip</Label>
</Border>
</Button.ToolTip>
</Button>

And the result looks like the following image:


image


Let's see another very interesting feature about the tooltipservice. If we have a disable element, the tooltip does not get shown when we move over on the element. But using ToolTipService.ShowOnDisabled property, we can display tooltip even on a disabled item. Below, the code is given:

<Button Width="100" Height="30" Content="Click Me!" 
IsEnabled="False"
ToolTipService.ShowOnDisabled="True"
ToolTipService.Placement="Bottom">
<Button.ToolTip>
<Border Margin="-4,0,-4,-3" Padding="10" Background="Silver">
<Border.BitmapEffect>
<OuterGlowBitmapEffect></OuterGlowBitmapEffect>
</Border.BitmapEffect>
<Label>This is a simple customization of tooltip</Label>
</Border>
</Button.ToolTip>
</Button>

And the effect of the above code looks like this:


image


Let's put a little more interesting code here.

<Button Width="100" Height="30" Content="Click Me!" 
ToolTipService.HasDropShadow="False"
ToolTipService.InitialShowDelay="100"
ToolTipService.ShowDuration="5000"
ToolTipService.ShowOnDisabled="True"
ToolTipService.Placement="Bottom">
<Button.ToolTip>
<Border Margin="-4,0,-4,-3" Padding="10" Background="Silver">
<Border.BitmapEffect>
<OuterGlowBitmapEffect></OuterGlowBitmapEffect>
</Border.BitmapEffect>
<Label>This is a simple customization of tooltip</Label>
</Border>
</Button.ToolTip>
</Button>

In the above code, we have set the ToolTipService.InitialShowDelay to 100 ms which allows the tooltip to show almost just after we mouse over the button. Now we have made the tooltip stay open a little longer using ToolTipService.ShowDuration to 5000 ms. We can customize more using the other properties of ToolTipService.


Summary


In this sort of article, we have seen a few interesting tricks about tooltip using ToolTipService. For more information about how to customize the tooltip, please visit the references. Best of luck and happy programming.


References



  1. http://msdn.microsoft.com/en-us/library/system.windows.controls.tooltipservice.aspx [About ToolTipService Class]
  2. http://msdn.microsoft.com/en-us/library/ms752368.aspx [How to Position a ToolTip]
  3. http://msdn.microsoft.com/en-us/library/system.windows.controls.tooltipservice_fields.aspx [Fields of ToolTip service]

Web browser control does not display data in WPF window if window's allow transparency is true

Windows from have web browser control since .net 2.0, WPF also introduced a browser control from .net 3.5 sp1, well the controls are very good as far as functionality is concern, i my self prefer windows forms browser since it have more control with the functionality.

Today i encountered with a strange problem, in one of my application i used a modal dialog to present data as light box effect, inside the modal i added a browser control and then populated appropriate data, when i run the application the modal showed up, but the browser was just blank, no data what so ever. Later after few trial and error i found that my modal windows allow transparency property is set to true,  when i turned it to false, browser's content showed up.

Its a small problem perhaps many of you already knew about it, but since it killed almost two hour of my time, i thought its worth sharing. Happy coding..

Wednesday, July 27, 2011

Using SQLite with Entity Framework in Visual Studio 2010

Introduction

In my previews blog post we have seen how using a simple “data provider” provided by http://sqlite.phxsoftware.com/ can make our life easier in context of SQLite in .net. In this short article we are going to see how we can use SQLite to generate Entity Framework Data model.

Choosing the Provider

First thing first create any type of project in Visual studio 2010. But I would prefer an web application or windows forms or perhaps a WPF application. Now click on project and select add new item to add a new item type. From Add new item wizard select “Ado.net Entity Data Model” and click on add this will brought up the Entity data model wizard.

  • Step 1: Select Generate from Database
  • Step 2: In next window select New connection
  • Step 3: Connection properties window will popup and the select right kind of provider for SQLite.
  • Step 4: After that the Connection properties will have browser or New db,

Create Data Model

  • Step 5: Now select existing db if you have using browser or New to create new db.
  • Step 6: Continue with the wizard to select database table items to include in model.
  • Step 7: Click finish to close the wizard and a data model will be generated for you.

Data Model Created

If you had any relationship in the database those will be automatically be synchronized in data model, that’s it we are good to jump in the code to retrieve data and do all type of necessary stuff that we must do in a database. Best of luck and happy coding.

Edit SQLite database using Visual Studio 2010 or SQLite Administrator

Introduction

In my previous blog I have shared few useful information about SQLite Embedded database and how to use its provider to create an connection using System.Data.SQLite. We have also seen a simple tool named “SQLite Administrator” which is very handy to use with SQLite database. In this short article we will see that how we can create and manipulate  data using Visual Studio 2010 or SQLite Administrator.

Creating Table in Visual Studio 2010

Select the SQLite connection that you created and expend the Tables node, then right click and select “Add New Table” that’s it you are good to go to add a table just like the bellow figure. I am sure you guys have done this hundreds of time in SQL server, this time its just SQLite. you might see a warning when you first enter into edit of table editor.

Creating Table In VS2010

Using SQLite Administrator

Double click on the SQLite database file and right click on tables and click "Create Table”, rest of the UI is fanatic to Create the table. Set field as primary key or assign auto increment to primary key all can be done via simple clicks. So no custom hand written SQL any more.

Edit Table in SQLite Administrator

Creating Relations in Visual Studio 2010

Creating table relations are easy in visual studio, just click on relation icon, the icon beside primary key, in fact to be precise right side icon of primary key button. Or perhaps you can select a table and then click on relations, this will popup an widget to create relation.

AddRelation

Creating auto increment primary key is a not that much difficult also, now a days in every table we use auto increment key so we must discuss about it. at first glance we didn’t find any button or option to assign it directly. You can use SQLite Administrator to add it in few clicks, but to add in Visual Studio 2010 you got to bring the indexes window, just click on Indexes after that you will find option to add auto increment column.

Edit Auto Increment in Vs2010

I hope this information's will be helpful to us to work better with SQLite. Hope to write more information's about SQLite in near future. Happy coding.

Tuesday, July 26, 2011

SQLite management tool.

SQLite have lots of management tools, some of them are open source and some of them are trial ware and some of them are commercial. I found “SQLite Administrator” Pretty easy to use and handy tool as far as SQLite database file is concern.

A complete list of SQLite management tools can be found here “http://sqlite.com/cvstrac/wiki?p=ManagementTools” download the use what ever best suits you.

Today I am going to talk about only in SQLite Administrator, It can be downloaded from the following site.

http://sqliteadmin.orbmu2k.de/

A Complete list of feature is given In that site.

image

Features:

  • Create / Modify / Delete Tables by Wizard
  • Create / Modify / Delete Indices by Wizard
  • Create / Modify / Delete Views by Wizard
  • Create / Modify / Delete Triggers by Wizard
  • SQL Code Completion that supports table aliases
  • SQL Code Highlighting
  • SQL Error Locating
  • Import Data from CSV Files
  • Export Data ( XLS / CSV / HTML / XML )
  • Store User Queries into Database
  • Search for User Queries
  • Store Images into Blob Fields ( JPG / BMP )
  • Show SQL of each Database Item
  • Migrate SQLite2 Databases to SQLite3
  • Try to keep Indices and Triggers after modifying a Table

 

Note

This tool need no installations what so ever. The whole package is in a zip file and need zero installation, just unzip and open the exe that’s it, and All of the functionality is pretty easy and it has very intuitive UI. I would recommend it to every one who work with SQLite.

Using SQLite in Visual Studio 2010

Introduction

Every now and then we need a simple database solution which is light, small and pretty easy to use. What more can be useful other than SQLite, A simple yet very powerful tool to support database for any kind of application needs. When we started this research work we had a particular focus to choose right kind of database depending on few criteria.

  • We don’t want to use a service based database rather a file system based database.
  • Client have to be light, fast and support blob data.
  • We don’t want to install any client or framework in client machine

 

Background

After few minutes of research in the internet we came up with few embedded file system database that can be used in .net and has support, necessary tool and provider.

  1. SQLite
  2. SQL Compact Database
  3. Firebird

Among those SQL Compact DB is really have good support with visual studio IDE and very easy to use but it has its own limitations and we would definitely discuss in future about it. But the end result was that we found that SQLite is winner in every case and that’s why we choose to recommend it in this short article.

Adding the provider

Change Data Source

Next step is to add a data connection in server explorer in Visual studio 2010. When you click on add connection by default you don’t have provider added in visual studio, so we have to add it using a third-party tool. You can download the provider for SQLite from http://sqlite.phxsoftware.com/ site. “SQLite-1.0.66.0-setup” this is the version we used for this particular case. When you install this provider you would be given an option to integrate this in vs2008 and vs2010.

Installing the provider

After installing the provider when you get back to the add data connection in server explorer you would see an new provider is available for SQLite.

Adding the connection is Server Explorer

SQLite Provider

Go ahead and click on after choosing SQLite Database File. Next we will be presented with a screen where you would either choose an existing database or created a new database file.

Create New SQLLite DB

That’s it your connection string and database connection is set up and you are good to go with design of the database. Few interesting note on this particular case. My SQL database have no database diagram support yet. But we hope that this will be provided soon. After adding connection we can created tables and add necessary relations to the table.

Conclusion

In this short article we have seen that how easily SQLite can be used in visual studio 2010 using a provider to create connection in server explorer. Next we would discuss how to use SQL Lite to create a data layer using Entity Framework.

Update

New article with new provider by SQLite org is published here http://munnaondotnet.blogspot.com/2012/06/using-sqlite-in-visual-studio-2010-with.html