[null, null, {"document_url": "http://kishor-naik-dotnet.blogspot.in/2013/10/wpf-attached-property-in-wpf.html", "unformatted_src": "http://1.bp.blogspot.com/-LJR2Ptidy3Q/Ul6OUIcWu8I/AAAAAAAABiA/fyNFFbTf6QA/s400/AttachedProperty_output.JPG", "src": "http://1.bp.blogspot.com/-LJR2Ptidy3Q/Ul6OUIcWu8I/AAAAAAAABiA/fyNFFbTf6QA/s400/AttachedProperty_output.JPG", "formatted_filename": "AttachedProperty output", "rendered_width": 400, "rendered_height": 265}, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]

WPF - Attached Property in WPF

An attached property is a concept defined by XAML. An attached property is intended to be used as a type of global property that is settable on any object. In Windows Presentation Foundation (WPF), attached properties are typically defined as a specialized form of dependency property that does not have the conventional property "wrapper".

Why and When we create an Attached Property??? Big Question....

An Attached Behavior is simply an Attached Property.Using attached behaviors, you can bundle up a piece of event-handling logic in a small, specific, reusable package which you can then apply to controls using XAML even we can use attached Property in Style.

Lets take a simple example,suppose i want to create a textbox that allow to user to enter digit only. In traditionally way we use Textbox PreviewTextInput event to block non digit value.

Let see how can we achieve this task.

Create a WPF Application and give the solution name as SolAttachedBehavior.

Add a Textbox control in window,it is look like this

Now write the following Non digit blocking logic to Textbox PreviewTextInput Event,it is look like this

This approach works fine if we have one textbox but what about when we have multiple textboxes for blocking non digit value.it is not reusable code then what is the solution??? The solution is to make a reusable code with Attached Property.

Remove TextBox PreviewTextInput event from XAML and Comment PreviewTextInput event code in Code Behind.
Now we will create Attached Property for TextBox which block Non digit value.it is look like this.

An attached behavior in WPF is normally a static class with one or more attached properties. The trick in this class is to listen to the change event of one of the properties, and to act upon it.

Mapping TextBoxBehavior class in window XAML,it is look like this

Finally it is look like on window tag

Apply Attached Property to textBox,it is look like this

using attached property in style,it is look like this

Full XAML Code Click on Image for Better View

Download Source Code
Posted by Kishor Naik Programmer Note Programmer Quotes This site is best viewed in Microsoft Internet Explorer 7.0 and above NDepend Tool