See Sharp
Is it really just a matter of point of view ?

Your code is running even though the program is stopped (And the truth is out there)

February 14, 2008 09:15 by salfab

Récemment, je me suis trouvé face au cas fort étrange d'une application WPF donc l'interprétation du XAML par le designer générait une erreur alors que l'exécution du programme compilé se déroulait sans encombre. Phénomène normal ou paranormal ? La vérité est ici !

Tout d'abord, situons un peu le cadre du problème. Afin d'avoir un exemple simple pour illustrer le problème, j'ai créé un exemple de toute pièce.

Il s'agit d'une application WPF, et comme toute bonne application WPF, elle contient des Binding : Une TextBox qui est liée à une DependencyProperty (DP) de type int. La valeur de cet int sera située entre 1 et 7, et indiquera le nom du jour à afficher dans la textbox. malheureusement, comme nous sommes liés à un entier, WPF n'a aucun moyen de savoir que nous voulons afficher un nom de jour de la semaine.

Afin de directement couper cours aux NitPickers, je tiens à préciser qu'il s'agit ici d'un exemple un peu tiré par les cheveux mais qui a le mérite d'illustrer des problèmes du même acabit qui pourraient être rencontrés dans des contextes bien plus complexes. Dans un cas d'application réel, nous aurions utilisé l'enum DayOfWeek. Maintenant que ceci est clarifié, revenons-en au coeur du problème.

Si l'on se contente de faire un Binding entre une textbox et un entier, la représentation donnée par la méthode ToString apparaitra dans la textbox. Pour nous permettre de convertir notre entier en nom de jour de la semaine, nous allons utiliser un Value Converter.

les value converters permettent d'ajouter la tuyauterie manquante pour adapter la valeur de la source à celle que la cible attend.

Si par malheur, dans notre ValueConverter, nous utilisons un objet qui n'a pas de valeur par défaut, ou n'a pas été instancié par le constructeur d'une ressource déclarée dans le XAML - Les ressources déclarées dans le XAML sont également instanciées, et ce, même en mode design - la compilation du projet en cours se passera sans encombres, l'exécution également, mais le designer ne pourra pas afficher la fenêtre du programme à l'écran et ajoutera une erreur dans la fenêtre ErrorList. L'erreur qui sera mentionnée peut prendre plusieurs formes. Il s'agit généralement d'une erreur de référence nulle sur un objet, mais il arrive parfois d'avoir quelques surprises. Nous verrons en détails pourquoi. Si nous naviguons jusqu'à a portion de code concernée, nous verrons qu'elle se trouvera dans le XAML, sur l'élément auquel nous avons appliqué un Binding.

Pourquoi donc notre code fonctionne-t-il au runtime, et pas en mode design ? 

Dans le projet d'exemple attaché, nous avons initialisé un tableau de chaînes de caractères dans le constructeur de App. Ce constructeur, n'a aucune raison d'être exécuté par le designer puisqu'aucune application n'a été instanciée, jusqu'ici, rien de surprenant. Un comportement que les développeurs de contrôles utilisateurs sous winforms auront certainement déjà rencontré est le fait que lors du design d'une application utilisant un contrôle utilisateur, le contrôle vit. Il possède son propre comportement en mode design, et d'une certaine façon, il est, lui, déjà en cours d'exécution.

En ce qui concerne le Binding en WPF, il s'agit du même phénomène : Le fait de permettre l'affichage à l'écran en live des modifications de notre interface graphique implique qu'une certaine logique applicative décrive la façon dont ces modifications seront reflètées. Dans la plupart des cas, cette logique applicative est incluse dans la framework .Net et est tout à fait transparente pour le développeur, cependant, dans noter cas, nous utilisons une fonctionnalité avancée pour nous permettre de crocher notre propre logique applicative dans le processus de rendu.

Afin de pouvoir continuer à reflèter les changements lors du design de façon cohérente, le designer va prendre en compte notre ValueConverter, et l'exécuter. Si celui-ci contient un bug, une exception sera générée. Généralement, il s'agit d'une erreur de type Object reference not set to an instance of an object, mais dans certains cas, l'erreur mentionnée peut être d'un autre type, par exemple, une erreur de casting. Ceci s'explique par le fait qu'au lieu d'être levée et affichée dans une fenêtre d'exception comme au runtime, elle sera affichée dans la fenêtre ErrorList. Celle-ci ne permettant pas de naviguer dans les InnerExceptions, elle affiche uniquement l'exception de niveau le plus élevé. Le choix de représenter ces erreurs dans la fenêtre ErrorList n'est pas anodin. En utilisant cette représentation, il est possible de signaler plusieurs erreurs simultanément, chose qui ne serait pas possible avec l'affichage séquentiel de plusieurs fenêtres d'exceptions, et qui pourrait être réellement handicapant dans le cas où un nombre important d'erreurs serait commis.

Il existe diverses manières de résoudre ce problème :

  • La première, qu'il est recommandé d'adopter, est de revoir le design de l'application : Les cibles de Binding sont généralement des DependencyProperties. Il est également possible d'utiliser des collections ou des propriétés qui implémentent INotifyPropertyChanged ou INotifyCollectionChanged. Dans ce cas, il est recommandé d'opter plutôt pour une DependencyProperty, qui permettent, elles, de définir une valeur par défaut. Il conviendra de ne pas choisir la valeur null comme valeur par défaut, bien évidemment.
  • Il n'est malheureusement pas toujours possible de changer le design de son application sans remettre en cause une grande partie du code de l'application. Il existe donc une autre façon de procéder, moins élégante, mais qui peut parfois sauver des vies : De la même façon qu'en WinForms il existe la propriété DesignerMode, WPF tient à jour une DependencyProperty IsInDesignMode, accessible par la méthode GetIsInDesignMode. Cette méthode fait partie de la classe DesignerProperties.

En attachement, un petit projet Visual Studio 2008 dont certaines portions de code sont en commentaires, N'hésitez pas à vous amuser à commenter / décommenter les différentes portions du code pour mettre en action les différents comportements.

XFiles.zip (12,58 kb)


Comments

August 11. 2009 01:44

cash loans

Hello to all Smile I can�t understand how to add your site in my rss reader. Help me, please

cash loans

August 15. 2009 04:56

Tissot Ladies Watches Belle

Hey I love your style I will subscribe for your feed please keep posting!

Tissot Ladies Watches Belle

August 17. 2009 02:54

Omega Mens Seamaster Planet

I would like to add your blog to my blogroll please tell me what anchor should I use?

Omega Mens Seamaster Planet

August 19. 2009 00:31

Seiko 5 Wrist Watches

Do you earn decent money from this blog or are you doing it just for fun?

Seiko 5 Wrist Watches

August 27. 2009 13:53

Baume Mercier Classima

I like how you write.Are you interesting in a part time writer job?

Baume Mercier Classima

August 28. 2009 06:00

bad credit loans

There is obviously a lot to know about this.  I think you made some good points in Features also.

bad credit loans

March 4. 2010 07:09

hd movies

I enjoy streaming movies online, it is way easier than going to the theaters.

hd movies

March 27. 2010 00:46

cash til payday loan

That is some inspirational stuff. Never knew that opinions could be this varied. Thanks for all the enthusiasm to offer such helpful information here.

cash til payday loan

March 27. 2010 15:52

personal loans

good good…this post deserves nothing Frown  …hahaha just joking Tong …nice post Tong

personal loans

March 28. 2010 23:33

quick unsecured loans

Hey - nice blog, just looking around some blogs, seems a pretty nice platform you are using. I'm currently using Wordpress for a few of my sites but looking to change one of them over to a platform similar to yours as a trial run. Anything in particular you would recommend about it?

quick unsecured loans

April 28. 2010 08:42

Rapidshare

I\'m happy I found this blog, I couldnt discover any info on this subject matter prior to. I also run a site and if you want to ever serious in a little bit of guest writing for me if possible feel free to let me know, i\'m always look for people to check out my site. Please stop by and leave a comment sometime!

Rapidshare

May 15. 2010 04:36

executive chair

This is a very good posting, I discovered your web page searching aol for a similar subject and came to this. I couldnt get to much additional info on this article, so it was wonderful to find this one. I will probably be returning to look at some other articles that you have another time.

executive chair

May 16. 2010 21:27

enchanting farming step by step wow

The Zune concentrates on being a Portable Media Player. Not a web browser. Not a game machine. Maybe in the future it'll do even better in those areas, but for now it's a fantastic way to organize and listen to your music and videos, and is without peer in that regard. The iPod's strengths are its web browsing and apps. If those sound more compelling, perhaps it is your best choice.

enchanting farming step by step wow

May 18. 2010 22:07

how to make lots of gold with a dk

Sorry for the huge review, but I'm really loving the new Zune, and hope this, as well as the excellent reviews some other people have written, will help you decide if it's the right choice for you.

how to make lots of gold with a dk

May 22. 2010 11:36

cheap floor lamps

Great article. There's a lot of good information here, though I did want to let you know something - I am running Fedora with the up-to-date beta of Firefox, and the design of your blog is kind of bizarre for me. I can read the articles, but the navigation doesn't function so well.

cheap floor lamps

June 2. 2010 11:52

rugs for the home

Comedy has to be based on truth. You take the truth and you put a little curlicue at the end. . Just my 2 cents. Damian.

rugs for the home

June 3. 2010 21:41

best kitchen curtains

I just want to emphasize the good work on this blog, has excellent views and a clear vision of what you are looking for.

best kitchen curtains

June 5. 2010 02:42

 murano glass birds

Interesting post and I really like your take on the issue. I now have a clear idea on what this matter is all about. Thank you so much.

murano glass birds

June 6. 2010 17:05

logitech security camera

I harmonise with your conclusions and will thirstily look forward to your next updates. Just saying thanks will not just be enough, for the exceptional clarity in your writing. I will directly grab your rss feed to stay privy of any updates. Solid work and much success in your business endeavors!

logitech security camera

June 12. 2010 18:40

microsoft points

Greetings from West Virginia!  Just ran across your blog.  Actually took in your article, I'll pass it along!  Smile  Have a fantastic day!

microsoft points

June 15. 2010 17:41

Svitlana.Net.Ua

I would like to thank you for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. In fact your creative writing abilities has inspired me to start my own BlogEngine blog now.

Svitlana.Net.Ua

June 17. 2010 15:59

няня

I would like to thank you for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. In fact your creative writing abilities has inspired me to start my own BlogEngine blog now.
http://svitlana.net.ua/staff/category/3/ гувернантка, http://svitlana.net.ua/staff/category/5/ повар, http://svitlana.net.ua/staff/category/6/ садовник, http://svitlana.net.ua/staff/category/10/ репетитор, http://svitlana.net.ua/staff/category/4 домработница, http://svitlana.net.ua/staff/category/8/ семейная пара, http://svitlana.net.ua/pages/2/ работа няней.

няня

June 19. 2010 23:39

new alicia keys

Hi buddy, your blog's design is simple and clean and i like it. Your blog posts are superb. Please keep them coming. Greets!!!

new alicia keys

June 23. 2010 20:42

Лучшие индивидуалки

Когда настало время уезжать, мы нехотя бросали вещи в машину, и понимали, что прощаемся с морем до следующего  года, и ни где так не чувствуется приближение осени, как на море.

Лучшие индивидуалки

June 27. 2010 03:57

Онлайн Покер

Can you please provide more information on this subject? BTW your blog is great. Cheers.

Онлайн Покер

June 27. 2010 17:23

xbox membership

Greetings from North Carolina!  Just saw your site.  Actually read your article, I'll pass it along!  >:-o  Have a excellent day!

xbox membership

July 4. 2010 23:15

Магазин сантехники

I really got a kick out of your article. I don\\\'t really have much to say in reply, I only wanted to comment to reply with wonderful operate. good luck in 2010.

Магазин сантехники

July 8. 2010 05:28

Проститутки в Москве

You have some honest ideas here. I done a research on the issue and discovered most peoples will agree with your blog.

Проститутки в Москве

July 10. 2010 22:37

Проститутки

You gave nice ideas here. I done a research on the issue and learnt most peoples will agree with your blog. Certainly, these practices are unfair; but they say that most of their rules are only to apply to people who overdraw.

Проститутки

July 11. 2010 00:04

online dyslexia test

where can i find more info?

online dyslexia test

July 11. 2010 20:29

Новинки сантехники

It\\\'s an intriguing approach. I commonly see minimalist judgments on the matter but yours it\'s written in a pretty special way. For sure, I will revisit your site for more info.

Новинки сантехники

July 29. 2010 20:07

Andy Pollara

This is a interesting post.

Andy Pollara

August 6. 2010 18:39

продажа конфискованных автомобилей

Subsequently, after spending many hours on the internet at last We\'ve uncovered an individual that definitely does know what they are discussing many thanks a great deal wonderful post.

продажа конфискованных автомобилей

August 10. 2010 01:20

Смесители Grohe

Quality is what sets GROHE apart. The consistently high standard of our products in every category and price range has cemented our reputation as the best value, premium brand within the sanitary industry.
At GROHE we believe quality is defined by the highest levels of craftsmanship, outstanding durability, high levels of functionality, long-lasting design and convenience of use.

Смесители Grohe

August 18. 2010 16:03

букмекеры

Thanks for share. Great post. You\'re the best.

букмекеры

August 27. 2010 05:36

chat nude

Just wanted to give you a shout from the valley of the sun, great information. Much appreciated.

chat nude

August 30. 2010 03:06

Smokeless Cigarette

goodto see you make postings on this issue, I should bookmark this web site. Just keep up the good job.

Smokeless Cigarette

September 1. 2010 02:30

Lemonade Diet Ingredients

Thanks for the read, I will bookmark it and come back later to check out some of your other posts =)

Lemonade Diet Ingredients

September 4. 2010 09:25

Silver Bullion

What an amazing post that I have ever come through. It gives the information that I was really searching for the past week and I am really satisfied with this post. Need more like this. Thank you.

Silver Bullion

September 5. 2010 05:20

nude chat

I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post

nude chat

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading