Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use custom Controls in WPF

Tags:

c#

wpf

I have created a custom control in C# ( Overridden methods in Button control and added new events) . I need to use this control in my wpf application. In WinForms i can use this by ToolBox(right click) --> Choose Items -->Browse. where as in WPF i can not import the custom controls. Is there any way to do this

like image 742
Thorin Oakenshield Avatar asked Sep 22 '10 09:09

Thorin Oakenshield


People also ask

How do I customize WPF controls?

Create a new WPF project and then right-click on your solution and select Add > New Item... It will open the following window. Now select Custom Control (WPF) and name it MyCustomControl. Click the Add button and you will see that two new files (Themes/Generic.

How do you use custom control?

On the Add Control page, select the control that you want, such as the Linear Slider control shown here, and then select Add. Choose the client where you want the control to appear. Web. To make the custom control available from any web browser, select the Web option next to the control.

What is the difference between user control and custom control in WPF?

A customControl can be styled and templated and best suited for a situation when you are building a Control Library. On the contrary, a UserControl gives you an easy way to define reusable chunk of XAML which can be reused widely in your application and when you don't need to use it as a Control Library .


1 Answers

might need a rebuild for the certain project then a xaml file should be active. Your custom control should appear in the toolbox. if it doesn't show. you can do the following:

in your xaml file, somewhere in the header tag, where you see many of the xmlns:yyy, add a new xmlns: for example:

<Window
    x:Class="MyProject.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:custom="clr-namespace:MyProject">

where custom is any identifier for the name space and MyProject is the namespace. Dont worry about this because when you type "xmlns:custom=" (without the quotes) intellisense will give you choice of existing namespaces currently referenced. so just choose the appropriate namespace from the drop down and press enter.

now scroll down to where you want to put your custom control and:

<custom:MyControl Content="Click Me!" Click="Button_Click" />

custom:MyControl is from the xmlns:custom (above) and the Control name, MyControl Content is the Content property assigned "Click Me!" and Click is the Click event with the handler "Button_Click".

Hope this helps!

like image 115
nathan_hc Avatar answered Oct 09 '22 01:10

nathan_hc