Click here to Skip to main content
11,412,833 members (72,817 online)
Click here to Skip to main content

How to : Creating a WPF User Control & using it in a WPF application ( C# )

, 24 Jan 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
How to : Creating a WPF User Control & using it in a WPF application ( C# )
This is an old version of the currently published article.
preview

Introduction

This article shows you how we can create an User Control in WPF and how we can use it in our WPF applications.
In this article I'll show you how we can create a custom ToolTip in WPF with VS2008 SP1 & C#.

Background 

There are the same articles like this article, for example see this article that written by Sacha Barber.

Using the Code 

There we go.
First we should create an User Control.
Thus we have to select WPF User Control Library Project.

Custom User Control in WPF

Now we can create or edit the XAML code for creating a custom user control.
I've used this XAML code for a custom tooltip. it's up to you what you want.
<UserControl 
    Name="UserControlToolTip"
    x:Class="CustomToolTip.UserControl1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d" RenderTransformOrigin="0,0" HorizontalAlignment="Left" VerticalAlignment="Top" >
    
    <UserControl.RenderTransform>
        <TransformGroup>
            <ScaleTransform ScaleX="1" ScaleY="1"/>
            <SkewTransform AngleX="0" AngleY="0"/>
            <RotateTransform Angle="0"/>
            <TranslateTransform x:Name="UserControlToolTipXY" X="0" Y="0"/>
        </TransformGroup>
    </UserControl.RenderTransform>
    
    <Grid HorizontalAlignment="Center" VerticalAlignment="Center" MinWidth="200" MinHeight="120">
    	<Grid.RowDefinitions>
    		<RowDefinition Height="0.333*"/>
    		<RowDefinition Height="0.667*"/>
    	</Grid.RowDefinitions>
        <Rectangle Fill="#FFFBFBFB" Stroke="#FF000000" RadiusX="10" RadiusY="10"
        	 RenderTransformOrigin="0.139,0.012" StrokeThickness="1" Grid.RowSpan="2">
            <Rectangle.BitmapEffect>
                <DropShadowBitmapEffect Opacity="0.8"/>
            </Rectangle.BitmapEffect>
        </Rectangle>
        <Rectangle RadiusX="10" RadiusY="10" RenderTransformOrigin="0.139,0.012" 
        	StrokeThickness="10" Stroke="{x:Null}" Margin="1,1,1,1" Grid.Row="0" Grid.RowSpan="2">
        	<Rectangle.Fill>
        		<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0.725">
        			<GradientStop Color="#00E6D9AA" Offset="0.487"/>
        			<GradientStop Color="#FFE6D9AA" Offset="0.996"/>
        		</LinearGradientBrush>
        	</Rectangle.Fill>
        </Rectangle>
        <Rectangle RadiusX="10" RadiusY="10" RenderTransformOrigin="0.493,0.485" 
        	StrokeThickness="10" Stroke="{x:Null}" Grid.RowSpan="2" Margin="1,1,1,1">
        	<Rectangle.Fill>
        		<LinearGradientBrush EndPoint="0.014,0.5" StartPoint="0.211,0.5">
        			<GradientStop Color="#00E6D9AA" Offset="0.513"/>
        			<GradientStop Color="#FFE6D9AA" Offset="0.996"/>
        		</LinearGradientBrush>
        	</Rectangle.Fill>
        </Rectangle>
        <Rectangle RadiusX="10" RadiusY="10" RenderTransformOrigin="0.493,0.485" 
        	StrokeThickness="10" Stroke="{x:Null}" Grid.RowSpan="2" Margin="1,1,1,1">
        	<Rectangle.Fill>
        		<LinearGradientBrush EndPoint="0.493,0.002" StartPoint="0.493,0.33">
        			<GradientStop Color="#00E6D9AA" Offset="0.513"/>
        			<GradientStop Color="#FFE6D9AA" Offset="0.996"/>
        		</LinearGradientBrush>
        	</Rectangle.Fill>
        </Rectangle>
        <Rectangle RadiusX="10" RadiusY="10" RenderTransformOrigin="0.493,0.485" 
        	StrokeThickness="10" Stroke="{x:Null}" Grid.RowSpan="2" Margin="1,1,1,1">
        	<Rectangle.Fill>
        		<LinearGradientBrush EndPoint="0.99,0.441" StartPoint="0.794,0.441">
        			<GradientStop Color="#00E6D9AA" Offset="0.513"/>
        			<GradientStop Color="#FFE6D9AA" Offset="0.996"/>
        		</LinearGradientBrush>
        	</Rectangle.Fill>
        </Rectangle>
        <TextBlock Text="TextBlock" TextWrapping="Wrap" x:Name="TextBlockToolTip" 
        	RenderTransformOrigin="0.5,0.5" Grid.Row="1" HorizontalAlignment="Left" 
            	VerticalAlignment="Center" Margin="20,0,0,20" />
        <TextBlock Name="ToolTipTitle" HorizontalAlignment="Stretch" Margin="15,16,15,6.1" 
        	FontSize="14" Text="title" d:LayoutOverrides="Height" />
    </Grid>
</UserControl>
Also, I've added these methods and properties for controlling the elements :
namespace CustomToolTip
{
    public partial class UserControl1 : UserControl
    {
        public UserControl1()
        {
            InitializeComponent();
        }

        public double UserControlToolTipX
        {
            get { return this.UserControlToolTipXY.X; }
            set { this.UserControlToolTipXY.X = value; }
        }

        public double UserControlToolTipY
        {
            get { return this.UserControlToolTipXY.Y; }
            set { this.UserControlToolTipXY.Y = value; }
        }

        public string UserControlTextBlockToolTip
        {
            get { return TextBlockToolTip.Text; }
            set { TextBlockToolTip.Text = value; }
        }

        public string UserControlToolTipTitle
        {
            get { return ToolTipTitle.Text; }
            set { ToolTipTitle.Text = value; }
        }
    }
}
After that, press Shift + F6 for building the DLL file.
Now we can create a WPF application and use our custom user control in it.
Thus we should choose WPF Application Project.

WPF APP

Then we have to add our User Control DLL file in the references.



We are going to use the custom User Control within a XAML window.
So we have to add an extra XAML code.
We have to add the following line within Window element :
user control XAML
At last we must have a Window tag in our XAML code like this :
<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:myToolTip="clr-namespace:CustomToolTip;assembly=CustomToolTip"
    Title="Window1" Height="600" Width="800">

</Window>

OK, now we can use the User Control in the XAML code with a XAML code like this :

user control XAML
At last I've created this XAML code :
<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:myToolTip="clr-namespace:CustomToolTip;assembly=CustomToolTip"
    Title="Window1" Height="600" Width="800">
    <Grid x:Name="rootGrid" RenderTransformOrigin="0.5,0.5">
    	<Grid.RenderTransform>
    		<TransformGroup>
    			<ScaleTransform ScaleX="1" ScaleY="1"/>
    			<SkewTransform AngleX="0" AngleY="0"/>
    			<RotateTransform Angle="0"/>
    			<TranslateTransform x:Name="rootGridXY" X="0" Y="0"/>
    		</TransformGroup>
    	</Grid.RenderTransform>
        <Rectangle Margin="26,34,496,374" Name="rectangle1" Stroke="Black" 
                   Fill="Coral" MouseLeave="rectangle_MouseLeave" MouseMove="rectangle_MouseMove" />
        <Rectangle Fill="Lavender" Margin="537,29,53,376" Name="rectangle2" 
                   Stroke="Black" MouseMove="rectangle_MouseMove" MouseLeave="rectangle_MouseLeave" />
        <Rectangle Fill="Peru" Margin="192,391,186,37.995" Name="rectangle3" 
                   Stroke="Black" MouseMove="rectangle_MouseMove" MouseLeave="rectangle_MouseLeave" />
        <myToolTip:UserControl1 UserControlTextBlockToolTip="Some texts" 
                                UserControlToolTipTitle="Title" 
                                Visibility="Hidden" 
                                x:Name="customToolTip" />
    </Grid>
</Window>

And these are the methods for showing or hiding our custom ToolTip:
namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        private void rectangle_MouseLeave(object sender, MouseEventArgs e)
        {
            state = true;
            customToolTip.Visibility = Visibility.Hidden;
        }

        bool state = true;
        Random rand = new Random(DateTime.Now.Millisecond);

        private void rectangle_MouseMove(object sender, MouseEventArgs e)
        {
            if (state)
            {
                customToolTip.Visibility = Visibility.Visible;
                customToolTip.UserControlToolTipTitle = (sender as Rectangle).Name.ToUpperInvariant();
                customToolTip.UserControlTextBlockToolTip = "";
                for (int i = 0; i < rand.Next(1, 30); i++)
                    customToolTip.UserControlTextBlockToolTip += (sender as Rectangle).Name 
                    	+ "\t" + i.ToString() + "\n";
            }
            customToolTip.UserControlToolTipX = Mouse.GetPosition(this).X + 10;
            customToolTip.UserControlToolTipY = Mouse.GetPosition(this).Y + 10;
            state = false;
        }
    }
}

