Blue Theme Orange Theme Green Theme Red Theme
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » WPF » WPF Practical Solutions

WPF Practical Solutions

This document describes step by step solution to some of general problems developer face in wpf application.

Page Views : 9794
Downloads : 0
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


Implementing Inheritance (Base-Class/Derived-Class) model in WPF

Description: Normally in multi-winform application we create a common base class which exhibits common behavior of all screens shown to user. So every screen (technically a win form or webpage) which is derived from base form will show similar common behavior.

Implementing base-derived model in WPF is a bit complex because both Xaml (User Interface) and code behind (.cs) class should know which base class to derive from.

Let's implement this model in WPF using one practical problem which we face when we are hosting wpf window from winform.

Example: Let assume we are hosting a wpf dialog from winform and we want that wpf dialog is shown to user as a modal dialog and always associated with parent window. We want this behavior for all wpf dialog used in our application.

Implementation Approach:

Step 1: Create a base class which exposes one public method ShowModalDialog() which associates WPF window to parent window. Any class deriving from this base class will call this exposed method instead of normal ShowDialog () method to show modal dialog.

public class DialogBase: Window

{

[DllImport("user32.dll")]

iternal static extern IntPtr GetActiveWindow ();  // Returns active window reference.

 

        public bool? ShowModalDialog()

{

WindowInteropHelper helper = new WindowInteropHelper(this);

helper.Owner = GetActiveWindow();    // Set main active window.

return this.ShowDialog();

}

}

Step 2: Now any new WPF window needs to derive from above base class.

public class SampleDialog : DialogBase

{

public SampleDialog( )

     {

 

 }

}

Step 3: As any WPF dialog also has a xaml associated with it. So we need to have reference of base class in xaml also so that it can associate itself with base class.

<my:DialogBase                               

       xmlns:my="clr-namespace:MyNameSpace" // Include namespace of base class.

      Title="Sample WPF Dialog"

      //// Implementation of xaml binding and other stuff as such.

</my:DialogBase>

Step 4: Now we have the basic framework available and we are ready to use it while showing WPF dialog. Instead of calling showDialog() method we will call base class's ShowModalDialog() method.

Main()

{

SampleDialog wpfDialog = new SampleDialog ();

        wpfDialog.ShowModalDialog();

}

Using same context menu items at multiple places

Description: Context menu in xaml is represented by <MenuItem> tag in xaml. Below example shows how to create context menu with submenus

E.g.


<
MenuItem  Header="Main Menu 1" >
         
<MenuItem  Header="Sub Menu 1"/>
         
<MenuItem  Header="Sub Menu 2"/>
</MenuItem>

Example:

Now suppose I want to create context menu hierarchy as shown in below image. Note that Main menu has child submenu items.

User wants to use same child context menu items for every main menu (i.e. Main Menu 1, Main Menu 2 and Main Menu 3).

One simple approach would be to add same child menus items 3 times one for each main menu. But this approach has disadvantages because we have to declare them multiple times for each main menu and situation can get worse if no of main menus increases.

Implementation Approach:

To use same child context menu across various parent menu items we can use <ArrayList> construct available in xaml.

<xmlns:c="clr-namespace:System.Collections;assembly=mscorlib">

<c:ArrayList  x:Key="ChildSubMenu"  x:Shared="False">

          <MenuItem  Header="Child Menu - A" ></MenuItem>

          <MenuItem  Header="Child Menu - A" ></MenuItem>

          <MenuItem  Header="Child Menu - A" ></MenuItem>

</c:ArrayList>

Now we can use above child context menu (x:Key=”Child Sub Menu”) for every main menu as below:

<MenuItem

Header="Main Menu 1"

ItemsSource="{StaticResource ChildSubMenu}">

</MenuItem>

<MenuItem

Header="Main Menu 2"

ItemsSource="{StaticResource ChildSubMenu}">

</MenuItem>

<MenuItem

Header="Main Menu 3"

ItemsSource="{StaticResource ChildSubMenu}">

     </MenuItem>

How to execute a command in WPF when user presses F5 (Application Refresh)

Example:

Suppose we are creating a user control and we want some custom action to be performed whenever user calls application refresh (F5).

We can achieve this in xaml by using NavigationCommands (Namespace: System.Window.Input) class which provides a standard set of navigation commands (e.g. NextPage, PreviousPage, Refresh, Search etc.)

Implementation Approach:

So we can call any custom code to execute on application refresh using NavigationCommands.Refresh as

<UserControl.CommandBindings>

<CommandBinding Command='NavigationCommands.Refresh'

                   Executed="ApplicationRefresh_Executed">

</CommandBinding>

</UserControl.CommandBindings>

Now in code behind class of UserControl we can define method as

private void ApplicationRefresh_Executed(object sender, ExecutedRoutedEventArgs e)

{

             // Implementation goes here.

}

How to use converters in Xaml

Description: WPF's binding and MultiBinding types define a Converter property that allows you to provide a converter that will be used during the binding process at runtime. If you don't explicitly specify a value converter, WPF will use its built-in primitive ones behind the scenes. If you do specify a value converter, WPF will invoke methods on your converter during the data binding process. These methods are:

  • Convert (). Called to convert a value when propagating it from the binding source to the binding target.
  • ConvertBack(). Called to convert a value when propagating it from the binding target to the binding source.

Example: Suppose I want to add some custom formatting in string displayed in text box control in WPF window.

E.g. I have following class

Private  Person
            {
           
    String FirstName,
               
String MiddleName,
               
String LastName
            }


Now I have declared a text box control in xaml

<TextBlock DataContext="{Binding Path=Person}"Text="{Binding Path=Firstname}"/>

Above textbox is binded to Person object and will show "FirstName" of person in text box.

Now suppose if we want to change the format of string getting displayed then we need to implement create a converter class which will define how to convert value at runtime:

Public class NameConverter: IValueConverter
{
   
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {

        String firstName
= value as string;
        Return "First Name : " + name; // Display in format :First Name : XXX 
     }

     public
object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
     {

        throw
new NotImplementedException();
     }

}


As you can see from above converter we have returned string in desired format which now will be displayed in text box.

But don't forget to mention this converter class in xaml as below

<window
xmlns
:c="clr-namespace:NameSpaceWhereConvereterClassExists"
    <
Window.Resources>
        <
ResourceDictionary>
            <
c:NameConverter x:Key="stringToName"/>
        <ResourceDictionary>
    <
Window.Resources>

 ///// other implementation 
//// other implementation 

<TextBlock DataContext="{Binding Path=Person}" Text="{Binding Path=Firstname, Converter={StaticResource stringToName}}"/>
. . . . . . .
.. . . . . . .

</Window>

That's it. Now suppose person first name is "James" the text box will show "First Name: James" in UI.

Tip: If converter is located in <Window.Resources> section or in user control then Converter class instance is created for each item in list. Suppose we are displaying 100 person objects in tree view then 100 instance of Converter class will be created.

So we should put it in App.xaml file and in this way only one instance will be created.

Implement If-Else model in WPF using Triggers/Setters.

Description: When applying a style to a control, all properties defined in setter elements are unconditionally applied to the control. If that is not the desired behavior, we can use triggers.

The trigger includes a condition, and when that condition is true, the Setters defined in the trigger will be applied. When the condition is false, the Setters are ignored.

There are three kinds of triggers:

  1. Property Triggers: Used to check on WPF Dependency properties like IsButtonPressed, IsMouseOver etc.

  2. Data Triggers: Based on value of data binding property.

  3. Event Triggers: Based on event happened.

Example: Let's understand triggers by using on example of DataTriggers.

Suppose I gave following Data Binding Object:

Private  Person
{
   
String Name,
    Int
 Age,
}

Now suppose we have to show list of person in list view control and if person age in 0 (new born) then we have to show that person in green text in control.

So if have to define a Style with trigger on "Age" property of person as below:

<Style x:Key="ListBoxStyle" TargetType="{x:Type ListBox}">

<Style.Triggers>

<DataTrigger Binding="{Binding Path=Age}">

<DataTrigger.Value>0</DataTrigger.Value>

<Setter Property="TextBox.ForeColor" Value="Green"/>

      </DataTrigger>

</Style.Triggers>

Include Style created above in listView control declaration xaml as below:

<ListView

x:Name="PersonListView"

ItemsSource="{Binding Path=Person}"

Style="{StaticResource ListBoxStyle }>

That's it. Now if person age is 0 then that person will be shown in green text in list view.

 

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Amit Tiwari
Hi, I have around 4 years of experience in Microsoft technologies (C# 2.0, Wbservices, SQL Server, TFS, VSTS, WPF etc). Currently i am working as software engineer in a leading software firm of India. At spare time i love to watch movies, cricket.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments
Implementing Inheritance by vkyadlapalli On September 9, 2009
Hi Amit Tiwari,

I have implemented the WPF windows inheritance as you mentioned, but I am not able to see the Window in designer format and getting the exception as "Exception has been thrown by the target of an invocation". Here is my code, please help me to solve the problem.


<
my:SsfWindow
x:Class="TEST_WPF.HelloWorldUIPrj.Window1_Form"
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:my="clr-namespace:WPFwindows;assembly=WrapperDLL"
Height="155"
Width="345"
>
//// Implementation of xaml binding and other stuff as such.
</my:SsfWindow>

Reply | Email | Modify 
Re: Implementing Inheritance by Amit On December 22, 2009

Hi,

Can you send me your demo code, so that i can look into problem.

Reply | Email | Modify 
6 Months Free & No Setup Fees ASP.NET Hosting!
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.