Click here to Skip to main content
12,691,789 members (30,460 online)
Click here to Skip to main content
Add your own
alternative version

Stats

46K views
263 downloads
10 bookmarked
Posted

WPF ("Avalon") Demo 2 - A Personal Clone of well-known MediaMania - Described

, 25 Jun 2006
Rate this:
Please Sign up or sign in to vote.
This demo application, combines both XAML declaration and C# Code to search for items on Amazon and populate the result into a WPF ListBox

Sample Image - mediamaniac.jpg

Introduction

If you've seen Mark Boulter and Mark Harsh's talk about Cider the designer for WinFX applications in visual studio and its corresponding demo video, you've found a very simple but useful application called MediaMania Online Catalogue.

I've searched for the demo project to investigate through the facilities the designer has, but no luck. Hopefully I had some motivation to build up the whole thing by myself according to the demonstration video combined with my own experience.

This project has been explained briefly here. Also there's a sample just like this one on gotdotnot. Many thanks to that, we both have similar thoughts about the demo but used different search policies. Mine is simpler I think.

Requirements

To run the application you need: WinFX Runtime Components February 2006 CTP.

To compile the source code containing your modification, you need additionally Visual Studio Orcas which brings you the "Cider" designer, Expression Interactive Desinger March 2006 CTP for style editing and gradient brushes and also A Valid Access Key from Amazon to Launch the WebService Requests.

Additional Things...

If you digg into the demonstration video and compare the resulting application with mine, you'll see that I've put a "Cancel" button on screen to Cancel the search.

I've used the new .NET 2.0 background wroker component to implement worker thread model and make the UI responsive.

Other things are exactly try to clone job over the main idea of the demo video.

The XAML - Described

According the two types of WinFX Applications (Windows and Browser Application) WinFX Projects basically contain WinFX Windows or WinFX Pages.

My last demo was a WinFX Browser Application which consisted a single Page (Scene1.xaml) despite this one which is a WinFX Winodws Application.

WinFX Windows Applications run on target machines which trust and full control over the local and internet resources. As you decided to install them you gave them the permission.

However WinFX Browser Applications are not fully trusted, cause they are distributed and accessed over the network. Just like Web Applications, WinFX Browser Applications cannot do anything Desktop Applications. And the differrence with Web Applications is that the UI is WPF ("Avalon") Host Managed one, means you can use greate Avalon Components on your application despite poor html applications which even AJAX won't help you do such thing.

By the way, although the two type are different in deployment and execution, but they are developed all the same way in .xaml files.

The Main Window

As all .xaml files are using XML markup, they are referrencing appropriate schemas:

<Window x:Class="MediaMania.WindowMain"
    xmlns="<A href="http://schemas.microsoft.com/winfx/2006/xaml/presentation">http://schemas.microsoft.com/winfx/2006/xaml/presentation</A>"
    xmlns:x="<A href="http://schemas.microsoft.com/winfx/2006/xaml">http://schemas.microsoft.com/winfx/2006/xaml</A>"
    Title="MediaMania" Height="456" Width="596"
    >

Window Resources

Any control styles and templates and data bindings which will be used by the window and its controls are defined in <Window.Resources> section.

Styles are a set of propperty setter markups which decorate a control or manages its behavior. And by using control templates you can build up a pre-defined control from scratch based on its core functionality. I've done this in a detailed change for button control in the last demo.

Here is the style and control template for <ListBoxItem>:

<BR>  <Window.Resources>
    <Style x:Key="{x:Type ListBoxItem}" TargetType="{x:Type ListBoxItem}">
      <Setter Property="OverridesDefaultStyle" Value="true" />
      <Setter Property="Background" Value="Transparent" />
      <Setter Property="BorderBrush" Value="Transparent" />
      <Setter Property="BorderThickness" Value="1" />
      <Setter Property="HorizontalContentAlignment" Value="Left" />
      <Setter Property="VerticalContentAlignment" Value="Center" />
      <Setter Property="Padding" Value="3" />
      <Setter Property="Template">
        <Setter.Value>
          <ControlTemplate TargetType="{x:Type ListBoxItem}">
            <Border 
              Background="{TemplateBinding Background}" 
              BorderBrush="{TemplateBinding BorderBrush}" 
              BorderThickness="{TemplateBinding BorderThickness}" 
              Padding="{TemplateBinding Padding}">
              <ContentPresenter x:Name="ContentSite" 
                HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
                VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
            </Border>
            <ControlTemplate.Triggers>
              <Trigger Property="IsSelected" Value="true">
                <Setter Property="Background">
                  <Setter.Value>
                    <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
                      <LinearGradientBrush.GradientStops>
                        <GradientStop Offset="0" Color="#F9F9F9"/>
                        <GradientStop Offset="1" Color="#E9E9E9"/>
                      </LinearGradientBrush.GradientStops>
                    </LinearGradientBrush>
                  </Setter.Value>
                </Setter>
                <Setter Property="BorderBrush" Value="Silver" />
              </Trigger>
              <MultiTrigger>
                <MultiTrigger.Conditions>
                  <Condition Property="IsSelected" Value="true" />
                  <Condition Property="Selector.IsSelectionActive" 
                             Value="false" />
                </MultiTrigger.Conditions>
                <Setter Property="Background" Value="#F8F8F8" />
                <Setter Property="BorderBrush" Value="#E0E0E0" />
              </MultiTrigger>
            </ControlTemplate.Triggers>
          </ControlTemplate>
        </Setter.Value>
      </Setter>
      <Style.Triggers>
        <Trigger Property="IsEnabled" Value="false">
          <Setter Property="Foreground" Value="Gray" />
        </Trigger>
      </Style.Triggers>
    </Style>
  </Window.Resources>

The style element is defined for a TargetType of ListBoxItem and is has also a x:Key which defines the style to be referrenced by its key for a particular compatible element.

The control template has defines some <Trigger> and <MultiTrigger> sections. The role of these two element is to define actions or style changes while a specific property-value match occures. The latter support multiple conditions, which is an AND between the conditions.

As shown above, while a ListBoxItem is selected it has some decoration on background, and also when its not the active control of the window but its selected, it has some other decoration.

Main Window's Visual Tree

The term Visual Tree is reffered to rendering system of WPF. Each element in Avalon has its own visual tree. This sample's window has tree <DockPanel>s, each of them has their own visual tree as well, like <RadioButton>s, <Label>s and <TextBox>s.

Here is the XMAL code:

<BR>  <DockPanel MinHeight="50" MinWidth="50" LastChildFill="True" Name="dockPanelMain" >
    <DockPanel MinHeight="50" MinWidth="50" LastChildFill="False" Name="dockPanelTop" <BR>	DockPanel.Dock="Top" Height="65">

This creates my MainWindow as you can see in the screenshot.

The Code

Now we need to write some code to handle the operation. We want to handle button clicks for Search and Cancel buttons and change the search mode when a specific radio button is selected.

If you open the demo project In the Visual Studio Orcas or Expression Interactive Designer, you see that the MainWindow.xaml has an associated MainWindow.xaml.cs C# code file.

Here is where the window class we declared in the xaml appears:

<BR><Window x:Class="MediaMania.WindowMain".../>

Using Namespaces

<BR>using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.Imaging; // used for the Image control on ListBoxItem
using System.Windows.Shapes;
using Amazon = MediaMania.Amazon;   // Amazon's web service referrence
                                    //(the proxy is auto-generated)

WindowMain Class

<BR>namespace MediaMania
{
    /// <summary>
    /// Interaction logic for WindowMain.xaml
    /// </summary>
    
	public partial class WindowMain : Window
	{
	...
    	}
}

Just like windows forms we write our codes inside the partial class definition. except we use Window as parent class.

RadioButton Handler

In the XAML file we've set <RadioButton ... Checked="ChangeSearchMode" ... />, which leads the WPF host to execute the method we should declare in our class.

<BR>        private string searchMode = "books";

	...

        
	void ChangeSearchMode(object sender, EventArgs e)        
	{            
		RadioButton checkedRadioButton = (RadioButton)sender;            
		searchMode = checkedRadioButton.Content.ToString().ToLower();        
	}

Seach and Cancel Buttons

When we click the Search button, an instance of Amazon Search Service initializes and we make an Async call to the webservice then catch the results when it's completed in the corresponding handler.

<BR>        protected const string AMAZON_ID = "Put Your Amazon Acess Key here";

        ...
	void buttonSearch_Clicked(object sender, EventArgs e)        
	{            
		this.labelStatus.Content = "Initializing search...";
            
		Amazon.KeywordRequest keywordRequest = new Amazon.KeywordRequest();       
		keywordRequest.locale = "us";            
		keywordRequest.sort = "reviewrank";
            
		keywordRequest.mode = searchMode;            
		keywordRequest.keyword = this.textBoxSearchPhrase.Text;            
		keywordRequest.tag = AMAZON_ID;            
		keywordRequest.devtag = AMAZON_ID;            
		keywordRequest.type = "heavy";            
		keywordRequest.page = "1";<P>            
		try           
		{                
			if(Ass == null)                    
				Ass = new Amazon.AmazonSearchService();
                
			Ass.KeywordSearchRequestCompleted += 
			  new MediaMania.Amazon.KeywordSearchRequestCompletedEventHandler(<BR>				Ass_KeywordSearchRequestCompleted);
                
			this.labelStatus.Content = "Searching...";
                
			Ass.KeywordSearchRequestAsync(keywordRequest);
                
			buttonCancel.IsEnabled = true;            
		}
            
		catch       
		{            
		}
	}</P>

 

Feedback

Please send your feedbacks. I'm really serious.

Acknowledgement

Many Thanks to Marc! He motivated me to complete the article, with the very correct words by his message. ;)

History

     4 May 2006 - Original Article

     5 May 2006 - Now it's an Article with detail description

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

A.Gharighi
Web Developer
Iran (Islamic Republic of) Iran (Islamic Republic of)
I'm lazy to retype it, check my blog plz.

An Intelligent Sense Of A Computer
http://aisac.wordpress.com

You may also be interested in...

Comments and Discussions

 
Questioncan we list controls present on WPF form [modified] Pin
sam_g129-May-06 19:43
membersam_g129-May-06 19:43 
AnswerRe: can we list controls present on WPF form [modified] Pin
A.Gharighi30-May-06 19:25
memberA.Gharighi30-May-06 19:25 
QuestionRe: can we list controls present on WPF form [modified] Pin
sam_g131-May-06 0:05
membersam_g131-May-06 0:05 
AnswerRe: can we list controls present on WPF form Pin
A.Gharighi10-Jun-06 1:03
memberA.Gharighi10-Jun-06 1:03 
Generalinteresting example, thanks Pin
BillWoodruff5-May-06 0:31
memberBillWoodruff5-May-06 0:31 
GeneralRe: interesting example, thanks Pin
Marc Clifton5-May-06 1:51
protectorMarc Clifton5-May-06 1:51 
GeneralRe: interesting example, thanks Pin
BillWoodruff5-May-06 4:07
memberBillWoodruff5-May-06 4:07 
GeneralIt would be really nice... Pin
Marc Clifton4-May-06 13:16
protectorMarc Clifton4-May-06 13:16 
GeneralRe: It would be really nice... Pin
Vertyg04-May-06 23:22
memberVertyg04-May-06 23:22 
GeneralRe: It would be really nice... Pin
Marc Clifton5-May-06 1:47
protectorMarc Clifton5-May-06 1:47 
GeneralRe: It would be really nice... Pin
Vertyg05-May-06 12:07
memberVertyg05-May-06 12:07 
GeneralRe: It would be really nice... Pin
A.Gharighi6-May-06 2:41
memberA.Gharighi6-May-06 2:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170117.1 | Last Updated 26 Jun 2006
Article Copyright 2006 by A.Gharighi
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid