Archive

Archive for the ‘Code’ Category

Naming your WPF and Silverlight resources

February 15th, 2009

imageI’ve written about WPF resource organization and keeping XAML clean before. Recently I came across a WPF sample application that had an interesting naming convention for brush resources.

Instead of naming a brush resource as MainWindowBackgroundBrush, they would use the name Background_MainWindow. At first, this may seem like an odd convention, especially with the underscore. However taken as a whole, this convention can be really useful in Expression Blend.

During the implementation process when applying brushes to WPF elements, the brushes can be quickly and easily set. Just select Brush Resources and find the correct brush. Since the brushes are in alphabetically order, all of the background brushes are in the same area. Likewise for the border and foreground brushes.

Also with this convention, we can remove the “Brush” word in the name since we can easily tell that a resource is a brush because the brush resources start with Border_, Background_, or Foreground_.

I think I will start following this naming convention in future WPF and Silverlight projects.

Code, Design , ,

Design Time Check for WPF and Silverlight

February 10th, 2009

Do you commonly check whether code is being run in Blend or in the Visual Studio design surface? Often times, this is necessary to load up sample data or to prevent code that could potentially break the “Blendability” of a WPF or Silverlight app.

In WPF, you can call the DesignerProperties.GetIsInDesignMode for it. In Silverlight, you can check for HtmlPage.IsEnabled property.

I check for design mode often and needed a simple, consistent method to mask the DesignerProperties call in WPF. In Silverlight, I wanted to hide the hacky HtmlPage.IsEnabled check and change it from being a not(!) check to a positive check. Also, when Silverlight support the DesignerProperties.GetIsInDesignMode method, I can just easily change my check in one place. With some refinements from friends at work, I condensed it to a single static property in App.xaml.cs that I can use throughout my application.

In App.xaml.cs:

public static bool IsInDesignMode
{
    get
    {
        #if Silverlight
            return !HtmlPage.IsEnabled;;
        #else
            return DesignerProperties.GetIsInDesignMode(new DependencyObject());
        #endif
    }
}

Note that the precompiler directives can be removed if you’re just targeting WPF or just targeting Silverlight

Here’s how I use it:

void MainView_Loaded(object sender, RoutedEventArgs e)
{
    if (App.IsInDesignMode)
    {
        LoadSampleData();
    }
    else
    {
        LoadRunTimeData();
    }
}

Code , ,