Welcome to MSDN Blogs Sign in | Join | Help

XamlpadX 4.0 now available

Lester Lobo has posted the latest version of the excellent XamlpadX utility here. This is a must-have for anybody who's doing serious XAML development.

 

xamlpadx screenshot

Posted by jgalasyn | 1 Comments

Visual Studio 2008 SP1 Docs Are Live on MSDN

The latest versions of the VS and .NET documentation are available on MSDN. Don't forget that MSDN is wiki-riffic -- you can add your own comments at the bottom of each page, in the Community Content section.

WPF Designer docs are here.

WPF docs are here.

Posted by jgalasyn | 1 Comments

Visual Studio 2008 SP1 and .NET Framework 3.5 SP1 are Live

Go forth and download:

A few value-adds:

  • The .NET Client Profile, which drastically reduces the size of the .NET Framework (by over 86%!) to allow for ease of deployment for .NET applications
  • Support for SQL Server 2008 both in Visual Studio and through features such as the ADO.NET Data Services and ADO.NET Entity Framework
  • Multiple enhancements to ASP.NET and TFS.  The performance and reliability issues we fixed in Visual Studio gives increased productivity to all developers.
Posted by jgalasyn | 0 Comments

Visualizing Climate Data in Phase Space

I've been reading the online draft (pdf) of Ray Pierrehumbert's excellent new book on climate science, Principles of Planetary Climate. On page 54, there's a nice graph of ocean 18O isotope levels over the past four million years. Using this data, we can infer how much of the planet's water was bound up in ice, as a function of time. The graph reminds me of the kind of trace you get from a nonlinear system that's in a chaotic state, so it seems like a neat idea to visualize this data in phase space. You may remember earlier posts of mine (here and here) on this subject.  Previously, I used music as a real-time input to a phase-space visualizer. This time, I decided to whip up a quick-and-dirty WPF PhaseSpaceControl class to view climate-related data in phase space.

A quick search brought me to Dr. Maureen Raymo's site, which has a convenient archive of climate data. Dr. Raymo constructs a model of 18O isotope levels over the Pliocene/Pleistocene epochs, from three million to one million years ago (1). She uses a model of ice volume that's driven by the computed insolation (amount of solar energy) at Earth's surface. Insolation varies deterministically with Earth's distance from the sun, with Earth's wobble as it spins (precession), and with Earth's axial tilt (obliquity).

This adds up to the following insolation in the Northern Hemisphere (NH) and Southern Hemisphere (SH) computed for the two million-year period under investigation. Figure 1 shows the computed insolation on Summer Solstice at 65N and 65S latitudes, from one million years before present (ybp)  to three million ybp. 

 

Raymo insolation  

Figure 1. Calculated 65°N summer insolation records for NH (21 June) and SH (21 December) (Raymo, et al.).

 

Using a simple ice-climate model, the following ice-sheet histories are computed.

 

Raymo ice sheet histories

Figure 2. NH (blue) and SH (red) modeled ice volumes (Raymo, et al.).

These traces show the modeled advance and retreat of ice sheets (glaciation and deglaciation) in the Northern and Southern Hemispheres.

Putting all this together, Dr. Raymo models the global sea level and corresponding 18O isotope levels.

 

Raymo sea level and d18O

Figure 3. Predicted sea level (solid line) and mean ocean δ18O (dashed line), derived from the ice volume histories in Fig. 2 (Raymo, et al.).

Finally, the predicted mean ocean δ18O is compared with the actual values recovered from ocean sediment cores (2).  

 

Raymo d18O predicted and observed

Figure 4. Comparison of predicted mean ocean δ18O and the LR04 stack (Raymo, et al.).

 

The agreement is pretty good. In particular, this model reproduces the puzzling 41,000-year (41 ky) frequency that dominates the measured δ18O record.

 

raymo spectra

Figure 5. Spectra of the LR04 stack, the paleomagnetically dated δ18O stack of Huybers, the paleomagnetically dated benthic δ18O record, 21 June summer insolation at 65°N, and NH model output from Fig. 2.

 

Insolation drives Earth's climate system*. You might imagine that the climate system responds to a signal like Figure 1 in a complex way. How many parameters does it take to describe that response? How many variables dominate the climate system?

Because the climate system is enormously complex, it's easy to think that the number of parameters required to describe its behavior is large. But one of the interesting results from nonlinear dynamics ("chaos theory") is that complex dynamics can arise from simple systems (and vice versa). There's something about the δ18O trace that makes me think that the number of parameters is small. How to test this idea? Constructing a phase space portrait can help.

We have a one-dimensional set of time series data that comprises a "slice" of the total system dynamics (δ18O measurements from ocean sediment cores). It's possible to recover the dynamics of the remaining dimensions by "embedding" the one-dimensional signal in a two-dimensional space, a three-dimensional space, and successively higher spaces. In principle, this is done by plotting the signal against its higher moments, i.e., against its first derivative, its second derivative, and so on. When we don't have direct measurements of these quantities, we can approximate them by plotting the signal against itself, with a time delay (for a 2D reconstruction) as follows.

x-axis: f(t)

y-axis: f(t-τ)

where f(t) is the signal, and τ is the time delay, usually expressed in number of samples.

This is the method of delays, and the resulting phase space reconstruction is sometimes called a pseudo-phase portrait.

For example, the Van der Pol oscillator can produce the following time series.

 

Figure 6. Signal from the Van der Pol oscillator viewed in the time domain (Van der Pol Oscillator).

 

When a one-dimensional Van der Pol signal is embedded in a two-dimensional phase space, the following phase portrait is the result.

 

Figure 7. Phase portrait of the Van der Pol oscillator (Phase Space).

 

A three-dimensional embedding uses a delay of for the third dimension.

z-axis: f(t-2τ) 

The following 3D phase portrait is reconstructed from electroencephalogram (EEG) data (3). The top trace shows the time series data, and the bottom diagram shows the corresponding phase portrait.

 

Michel Le Van Quyen phase space

Figure 8. Three-dimensional phase space reconstruction of neurological data (Michel Le Van Quyen).

 

Now we can examine the phase portraits of climate data I promised so long ago. Here are the phase portraits of the computed Northern Hemisphere (NH) insolation from Figure 1. The two-dimensional embedding is shown in the left frame, and the three-dimensional embedding is shown in the right frame.

 

NH insolation phase portraits

Figure 9. Phase portraits of the computed NH insolation from Fig. 1.

 

The value of τ = 32 samples is chosen by trial and error. I want the trace to intersect itself as seldom as possible. Because the 2D embedding looks "squashed" I assume that we need a 3D embedding to visualize the dynamics effectively. Not shown here is the rotation animation I've applied to the 3D phase portrait that lets me see it from different angles. Also, I've applied a cubic spline interpolation to the original data to make the phase portraits smoother. One interesting feature revealed by the 3D phase portrait is the presence of discrete bundles of orbits. This suggests that there is an attractor at work.

Here are the phase portraits of the computed global sea level, as a function of insolation and the simple ice-climate model used by Dr. Raymo.

 

global sea level phase portraits

Figure 10. Phase portraits of the computed global sea level Fig. 3.

 

Here's the same portrait, with the 3D embedding viewed from another angle.

 

global sea level phase portraits2  

Figure 11. Phase portraits of the computed global sea level from Fig. 3.

 

What's interesting about the 3D portrait is the introduction of a funnel shape to the dynamics.

Here are the portraits for the modeled mean ocean δ18O from Figure 3.

 

model d18o phase portraits

Figure 12. Phase portraits of the modeled δ18O from Fig. 3.

 

Banding in the phase portrait, similar to that in the insolation portrait (Figure 9), is still visible.

Finally, here's the phase portrait for the actual δ18O measurements from ocean sediment cores.

 

LR04 stack phase portraits

Figure 13. Phase portraits of the measured δ18O from Fig. 4. Original data have an applied cubic spline interpolation to smooth the portrait.

 

Okay, it's hard to tell much of anything from these. Banding isn't really apparent, and the overall portrait is a tangled mess. The only obvious similarity to the portraits in Figure 12 is the presence of the "outlier" orbits. We'll need a few more tools to tease anything out of these portraits. Future work includes:

  • Visualizing Poincaré sections, which show slices of that tangle and may reveal an attractor pattern;
  • Visualizing the phase-space flow, which involves displaying little arrows that follow the orbits around the phase portrait;
  • Reworking the PhaseSpaceControl to use a Trackport3D, which lets the user tumble and zoom the portrait with the mouse.

I'll keep you posted as I implement these features. 

Update: Dr. Raymo kindly pointed me to the work of Barry Saltzman, who pursued the question of nonlinear (chaotic) dynamics in climate models. She provided a couple of citations, and after a quick trip to the Fish/Oceans library at the University of Washington, I have a hardcopy of Dr. Saltzman's 1994 paper (4). 

Dr. Saltzman proposes that for the last five million years, the climate system can be modeled with three slow-response variables: global ice mass, CO2, and ocean temperature. This is an exciting confirmation of my intuition, and I'll blog as I investigate further.

---

* Volcanism and heat diffusing from the molten interior contribute a very small quantity of energy to Earth's surface, around two orders of magnitude less than the sun's energy. This contribution is considered to be negligible.

[1] Plio-Pleistocene Ice Volume, Antarctic Climate, and the Global δ18O Record, Raymo, et al. [2006] Science.

[2] Lisiecki, L. E., and M. E. Raymo (2005), A Pliocene-Pleistocene stack of 57 globally distributed benthic δ18O records, Paleoceanography, 20, PA1003, doi:10.1029/2004PA001071.

[3] Disentangling the dynamic core: a research program for a neurodynamics at the large-scale, Michel Le Van Quyen, Biol. Res. v.36 n.1, Santiago 2003.

[4] Late Pleistocene Climatic Trajectory in the Phase Space of Global Ice, Ocean State, and CO2: Observations and Theory,  Barry Saltzman and Mikhail Verbitsky,

Paleoceanography, 9(6), pp 767–779, 1994.  

Posted by jgalasyn | 1 Comments

WPF Designer: Changes and Fixes in VS2008 SP1 Beta

Here's the definitive list:

List of changes and fixed issues for Visual Studio 2008 Service Pack 1 Beta for Windows Presentation Foundation Designer

New features

  • The Properties window now contains the Events tab. The Events tab lets you create events, assign events, and review events.
  • The Properties window now includes a category sort option and an alphabetical sort option to allow for faster property location.
  • Code changes have been made to the XAML Refactor/Rename definition and to the Go to definition. These changes allow XAML rename operations to occur automatically. Additionally, you can navigate the XAML definition by pressing F12.
  • You can now drag controls or create controls from the toolbox in XAML view or in Design view. You can do this even if you use a split view configuration.
  • Snaplines are now implemented for control margins. This lets the designer control a fixed distance from other controls, from container edges, or from gridlines.
  • Tab controls now support TabItem activation and TabItem design. To do this, click the tab that you want to design.
  • The Expander control now expands conditionally based on what is selected. You can design the contents of the Expander control at design time with affecting the IsExpanded attribute of the runtime.
  • Many stability improvements have been added to Visual Studio 2008 SP1. These include improvements to document loading in the designer and to error reporting. Because of these improvements, you will be able to load more documents in the designer.
Posted by jgalasyn | 0 Comments

Visual Studio 2008 SP1 Beta is posted

Get it here.

Discuss amongst yourselves at the forum.

Don't miss Guy Burstein's guided tour.

Here's the official word:

Visual Studio 2008

  • With Visual Studio 2008, developers and development organizations have the tools that enable them to be more productive, take advantage of all the latest platform advances on Windows, Office and the Web, and collaborate more effectively throughout the software lifecycle.
  • Visual Studio 2008 offers more than 250 new features and improvements to existing features, providing developers of all skills sets – from the hobbyist to the small development shop to enterprise development organizations – the tools they need to build great applications.
  • Microsoft is committed to helping developers be successful and provides community resources, reference material, software, add-ins, and more to guide construction of Software+Services applications, data-driven solutions, and compelling user experiences.
  • Visual Studio 2008 SP1 beta introduces improvements and new functionality in several areas including:
    • Full support for SQL Server 2008.
    • Improved functionality and performance in the WPF designers.
    • Additional components and tools for Visual Basic & Visual C++ including an MFC-based Office 2007 Ribbon and various stability improvements.
    • Richer JavaScript features.
    • Improved Web development and site deployment.
    • Performance improvements for the IDE.
    • Improvements to TFS to respond to customer feedback on version control usability and performance, improved email integration with work item tracking.  In addition, TFS now provides full support for hosting on SQL 2008 and Windows Server 2008.

.NET Framework 3.5

  • With the .NET Framework 3.5 Microsoft is extending the capabilities in the framework with new support for Internet protocols, peer-to-peer communication, device programmability, and data handling. The .NET Framework provides a single, common programming model supporting the broadest set of applications.
  • Microsoft is committed to delivering enhanced capabilities and increased productivity for developers in the .NET Framework 3.5.
  • Expanded and improved offerings in the .NET Framework and tooling support in Visual Studio 2008 gives developers enhanced capabilities to build S+S, SOA and Web 2.0 applications.
  • The .NET Framework 3.5 SP1 beta introduces improvements and new functionality in several areas including:
    • More controls, streamlined setup, improved start-up performance, powerful new graphics features for client development and rich data scaffolding, and improved AJAX support.
    • Introduces the ADO.NET Entity Framework and ADO.NET Data Services, simplifying data access code in applications by providing an extensible, conceptual model for data from any data source and enabling this model to closely reflect business requirements.
Posted by jgalasyn | 0 Comments
Filed under: , ,

Using WriteableBitmap to Display a Procedural Texture

A long time ago, back in the Java days, I wrote some code to simulate a particular kind of autocatalytic chemical reaction. A chaos theory researcher named Vladimir Gontar was doing some interesting work,  adapting cellular automata to more closely resemble real physical systems. He presented a method [1] for modeling a two-stage chemical reaction of the form

A → B → C

What's neat about this reaction is that it's defined to be autocatalytic, meaning that the chemicals accelerate their own formation, or as Wikipedia says, the reaction product is itself the catalyst for the reaction. In the Gontar model, chemical B catalyzes the reaction from chemical B to chemical C.

To account for spatial variation, Gontar distributes each chemical concentration Xa, Xb, and Xc on a 2D grid, with coordinates i and j. Each grid cell is coupled to its neighbors by diffusion, which is modeled with a simple weighting rule. The equations of state at time step n are

Xan(i,j) + Xbn(i,j) + Xcn(i,j) = 1,

Xbn(i,j) / Xan(i,j) = K1 * exp[ -W1 / MXcn-1(i,j) ],  

Xcn(i,j) / Xbn(i,j) = K2 * exp[ -W2 / MXbn-1(i,j) ].   

M is the weighting function that couples cell (i,j) to its neighbors:

MX(i,j) = 1/5 * [ X(i,j) + X(i-1,j) + X(i+1,j) + X( i,j-1) + X(i, j+1)].

Because models such as this account for both the chemical reactions and the transport of chemicals through the solution by diffusion, they are called reaction-diffusion systems. Chemical systems of this kind are known to be responsible for important biological functions, such as pigmentation patterns in animal skin [2] and microtubule formation in the cellular skeleton [3].

 

fish stripes and rd

Dynamic pattern change in fish and reaction-diffusion simulation. (Kondo, 2002.)

 

In 1991, when Gontar ran these equations on his little old PC (a 386, no doubt), he found solutions that were clearly analogous to real-world chemical reactions. In particular, his model successfully demonstrated the spiral wave propagation that is characteristic of the famous Belousov-Zhabotinsky reaction. 

 

gontar spiral waves 

Gontar model of B-Z reaction.

 

 bz3

Actual B-Z reaction. (Tabletop Experiments, August 2007.)

 

I find these nonlinear "chaotic" systems to be endlessly fascinating, so I reproduced Gontar's results by using old skool Java code. When the .NET Framework 1.0 shipped, my very first Windows Forms control was adapted from the original Java implementation. It was a bit disappointing when performance wasn't appreciably better than Java bytecode. I re-wrote the engine by using unsafe code blocks to do array access and copying, but it wasn't much help. For a 400x400 grid, I'd get around 5 frames per second on a decent machine. The presentation layer was CPU bound.

 

rdwf

Windows Forms implementation of the Gontar model. Typical frame times for a 400x400 grid are around 190 milliseconds.

 

But now we have WPF. It was a simple matter to write a new visualization layer on the old engine, and the WriteableBitmap class was just what I needed. Best of all, frame time went down considerably. The WPF implementation is almost three times faster than the WinForms implementation:

 

rdwpf

WPF implementation of the Gontar model. Typical frame times for a 400x400 grid are around 70 milliseconds.

 

The WriteableBitmap class is good for any sort of procedural texture, including fractals, cellular automata, and music visualizers. I'm hoping for even better perf when the new implementation ships with Arrowhead.

Another thing just popped into my head: the state equations generalize to 3D quite naturally. It might be an interesting exercise to build a 3D visualizer. Not sure how I'd approach that, but it's something to think about.

Update: I've posted the code for the WPF visualizer at Code Gallery. Please keep in mind that the ReactionVessel engine was the very first thing I ever wrote in the .NET Framework, so it might have a few warts.

---

[1]V. G. Gontar and A. V. Il'in, "New dynamic model describing spatio-temporal behaviour of chemical reactions," Physica D 52 (1991), pp 528-531.

[2] Kondo, Shigero, "The reaction-diffusion system: a mechanism for autonomous pattern formation in the animal skin," Genes To Cells (2002) 7, 535-541.

[3] James Tabony, Nicolas Glade, Jacques Demongeot, and Cyril Papaseit, "Biological Self-Organization by Way of Microtubule Reaction-Diffusion Processes," Langmuir, 18 (19), 7196 -7207, 2002.

Posted by jgalasyn | 4 Comments
Filed under: ,

Big Announcements at MIX '08

In case you haven't heard, during the MIX ’08 keynote, Ray Ozzie, Scott Guthrie, and Dean Hachamovitch made the coveted "game-changing announcements" on the power of the .NET platform, IE8, and tools to enable delivery of next-gen Web and device experiences. 

We're launching a Silverlight 2 Beta that offers .NET and cross-device support, and we're launching Expression Studio 2 and Internet Explorer 8 Beta. 

Silverlight’s support for .NET will empower you 4 million+ professional .NET developers to deliver .NET-based media and RIA experiences in the same way you develop Windows applications today. Silverlight’s support for Windows Mobile and Nokia (on their S60 devices) will now make it cross-device, in addition to being cross-platform and cross-browser.   

The Beta of Expression Studio 2 includes Expression Web, Expression Blend, Expression Design, Expression Media, and Expression Encoder. This empowers you designers to build rich client applications with WPF and rich media/RIA experiences with Silverlight. 

Details

Here are a few details on product availability to whet the appetite:

  • Silverlight 2 Beta 1 including a non-commercial Go-Live license (http://www.microsoft.com/silverlight/).

  • Silverlight 2 support for .NET and cross-device OS.

  • Microsoft Expression Studio 2 Beta for targeting the latest supported Microsoft platform technologies including Microsoft .NET 3.5 and Silverlight 1.0 (http://www.microsoft.com/expression/).

  • Microsoft Expression Blend 2.5 March 2008 Preview with support for Silverlight 2, Silverlight 1.0 and WPF.

  • Expression Professional Subscription introduced as a premium offering for professional designers that complements the existing MSDN subscriptions for developers.

  • Visual Studio 2008 tooling and IIS 7 Media Pack enhancements for Silverlight 2.

  • Internet Explorer 8 Beta for delivering enhanced user experiences with significantly improved standards-support and developer platform investments that enable it to uniquely deliver on the promise of the world of online services (http://www.microsoft.com/ie/ie8).

Find out more at http://visitmix.com/.

Posted by jgalasyn | 0 Comments

Using the WPF Designer: Guidance for Windows Forms Developers

If you're a WinForms dev, and you'd like to know how to implement your favorite features in WPF, take note: Our new topic, The WPF Designer for Windows Forms Developers, gives you a detailed mapping of WinForms features to WPF Designer features. No more flailing about, trying to figure out how to anchor a control in the WPF Designer!

 

Task in Windows Forms Designer Equivalent in WPF Designer
Absolute layout Use the Canvas class as the root element.
Alphabetic sorting in the Properties window

To find a property, use the Search box in the Properties window.

To browse properties, use IntelliSense in XAML view or in the Code Editor. You can also use the Object Browser.

Anchoring

Use the Grid and the anchor capabilities in Design view to set your anchor targets.

...

More life-saving guidance here.

Posted by jgalasyn | 1 Comments
Filed under: , ,

MSDN Code Gallery Launched

MSDN and the Developer Division Community Connection Team are pleased to announce the launch of the MSDN Code Gallery. Microsoft and community members can use this site to share code samples/snippets, sample applications, and other resources. 

One of the most requested features on MSDN is more code samples. The MSDN Code Gallery is the place to find them.

clip_image001

The MSDN Code Gallery is a great place to put any sample projects you may have to help the developer community.  Here you can create a Wiki-style page to describe your sample and upload supporting documents including screenshots, design documents, or even video files. In addition, you can host conversations about your samples, sample projects or other resources that you have provided to the community. You then place your code file on the releases tab to automatically receive a download count and an MS Public License click through.  

Check it out: http://code.msdn.microsoft.com

Posted by jgalasyn | 2 Comments

Silverlight 1.0 on Microsoft Update and WSUS

Silverlight 1.0 is now available to WSUS administrators for enterprise deployments as well as to Microsoft Update consumers.

IT administrators, you now have the ability to deploy Silverlight across your enterprise using the standard deployment tools you already use. Consumers also have the option of installing Silverlight through the familiar Microsoft Update site. Silverlight 1.0 also will be available from the Microsoft Update Catalog.

Here's the official word:

New product family, Silverlight coming Tuesday 1/22/08

 

 

Posted by jgalasyn | 0 Comments
Filed under: , ,

Silverlight Fire Starter video site at MIX University

We get a lot of requests for training on Silverlight, and now there's a great new option: the Silverlight Fire Starter course content is now available online. Five hours of high-quality training material from MIX University  The content is, of course, hosted using Silverlight. Check it out:

clip_image001

Silverlight Fire Starter

Posted by jgalasyn | 0 Comments
Filed under: ,

Mobiform's VantagePoint WPF Controls released

Mobiform has released v1 of their neat VantagePoint WPF Controls suite. View the Demo, which is a live xbap -- I was running it in Firefox this morning!

 

Mobiform's Variable Gauge control 

Posted by jgalasyn | 2 Comments
Filed under:

WPF Designer docs are posted

The MSDN library online has been refreshed, and you can find all the new documentation for the WPF Designer for Visual Studio (formerly known as "Cider") here. You might want to start with the overview topic, or if you want to start autoring your own custom design time, try the extensibility portal topic.

Here's some random artwork from the docs to give you a taste.

 

Design view features in the WPF Designer

Design View Features

 

 

XAML view features in the WPF Designer

XAML View Features

Posted by jgalasyn | 2 Comments
Filed under: ,

Troubleshooting WPF Designer load failures

Now that people have been kicking the tires of the WPF Designer for Visual Studio 2008 (aka "Cider"), we're starting to see a lot of questions about why perfectly good WPF code doesn't load in the designer.  Here's a preview of the topic that will ship in the docs. Hopefully this will help out before frustration and despair set in.

Update: This topic is now posted at MSDN.

---

Windows Presentation Foundation Designer Extensibility for Visual Studio

Troubleshooting WPF Designer Load Failures

The Windows Presentation Foundation (WPF) Designer for Visual Studio includes a sophisticated and extensible visual designer that renders XAML. If your XAML file does not load in the designer, there are several things that you can do to try to understand what is going wrong. This topic describes some tips and techniques to help you troubleshoot WPF Designer load failures.

Note: Many of the techniques in this topic also apply to Expression Blend.

Troubleshooting Steps

The following steps can help you troubleshoot WPF Designer load failures.

  1. Read any exception messages you receive. This may seem obvious, but if you get an exception, clearly read the message. In some cases, it can help you quickly diagnose the problem. For more information see "Debugging and Interpreting Errors in the WPF Designer".
  2. Determine if the problem is in your implementation. Build and run your application to determine whether the problem is the result of your implementation only, or an interaction with the WPF Designer. If the application builds and runs, the design-time error is likely caused by your implementation.
  3. Use the Visual Studio debugger to step into your code at design time. For more information, see "Walkthrough: Debugging WPF Custom Controls at Design Time".
  4. Determine if the problem is a loading error. If Design view fails to load because of an exception, the problem is likely a loading error. If you have custom code that is loaded at design time, and you experience exceptions or load failures at design time, see the Writing Code for Design Time section in this topic. If you are working with resources and they do not appear to be loading, see the UserControl and Custom Control Resources at Design Time section in this topic.
  5. Review your code that is loaded at design time. There are two approaches to writing code that also runs at design time. The first approach is to write defensive code by checking the input parameters to classes. The second approach is to check whether design mode is active by calling the GetIsInDesignMode method. For more information, see the Writing Code for Design Time section in this topic.
  6. Review other areas of your code. Review the Programming Tips section of this topic for some programming tips when you work with the WPF Designer. Review the Programming Best Practicess section of this topic for techniques on how to write more robust code.
  7. If you still have problems, you can use the WPF Designer forum on MSDN to connect with other developers who are using the WPF Designer. To report potential issues or provide suggestions, use the Visual Studio and .NET Framework Feedback site.

Writing Code for Design Time

Ensure that your code runs at design time, as well as run time. If your code runs at design time, do not assume that Application.Current is your application. For example, when you are using Expression Blend, Current is Expression Blend. At design time, MainWindow is not your application's main window. Typical operations that cause a custom control to fail at design time include the following.

  • Casting Current to your custom subclass of Application.
  • Casting MainWindow to your custom subclass of Window.
  • Using the FindResource or FindName method on Current or MainWindow.
  • Referencing resources from Application.Resources. The design-time instance of Application is not the same as your application and does not have the same resources.
  • Not checking whether Application.Current or Application.MainWindow has returned a value that is null. If Visual Studio does not create an application object, then Application.Current may return null.
  • Not checking whether Assembly.GetEntryAssembly has returned a value that is null. For Visual Studio, this method returns null.

There are two approaches to writing code for design time. The first approach is to write defensive code by checking the input parameters to classes, such as value converters. The second approach is to check whether design mode is active by calling the GetIsInDesignMode method.

Checking input parameters for some implementations is necessary because the design environment provides different types for some inputs than those provided by the runtime environment.

Style selectors and value converters usually require one of these approaches to run correctly at design time.

Value Converters
Your custom IValueConverter implementations should check for null and for the expected type in the first parameter of the Convert method. The following XAML shows a binding to Application.Current that fails at design time if the value converter is not implemented correctly.

<ComboBox.IsEnabled>
    <MultiBinding Converter="{StaticResource specialFeaturesConverter}">
        <Binding Path="CurrentUser.Rating" Source="{x:Static Application.Current}"/>
        <Binding Path="CurrentUser.MemberSince" Source="{x:Static Application.Current}"/>
    </MultiBinding>
</ComboBox.IsEnabled>

The binding raises an exception at design time because Application.Current refers to the designer application instead of your application. To prevent the exception, the value converter must check its input parameters or check for design mode.

The following code example shows how to check input parameters in a value converter that returns true if two input parameters satisfy particular business logic.

public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    // Check the values array for correct parameters.
    // Designers may send null or unexpected values.
    if (values == null || values.Length < 2) return false;
    if (!(values[0] is int)) return false;
    if (!(values[1] is DateTime)) return false;

    int rating = (int)values[0];
    DateTime date = (DateTime)values[1];

    // If the user has a good rating (10+) and has been a member for
    // more than a year, special features are available.
    if((rating >= 10) &&
    (date.Date < (DateTime.Now.Date - new TimeSpan(365, 0, 0, 0))))
    {
        return true;
    }
    return false;
}

The second approach to writing code for design time is to check whether design mode is active. The following code example shows a design-mode check instead of the parameter check shown previously.

public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    // Check for design mode.
    if ((bool)(DesignerProperties.IsInDesignModeProperty.GetMetadata(typeof(DependencyObject)).DefaultValue))
    {
        return false;
    }

    int rating = (int)values[0];
    DateTime date = (DateTime)values[1];

    // If the user has a good rating (10+) and has been a member for
    // more than a year, special features are available.
    if((rating >= 10) &&
(dat.Date < (DateTime.Now.Date - new TimeSpan(365, 0, 0, 0))))
    {
        return true;
    }
    return false;
}

Style Selectors
Your custom style selectors also must be implemented to run in design mode. The following XAML shows a custom template selector that uses Application.MainWindow at run time to determine which resource is returned as a DataTemplate. At design time, this resource may not be available, so the SelectTemplate override returns null at design time.

<local:TaskListDataTemplateSelector x:Key="myDataTemplateSelector"/>
<ListBox Width="400" Margin="10"
         ItemsSource="{Binding Source={StaticResource myTodoList}}"
         ItemTemplateSelector="{StaticResource myDataTemplateSelector}"
         HorizontalContentAlignment="Stretch"
         IsSynchronizedWithCurrentItem="True"/>

The following code shows the implementation of the style selector.

public class TaskListDataTemplateSelector : DataTemplateSelector
{
    public override DataTemplate SelectTemplate(
object item,
DependencyObject container)
    {
        if (item != null && item is Task)
        {
            Task taskitem = item as Task;
            Window window = Application.Current.MainWindow;

            // To run in design mode, either test for the correct window class
            // or test for design mode.
            if (window.GetType() == typeof(Window1))
            // Or check for design mode:
            //if (!DesignerProperties.GetIsInDesignMode(window))
            {
                if (taskitem.Priority == 1)
                    return window.FindResource("importantTaskTemplate") as DataTemplate;
                else
                    return window.FindResource("myTaskTemplate") as DataTemplate;
            }
        }


        return null;
    }
}

UserControl and Custom Control Resources at Design Time
By default, UserControl and custom control resources that are available at run time may not be available at design time. When you add your custom controls and user controls to a Page or Window on the design surface, an instance of the control is created. Resources in App.xaml are not available to UserControl and custom control instances loaded on a page or window.

To make your resources available at design time, factor them into a separate resource dictionary and include the dictionary in App.xaml and your control's XAML. Change all StaticResource references to DynamicResource references. The following code example shows how to share a resource dictionary so that its resources are available at design time.

UserControl1.xaml

<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Dictionary1.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
</UserControl.Resources>

App.xaml

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Dictionary1.xaml" />
            </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

Pack URI Syntax
You should not use application-relative resource references. The following code example shows the application-based syntax, which may fail at design time.

<Image Name="image1" Source="pack://application:,,,/Image1.bmp" />

Such references are relative to the application instead of the DLL. Using an application-relative resource reference in a DLL makes the DLL dependent on resources in the parent application. This approach is fragile and not guaranteed to work at design time.

Instead of using application-relative resource references, add resources to the DLL itself and use component-based resource references. For more information, see "Pack URIs in Windows Presentation Foundation".

The following code examples show the component-based syntax, which is the recommended approach.

<Image Name="image1" Source="/TestHostApp;component/Image1.bmp" />
<Image Name="image1" Source="pack://application:,,,/TestHostApp;component/Image1

Programming Tips
The following are some programming tips when you work with the WPF Designer.

  • If you want your custom control to load in the WPF Designer, you must provide CLR get and set methods for any dependency properties that you have defined. For more information, see Custom Dependency Properties.
  • Adorners of type ComboBox are not supported.
  • To use a third-party Windows Forms control, create a UserControl type which has an instance of the vendor control in its Controls collection. For more information, see Walkthrough: Hosting a Third-Party Windows Forms Control in a WPF Application.
  • Design-time for the FlowDocument is not supported directly. If you want to use the WPF Designer on an embedded FlowDocument, first place the FlowDocument in a Frame control, which you can then use in the WPF Designer.

Programming Best Practices
The following are some programming best practices on how to write more robust code for the WPF Designer.

  • Always wrap editing scopes in using statements or try/finally blocks. If an exception is raised, the change is aborted in the Dispose call. For more information, see ModelEditingScope.
  • Use a ModelEditingScope to move a control from one container to another. Failure to do this raises an exception.
  • In WPF and the WPF Designer, do not set a property value to its default if your intent is to clear it. For NaN values, such as Height, call the ClearValue method instead of assigning NaN.
  • When retrieving values from a property, use the computed value of the property. This means you should use the ComputedValue property instead of the GetCurrentValue method of ModelItem. The GetCurrentValue method returns bindings and other expressions if they were stored in the XAML, so you can get cast exceptions in some cases.
Posted by jgalasyn | 4 Comments
Filed under: , ,
More Posts Next page »
 
Page view tracker