That's all.

History

First post : 24th of January , 2009

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Mohammad Dayyan

Iran (Islamic Republic Of) Iran (Islamic Republic Of)
No Biography provided

Comments and Discussions


Discussions posted for the Published version of this article. Posting a message here will take you to the publicly available article in order to continue your conversation in public.
 
QuestionError when copying and paste the code Pin
Syed Akmal at 28-Oct-14 18:17
memberSyed Akmal28-Oct-14 18:17 
GeneralMy vote of 5 Pin
Shabana Parveen at 11-Apr-13 10:31
memberShabana Parveen11-Apr-13 10:31 
Suggestion[My vote of 1] Not clear .... jumping from one topic to another topic without addressing what is going on. Pin
Ramsin at 27-Feb-13 16:11
memberRamsin27-Feb-13 16:11 
GeneralMy vote of 4 Pin
Alireza Vaezi at 4-Dec-12 12:50
memberAlireza Vaezi4-Dec-12 12:50 
GeneralHow to Create a WPF User Control & Use It in a WPF Application ( C# ) Pin
123tran at 1-Aug-12 0:41
member123tran1-Aug-12 0:41 
GeneralMy vote of 4 Pin
SteveQ56 at 3-Apr-12 2:53
memberSteveQ563-Apr-12 2:53 
GeneralMy vote of 5 Pin
sepidar_902 at 20-Dec-11 22:53
membersepidar_90220-Dec-11 22:53 
GeneralMy vote of 4 Pin
wookie2u@gmail.com at 25-Oct-11 18:31
memberwookie2u@gmail.com25-Oct-11 18:31 
Generalnice article... Pin
Prasanth334 at 26-Aug-11 1:28
memberPrasanth33426-Aug-11 1:28 
Generalnot bad Pin
CIDev at 10-Jun-11 5:59
memberCIDev10-Jun-11 5:59 
GeneralMy vote of 1 Pin
jenik at 21-Apr-11 15:47
memberjenik21-Apr-11 15:47 
GeneralThank you (Vote of 5) Pin
Jyothikarthk at 12-Apr-11 19:25
memberJyothikarthk12-Apr-11 19:25 
GeneralMy vote of 5 Pin
Chloe Lim at 8-Mar-11 23:45
memberChloe Lim8-Mar-11 23:45 
Generalthanks Pin
JackVR at 3-Oct-10 9:45
memberJackVR3-Oct-10 9:45 
GeneralMy vote of 5 Pin
mrsnipey at 25-Jul-10 17:38
membermrsnipey25-Jul-10 17:38 
Generalmoshkel Pin
sadegh-zarifi at 6-Mar-10 1:58
membersadegh-zarifi6-Mar-10 1:58 
GeneralRe: moshkel [modified] Pin
_Mohammad_ at 6-Mar-10 9:07
member_Mohammad_6-Mar-10 9:07 
GeneralWPF Persian Calendar + User ToolTip Pin
anen at 5-Feb-10 7:10
memberanen5-Feb-10 7:10 
GeneralRe: WPF Persian Calendar + User ToolTip Pin
_Mohammad_ at 5-Feb-10 7:58
member_Mohammad_5-Feb-10 7:58 
GeneralRe: WPF Persian Calendar + User ToolTip Pin
anen at 5-Feb-10 8:43
memberanen5-Feb-10 8:43 
GeneralGood effort Pin
nasq at 9-Feb-09 11:17
membernasq9-Feb-09 11:17 
GeneralRe: Good effort Pin
Mohammad Dayyan at 9-Feb-09 11:51
memberMohammad Dayyan9-Feb-09 11:51 
GeneralMy vote of 2 Pin
danysm123 at 27-Jan-09 22:34
memberdanysm12327-Jan-09 22:34 
GeneralMy vote of 1 Pin
Jeremy Alles at 27-Jan-09 8:44
memberJeremy Alles27-Jan-09 8:44 
GeneralRe: My vote of 1 Pin
Mohammad Dayyan at 27-Jan-09 18:28
memberMohammad Dayyan27-Jan-09 18:28 
GeneralRe: My vote of 1 Pin
mrsnipey at 25-Jul-10 17:40
membermrsnipey25-Jul-10 17:40 
GeneralDependency Properties Pin
mattraffel at 27-Jan-09 5:39
membermattraffel27-Jan-09 5:39 
GeneralRe: Dependency Properties Pin
Mohammad Dayyan at 27-Jan-09 18:21
memberMohammad Dayyan27-Jan-09 18:21 
GeneralRe: Dependency Properties Pin
Yury Goltsman at 28-Jan-09 8:08
memberYury Goltsman28-Jan-09 8:08 
GeneralRe: Dependency Properties Pin
Mohammad Dayyan at 28-Jan-09 8:22
memberMohammad Dayyan28-Jan-09 8:22 
GeneralYou created WPF control... So what? [modified] Pin
taras_b at 24-Jan-09 22:55
membertaras_b24-Jan-09 22:55 
GeneralRe: You created WPF control... So what? Pin
Mohammad Dayyan at 25-Jan-09 2:28
memberMohammad Dayyan25-Jan-09 2:28 
GeneralRe: You created WPF control... So what? Pin
ldyc at 28-Jan-09 6:40
memberldyc28-Jan-09 6:40 
GeneralRe: You created WPF control... So what? Pin
cwp42 at 2-Feb-09 22:08
membercwp422-Feb-09 22:08 
GeneralRe: You created WPF control... So what? Pin
taras_b at 2-Feb-09 23:48
membertaras_b2-Feb-09 23:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    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.150427.1 | Last Updated 24 Jan 2009
Article Copyright 2009 by Mohammad Dayyan
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid