Click here to Skip to main content
Click here to Skip to main content

How to Create a WPF User Control & Use It in a WPF Application ( C# )

By , 24 Jan 2009
 
preview

Introduction

This article shows you how we can create a 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 similar articles like this, for example, see this article that was written by Sacha Barber.

Using the Code

There we go. First we should create a 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 a 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 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)

About the Author

Mohammad Dayyan
Iran (Islamic Republic Of) Iran (Islamic Republic Of)
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberShabana Parveen11 Apr '13 - 9:31 
very nice for beginners like me...
Suggestion[My vote of 1] Not clear .... jumping from one topic to another topic without addressing what is going on.memberRamsin27 Feb '13 - 15:11 
If somebody knows a topic very well but doesn't know how to teach or share it then it would be better stick to his desk and does his coding.
 
I'm sure you know your stuff very well and doing a great job every day but honestly look at your articles it is not clear. I am sorry but I just want to let you know you better clear things out here. We already have a namespace here then in next block you see another namespace in the snippet.
 
I am hoping you will modify your sharing method ... this is nothing but confusion.
 
Thanks anyway for your try.
GeneralMy vote of 4memberAlireza Vaezi4 Dec '12 - 11:50 
I learnt how to make a userControl by reading this Smile | :)
GeneralHow to Create a WPF User Control & Use It in a WPF Application ( C# )member123tran31 Jul '12 - 23:41 
when I use user control and I want set dynamic content as code behind as c#.
with that subject, how I do?(developer metro app)
GeneralMy vote of 4memberSteveQ563 Apr '12 - 1:53 
Simple intro - exactly what a beginner needs!
Well done.
GeneralMy vote of 5membersepidar_90220 Dec '11 - 21:53 
Thanx
GeneralMy vote of 4memberwookie2u@gmail.com25 Oct '11 - 17:31 
A good run down in the mechanics of creating a custom UserControl in VS2008, but the code/xaml doesn't follow best practices... for example, MyToolTip could, and therefore should (IMHO), Show and Hide itself. Four out five Wink | ;-)
Generalnice article...memberPrasanth33426 Aug '11 - 0:28 
Good article for learners like me to understand the user control concept.
 
Laugh | :laugh: thx. man
 
Regards,
Prasanth
Generalnot badmemberCIDev10 Jun '11 - 4:59 
Not very in depth, but useful for folk just starting out.
Just because the code works, it doesn't mean that it is good code.

GeneralMy vote of 1memberjenik21 Apr '11 - 14:47 
There are other ways to do it. more easy
GeneralThank you (Vote of 5)memberJyothikarthk12 Apr '11 - 18:25 
Hey, Just what I wanted to read about... Thanks for sharing! Smile | :) Smile | :)
-
Bits and Bytes Rules!
10(jk)

GeneralMy vote of 5memberChloe Lim8 Mar '11 - 22:45 
a very good start on using user control. 5 from me
GeneralthanksmemberJackVR3 Oct '10 - 8:45 
thanks, good for noobs like me
GeneralMy vote of 5membermrsnipey25 Jul '10 - 16:38 
Nice and simple.
Generalmoshkelmembersadegh-zarifi6 Mar '10 - 0:58 
saLLam mohhamad jan
khobi
omid varm ke betooni ino bekhooni
agha ye moshkel
ya soaL???
mohammad jan
man mikham to C# shapes bekesham
albate ba mouse
nemiiiiitoonam
komak kon
Lotfan
in maile mane
sadegh_roma@yahoo.com
GeneralRe: moshkel [modified]member_Mohammad_6 Mar '10 - 8:07 
Hi dear Sadegh,
I Google your problem, and I've found some solutions, I think the following link can resolve your problem
http://stackoverflow.com/questions/975767/mouse-followed-drawing-in-c[^]
modified on Saturday, March 6, 2010 2:14 PM

GeneralWPF Persian Calendar + User ToolTipmemberanen5 Feb '10 - 6:10 
Hello
I am wondering could you add the tooltip to the wpf , so that if you have mouse hover on the date it will show is it's a holiday( thoose mark ones ). Can you give me a clue how to start - doing it ,but can't to the date's.
 
Sorry for my English - not a native speaker
GeneralRe: WPF Persian Calendar + User ToolTipmember_Mohammad_5 Feb '10 - 6:58 
Hi anen,
Maybe Persian Diary in WPF[^] help you.
GeneralRe: WPF Persian Calendar + User ToolTipmemberanen5 Feb '10 - 7:43 
Thx Smile | :)
GeneralGood effortmembernasq9 Feb '09 - 10:17 
Dayyan!
 
Dont be disappointed by some racists even here. Keep it up. Good job
GeneralRe: Good effortmemberMohammad Dayyan9 Feb '09 - 10:51 
Thank you nasq
GeneralMy vote of 2memberdanysm12327 Jan '09 - 21:34 
This is trivial USER control
i did not see any complex users control or samples that create the UC dynamicly and on runtime change there apperence
GeneralMy vote of 1memberJeremy Alles27 Jan '09 - 7:44 
useless, lot of spelling errors
GeneralRe: My vote of 1memberMohammad Dayyan27 Jan '09 - 17:28 
Grammar errors ! yeah Blush | :O
But not spelling errors .
GeneralRe: My vote of 1membermrsnipey25 Jul '10 - 16:40 
I liked your article.
Nice and simple. Cleared up a few xmlns declaration issues I was having.
Keep up the good work.

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 24 Jan 2009
Article Copyright 2009 by Mohammad Dayyan
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid