Wednesday, September 22, 2010

Some Best Practices for Silverlight Application Development (XAML)

I was working with WPF/Silverlight since March 2008 and learnt lots of things. I wrote lots of Articles on Silverlight and published in my Blog. Today I decided to share you some of the best practices you should follow while doing development in WPF/Silverlight. Hope, this will help you guys while writing XAML codes. Read and try to strict with the guidelines whenever you are modifying your XAML.

 

Feedbacks are always appreciated. Hence, don’t forget to leave your comments at the end. If you have any more points, please share it here. I will review them and add those here.

 

Update [08-Aug-2010]: On popular demand, I updated this post with some explanation on “Why?”.

 

Some of the XAML coding best practices mentioned below:

  • Don’t use unnecessary “xmlns” namespaces in the XAML file. This overburdens the load time of the Silverlight page (If you are using Resharper, you can do this very easily as it will change the color of the unnecessary items to Grey).
  • Don’t add same namespaces multiple times in a single XAML page. It screws up the XAML code at the time of maintenance and also loads the assembly namespace multiple times causing various memory issues at runtime.
  • Use proper name for your “xmlns” namespace prefix. For example: xmlns:commonControls is more meaningful than xmlns:cctrl. This avoids multiple declarations of namespaces in future.
  • Try avoiding “xmlns” namespace prefix name as “local”. Instead use “localControls” or “localConverters” etc. as per your namespace name. Using “local” will not give you proper meaning. In the same assembly there may be two or more namespaces (e.g. Controls, Converters etc.). In such case, it will be helpful for you to use proper prefix name to distinguish between them in proper way.
  • When adding a control that has no elements inside it, better to close it by self-closing tag “/>” instead of the hard closing tag (</TAG>). This gives more cleaner XAML code. 
  • Remove all unnecessary resource keys if they are not in use. These increases the memory uses and you may sometime encounter some animation issues due to this. If you need it at later point of time, you are always welcome to add it.
  • Don’t use extra panels (e.g. Grid, StackPanel, Canvas etc.) unless it is required.
  • Always try to use Grid as your panel first and if you require other panels, use them. Grid has the flexible UI layout and thus resizing your application will have a great effect.
  • Never try to give a name to all of your controls inside your Silverlight page as it takes unnecessary object creation at the time of load. Name only those elements which you want to use from your code behind and/or from your xaml. If you are using MVVM pattern, you can remove the naming of your controls in almost all the cases.
  • Use the Visibility property of the controls instead of the Opacity property to hide the content. Opacity to zero makes the control to hide but takes space in both memory and the UI. Other side, the Visibility property collapses the control from the UI, thus making spaces for the other controls in the same place.
  • Use proper formatting of your XAML code. This gives better look of code and also easy to maintain in future.
  • Use comments in XAML whenever require. This is useful when you revisit the code after a long time or some other person comes to work with your XAML file.
  • Try to use StaticResource instead of DynamicResource as it increases the performance and also it throws exceptions at development time. Hence, easier to identify the root cause.
  • Remove unnecessary styles & storyboard animations if they are not require at all.
  • Try to add your styles in a separate file if you want to share them across your application. If they are specific to a single page then add them in the page resource.


Save and Share!

Share/Bookmark

Posted via email from Mocha Brain Freeze

Thursday, September 16, 2010

Visual Studio Tip: Open XAML in code only mode

For those of us who prefer working in code

Posted via email from Mocha Brain Freeze

Tough on my feet

Luke complained this morning of a boy at school being bossy. Luke said the kid is scary. I said don't be scared your're tougher than him! Luke proudly proclaims yes I am! When I run away from him it's like this -- ZOOM!

Posted via email from Mocha Brain Freeze

Thursday, September 9, 2010

Debugging Data Bindings in a WPF or Silverlight Application - WPF & Silverlight Designer - Site Home - MSDN Blogs

Debugging Data Bindings in a WPF or Silverlight Application

The WPF and Silverlight platforms use late bound data binding resolution for bindings in XAML files. This feature allows a DataContext to be set at run-time and the objects within that DataContext to resolve their property bindings then. This late binding enables cool features like DataTemplates, composable applications and run-time loading of loose XAML.

A side effect of late bound binding resolution that can cause developers some minor frustration is that their controls do not display the expected data at run-time.

This article will explain troubleshooting techniques that can help you locate and correct the problem.

Data Binding Overview

Data binding is fundamental to WPF and Silverlight. You will struggle with your application designs, coding and troubleshooting until you understand data binding in these platforms.

The best data binding resource available is the MSDN Data Binding Overview topic. If you have not read or don't fully understand the material in this topic, please take the required amount of time to learn this material.

Ounce of Prevention is Worth a Pound of Cure

Visual Studio 2010 has great tooling to wire up data bindings and checked them at design-time. Please read this article: How to Enable Using the Binding Builder in WPF and Silverlight Applications.

Visual Studio 2010 has excellent design-time sample data support. If you use design-time sample data, you'll immediately see controls that don't have expected data values at design-time.

For a detailed examination of sample data in the WPF and Silverlight Designer for Visual Studio 2010, please read this article: Sample Data in the WPF and Silverlight Designer.

Troubleshooting List

  • Verify that DataContext is set in either XAML or code
  • Run the application and view the output in the Debug Output Window
    • For WPF applications you can increase or decrease the amount of information displayed in the Debug Output Window by changing the WPF Trace Settings, Data Binding value
  • Name the control that has DataContext assigned, set a break point in the code, and view the named control's DataContext property in the debugger
  • If binding to a CLR object, put a breakpoint in the source property getter to see that its actually being queried
  • Add a converter to a binding, then put a breakpoint in the converter

Verify that DataContext is set in either XAML or Code

This tip is along the lines of, "if the TV won't turn on, check that it's plugged in."

This is important for many reasons, but one is easily overlooked; if a DataContext is null, the Debug Output Window will not display any error messages in Silverlight or in WPF.

In WPF you can use the below PresentationTraceSources on a binding and set the TraceLevel to High to view errors related to a null DataContext.

View the Debug Output Window

If you have the DataContext set, any data bindings within that DataContext that can't be resolved will be listed in the Debug Output Window at run-time.

Sample Debug Output Window Data Binding Error

Sample One

System.Windows.Data Error: 40 : BindingExpression path error: 'FirstName' property not found on 'object' ''Object' (HashCode=62178992)'. BindingExpression:Path=FirstName; DataItem='Object' (HashCode=62178992); target element is 'TextBox' (Name=''); target property is 'Text' (type 'String')

Sample Two

System.Windows.Data Error: 40 : BindingExpression path error: 'FirstName' property not found on 'object' ''Customer' (HashCode=13640894)'. BindingExpression:Path=FirstName; DataItem='Customer' (HashCode=13640894); target element is 'TextBox' (Name=''); target property is 'Tag' (type 'Object')

While the above messages look verbose and complex, you can glean several interesting points of information that will help you correct this data binding:

  • The Binding Path is FirstName. Search your XAML file for FirstName and see if you expect the DataContext to expose a FirstName property whose scope will allow this binding to resolve this property.
  • The Source object in Sample One is of Type Object. There is a good chance the Type Object does not have a FirstName property.
  • The Source object in Sample Two is of Type Customer. Check your Customer Type; does it have a FirstName property?
  • Notice in Sample Two, the target property is Tag. In all likelihood, the Text property was the desired target property and not Tag. Also the Type of Tag is Object; you would probably be expecting String when binding to the FirstName property.

Review

  • Verify the property name is spelled correctly
  • Verify the property name has the correct character casing. FirstName is not the same as firstName.
  • Verify the property is a member of the DataContext Type
  • Verify the target element is the correct Type
  • Verify the target property name and Type are correct

Posted via email from Mocha Brain Freeze

Wednesday, September 1, 2010

Signs in Arizona warn of smuggler dangers - Washington Times

The federal government has posted signs along a major interstate highway in Arizona, more than 100 miles north of the U.S.-Mexico border, warning travelers the area is unsafe because of drug and alien smugglers, and a local sheriff says Mexican drug cartels now control some parts of the state.

The signs were posted by the Bureau of Land Management (BLM) along a 60-mile stretch of Interstate 8 between Casa Grande and Gila Bend, a major east-west corridor linking Tucson and Phoenix with San Diego.

They warn travelers that they are entering an "active drug and human smuggling area" and they may encounter "armed criminals and smuggling vehicles traveling at high rates of speed." Beginning less than 50 miles south of Phoenix, the signs encourage travelers to "use public lands north of Interstate 8" and to call 911 if they "see suspicious activity."

Pinal County Sheriff Paul Babeu, whose county lies at the center of major drug and alien smuggling routes to Phoenix and cities east and west, attests to the violence. He said his deputies are outmanned and outgunned by drug traffickers in the rough-hewn desert stretches of his own county.

"Mexican drug cartels literally do control parts of Arizona," he said. "They literally have scouts on the high points in the mountains and in the hills and they literally control movement. They have radios, they have optics, they have night-vision goggles as good as anything law enforcement has.

"This is going on here in Arizona," he said. "This is 70 to 80 miles from the border - 30 miles from the fifth-largest city in the United States."

He said he asked the Obama administration for 3,000 National Guard soldiers to patrol the border, but what he got were 15 signs.

Arizona Gov. Jan Brewer condemned what she called the federal government's "continued failure to secure our international border," saying the lack of security has resulted in important natural recreational areas in her state being declared too dangerous to visit.

In a recent campaign video posted to YouTube, Mrs. Brewer - standing in front of one of the BLM signs - attacked the administration over the signs, calling them "an outrage" and telling President Obama to "Do your job. Secure our borders."

BLM spokesman Dennis Godfrey in Arizona said agency officials were surprised by the reaction the signs generated when they were put up this summer.

Story Continues →

© Copyright 2010 The Washington Times, LLC. Click here for reprint permission.

‹‹ previous1234next ››

Posted via email from Mocha Brain Freeze