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:
-
Property Triggers: Used to check on WPF Dependency properties like IsButtonPressed, IsMouseOver etc.
-
Data Triggers: Based on value of data binding property.
-
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.