Syndicate

News

My name's Marco De Sanctis and I'm an IT professional from Italy. This is my technical blog, about .NET and related application development and design technologies.

Download my Resume (.doc)

Recent Comments

10/23/2008 at 3:48 PM

sorry, my previous post was not complete... I trie...
by glondi

Read more...

9/22/2008 at 10:03 AM

Good one!!!Could you please post source code for t...
by Nisa

Read more...

9/10/2008 at 5:53 PM

I didn't even realize people were aware of the WPF...
by Mike Brown

Read more...

9/8/2008 at 1:22 AM

Marco,How are you handling scenarios where you nee...
by ctodd

Read more...

9/3/2008 at 1:00 AM

@ctodd: Hi,basically for the reasons I described a...
by Marco De Sanctis

Read more...

Recent Posts

Crunch mode is a pure waste of time, energy and money

7/31/2008 at 5:41 PM

Read more...

Double Click on the .sln file doesn't open Visual Studio on Vista

7/27/2008 at 9:02 AM

Read more...

Domain Model & Aggregates: when do master-detail associations happen?

7/22/2008 at 4:08 PM

Read more...

How I Got Started in Software Development

7/14/2008 at 12:16 AM

Read more...

Unleash the power of VisualStateManager with custom states

6/30/2008 at 12:12 AM

Read more...

Spread a property from Window to Controls (the WPF way)

posted on Wednesday, May 07, 2008 12:10 AM | Filed Under [ WPF ]

Today I was preparing a demo app which integrates WPF and LinqToSql. The idea is to implement the same pattern I've always used with NHibernate: a Session DataContext per Window, automatically disposed when its owner is closed and shared among all the various UserControls it has.

So, what I did was building my custom window class with an amazing MyDatabaseDataContext property in it

   10 public class PersistentWindow : Window

   11 {

   12     private MyDatabaseDataContext myDatabaseDataContext =

   13         new MyDatabaseDataContext();

   14     public MyDatabaseDataContext MyDatabaseDataContext

   15     {

   16         get { return myDatabaseDataContext; }

   17         set { myDatabaseDataContext = value; }

   18     }

   19 }

Now, every window in my application can access the built in LINQ DataContext simply inheriting from my PersistentWindow custom class:

    1 <classes:PersistentWindow x:Class="MySampleApp.MainWindow"

    2    xmlns="http://...."

    3    xmlns:x="http://...."

    4    xmlns:classes="clr-namespace:MySampleApp.Classes"

    5    Title="Demo Application" Height="450" Width="600">

Pretty easy, isn't it? But often I do love holding a lot of logic and layout inside UserControls, both to keep my home window code simple and to build re-utilizable blocks; and almost always those UserControl need some DataBase access, that's why I need to share PersistentWindow's DataContext among all the UserControls.

If I was in Windows Forms, I probably would have ended shadowing the FindForm method with something like this:

    9 public PersistentForm FindForm()

   10 {

   11     return base.FindForm() as PersistentForm;

   12 }

But WPF has that fantastic DependencyProperty infrastructure, so maybe could be more elegant to leverage its Value Inheritance to achieve our goal. In fact, value inheritance allows property value inheritance across controls logical tree. That means that, if both your parent (window) control and your some-level child (UserControl) have the same property, the parent's property value is forwarded to every child unless they don't redefine their own value.

What we need to do is rewriting our MyDatabaseDataContext property as an AttachedProperty:

   13 public static readonly DependencyProperty MyDatabaseDataContextProperty =

   14     DependencyProperty.RegisterAttached("MyDatabaseDataContext",

   15     typeof(MyDatabaseDataContext), typeof(PersistentWindow),

   16     new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.Inherits));

   17 public static void SetMyDatabaseDataContext(

   18       UIElement instance, MyDatabaseDataContext value)

   19 {

   20     instance.SetValue(MyDatabaseDataContextProperty, value);

   21 }

   22 public static MyDatabaseDataContext GetMyDatabaseDataContext(UIElement instance)

   23 {

   24     return instance.GetValue(

   25         MyDatabaseDataContextProperty) as MyDatabaseDataContext;

   26 }

Did you notice that Inherits flag? It's what does all the magic! In fact, having a reference to window's Linq Context from our custom UserControl is simply a matter of writing a property like this:

   11 public class PersistentUserControl : UserControl

   12 {

   13     public MyDatabaseDataContext MyDatabaseDataContext

   14     {

   15         get

   16         {

   17             return this.GetValue(

   18                 PersistentWindow.MyDatabaseDataContextProperty)

   19                 as MyDatabaseDataContext;

   20         }

   21         set

   22         {

   23             this.SetValue(PersistentWindow.MyDatabaseDataContextProperty, value);

   24         }

   25     }

   26 }

Nice, isn't it?

kick it on DotNetKicks.com

Technorati tags: ,

Comments

Gravatar
# re: Spread a property from Window to Controls (the WPF way)
Posted by Nicolò Carandini on 5/9/2008 11:58 AM
Bellissimo post.
Accidenti, ora mi tocca installare un feed reader, perchè ci sono sempre più bloggers (che a me interessano) che postano fuori muro UGI.
Sei la goccia che fa traboccare il vaso!
Gravatar
# re: Spread a property from Window to Controls (the WPF way)
Posted by Marco De Sanctis on 5/9/2008 12:10 PM
Grazie Nicolò!
Gravatar
# re: Spread a property from Window to Controls (the WPF way)
Posted by alkampfer on 5/10/2008 3:23 PM
Heheh, purtroppo il blog in inglese è veramente una grande tentazione :D

Alk.
Gravatar
# re: Spread a property from Window to Controls (the WPF way)
Posted by Derek Lakin on 5/12/2008 11:11 AM
"But WPF has that fantastic DependencyProperty infrastructure, so maybe could be more elegant to leverage its Value Inheritance to achieve our goal. In fact, value inheritance allows property value inheritance across controls logical tree. That means that, if both your parent (window) control and your some-level child (UserControl) have the same property, the parent's property value is forwarded to every child unless they don't redefine their own value."
The above quote from your post is absolutely correct, but it realising this you haven't made the correct use of the available WPF features.

The FrameworkElement class (the base class which Window, Control, UserControl, etc inherit from) defines the DataContext dependency property, which you could more easily assign the value of your LINQ data context, which would then automatically be available in the DataContext property of all of the child user controls.

If you still needed the native DataContext property for other (data binding for example) then the more correct solution would be to define a new "dependency" property not an "attached" property. The main purpose of atatched properties is to enable child controls to set a property defined in the parent (such as Canvas.Left and Canvas.Top) rather than inheriting a value from the parent.

I hope this helps :)
Gravatar
# re: Spread a property from Window to Controls (the WPF way)
Posted by Marco De Sanctis on 5/12/2008 12:38 PM
Hi Derek, thanks for your feedback.

DataContext is a property dedicated to store the default binding source. Being an object, you can obviously use it to transfer property values from parent to children, but I'd prefer leaving it for its original purpose. Moreover, what if you have more than one property whose values you need to share?

That's why I chose to create a custom property. That said, when you need value inheritance, you should always rely on Attached properties instead of simple Dependency ones, according to this article on MSDN Library:
http://msdn.microsoft.com/en-us/library/ms753197.aspx#Making_a_Custom_Property_Inheritable

"Although property value inheritance might appear to work for nonattached dependency properties, the inheritance behavior for a nonattached property through certain element boundaries in the run-time tree is undefined. Always use RegisterAttached to register properties where you specify Inherits in the metadata."

Do you see any drawback on using attached props for that purpose?
Gravatar
# re: Spread a property from Window to Controls (the WPF way)
Posted by Derek Lakin on 5/13/2008 3:54 PM
Hi Marco,

I appreciate that the DataContext property is intended for the default binding source, but I had assumed that was the purpose of using a LINQ context in your example. I did also say that you would need to use an alternative solution if you wanted to use the DataContext property.

Thank you for highlighting the guidance on using Attached Properties for implementating DP inheritance. I hadn't realised this at all. I feel a blog post coming on ;)
Gravatar
# re: Spread a property from Window to Controls (the WPF way)
Posted by Nisa on 9/22/2008 10:03 AM
Good one!!!
Could you please post source code for this as well?
Gravatar
# hwiuwmnl
Posted by hwiuwmnl on 1/7/2009 5:29 AM
hwiuwmnl
Gravatar
# Dixie chicks.
Posted by Find call girls and private chicks. on 1/24/2009 6:13 AM
Black dicks latin chicks. Hot naked chicks. Chicks sporting goods. Squirting chicks. Biker chicks. Amateur chicks galleries. Dixie chicks lyrics. Black dicks white chicks. Drunk chicks.
Gravatar
# Buy no phentermine prescription.
Posted by Online phentermine. on 1/27/2009 4:37 AM
Phentermine. Xenical hgh phentermine quit smoking detox. Danger of phentermine. Buy phentermine diet pill.
Gravatar
# Animal sex pics.
Posted by Weird animal sex pictures. on 1/30/2009 4:37 AM
Animal sex movies. Free animal sex videos. Animal sex mating. Animal sex stories free. Free animal sex movies.
Gravatar
# Viagra.
Posted by Viagra. on 3/8/2009 9:48 AM
Buy viagra online. Viagra. Pictures of viagra. Re viagra cello. Ship free viagra sample.
Gravatar
# Boy fucking granny.
Posted by Granny movie galleries. on 3/8/2009 5:23 PM
Granny porn. Granny movies. Granny tits. Granny gallery. Granny pussy. Granny planet.
Gravatar
# Re viagra cello.
Posted by Viagra. on 3/9/2009 9:30 AM
Generic viagra.
Gravatar
# Tramadol.
Posted by Tramadol. on 3/9/2009 8:11 PM
Tramadol.
Gravatar
# Granny free.
Posted by Granny post. on 3/10/2009 11:18 AM
Granny porn. How do i convert my garage to a granny flat. Older granny. Granny sex. Granny gallery. Granny pics.
Gravatar
# Vicodin detox.
Posted by Effects of vicodin. on 7/8/2009 8:19 AM
Vicodin online. Vicodin. Vicodin side effects. Vicodin at overseas pharmacies. Vicodin without prescription.
Gravatar
# Ashes of soma lyrics.
Posted by Ashes of soma lyrics. on 7/9/2009 12:34 AM
Soma side effects. Soma. Soma information.
Gravatar
# Soma.
Posted by Soma. on 7/10/2009 12:11 AM
Soma next day delievery. Pornstar soma.
Gravatar
# Drug test detect ephedra.
Posted by Ephedra is it legal. on 7/11/2009 12:12 AM
Wyoming ephedra attorney. Ephedra products for sale. Ephedra swarm. Atlanta ephedra attorneys. Delaware ephedra lawyers. Buy ephedra online. Ephedra.
Gravatar
# Phentermine side effects.
Posted by Phentermine no prescription. on 7/12/2009 12:07 AM
Phentermine.
Gravatar
# Vicodin.
Posted by Vicodin. on 7/13/2009 12:25 AM
Vicodin. Quiting vicodin information. Vicodin no rx.
Gravatar
# Vicodin.
Posted by Vicodin overdose. on 7/14/2009 12:37 AM
Darvocet vs vicodin. Vicodin. Buy vicodin without script.
Gravatar
# Buy vicodin without prescription.
Posted by Drug vicodin. on 7/19/2009 12:47 AM
Vicodin. Prescriptions drugs pharmacy online vicodin. Vicodin without prescription. Buy vicodin without script. How l ong does vicodin stay in your system. Buy vicodin.
Gravatar
# Percocet.
Posted by Percocet. on 7/20/2009 1:21 AM
Canadian prescritions and percocet. Mixing tylenol 3 and percocet. Percocet. Buy percocet online without office visit.
Gravatar
# Buy valium c.o.d..
Posted by Buy valium. on 8/8/2009 7:50 AM
Buy valium c.o.d.. Buy valium. Buy valium online without a prescription. Buy valium online.
Gravatar
# Codeine.
Posted by Metabolism of codeine in urine. on 8/8/2009 8:11 AM
Codeine cough syrup. Codeine.
Gravatar
# Hydrocodone.
Posted by Buy hydrocodone online. on 8/9/2009 10:48 AM
Hydrocodone. Elimination of hydrocodone in urine drug screens. Hydrocodone international pharmacies. Snorting hydrocodone.
Gravatar
# Adderall.
Posted by Adderall prescription. on 8/9/2009 11:17 AM
Buy adderall without a prescription. Dosage and tolerance to adderall. Adderall. Adderall online pharmacy.
Gravatar
# Buy hydrocodone.
Posted by Buy hydrocodone. on 8/9/2009 8:17 PM
Buy hydrocodone.
Gravatar
# Ativan.
Posted by Ativan without prescription. on 8/10/2009 3:15 AM
Who makes ativan. Generic ativan.
Gravatar
# Levoxyl vs levothyroxine.
Posted by Levothyroxine. on 8/10/2009 6:31 AM
Levothyroxine and fiber interaction. Levothyroxine sodium for dogs. Levothyroxine weight loss. Levothyroxine. Levothyroxine altrenitive.
Gravatar
# Canine dosage amoxicillin.
Posted by Amoxicillin anti-inflammatory. on 8/11/2009 7:37 AM
Amoxicillin orange suspension. Amoxicillin. Amoxicillin dosage. Amoxicillin kills acne. Amoxicillin online no prescription.
Gravatar
# Buy ambien 10.
Posted by Buy ambien without prescription. on 8/11/2009 5:23 PM
Ambien buy. Buy ambien 12.5 mgm overnight mail md consultation. Buy ambien overnight mail md consultation. Buy ambien online cod. Ambien where can i buy next day delivery. Buy ambien without prescription. Buy ambien.
Gravatar
# Buy cheap adderall online.
Posted by Buy adderall. on 8/11/2009 9:29 PM
Buy adderall. Buy adderall or dexadrine no prescription.
Gravatar
# Percocet dependency.
Posted by Percocet. on 8/12/2009 6:16 AM
Is darvocet stronger than percocet. Can percocet cause nightmares. Adrenaline levels after percocet. Percocet. Percocet vs vicodon. Cheap percocet. Percocet extract how to shoot.
Gravatar
# Fiorinal butalbital aspirin caffeine for migraines.
Posted by Fiorinal butalbital aspirin caffeine for migraines. on 8/12/2009 11:44 AM
Generic butalbital photos. Snort and butalbital. Butalbital apap tbmik. Butalbital. Side effects of butalbital.
Gravatar
# Butalbital fioricet com i.
Posted by Fioricet. on 8/13/2009 2:13 AM
Fioricet prescription. Fioricet side effects message board. Webresults fioricet. Fioricet. Fioricet online. Buy fioricet full information amp low prices. Fioricet plain pill.
Gravatar
# Buy adderall online no prescription.
Posted by Buy cheap adderall online. on 8/13/2009 3:35 AM
Buy cheap adderall online. Buy wholesale adderall. Buy adderall. Buy adderall online. Buy adderall without a prescription. Buy adderall xr perscriptionless.
Comments have been closed on this topic.