You have created a view-model for your ToolBar control, and you have a collection of commands exposed by the view-model as a property (Commands). Now you want to bind your ToolBar.ItemsSource with that property, so you have something like this:
<ToolBar ItemsSource="{Binding Commands}" Height="64" />
Of course, you want to have each command as a button, so you’ve created a DataTemplate:
<DataTemplate DataType="{x:Type local:CommandModel}">
<Button Command="{Binding Command}">
<StackPanel>
<Image Source="{Binding Icon}" Width="32" Height="32" />
<TextBlock Text="{Binding Title}" VerticalAlignment="Center" />
</StackPanel>
</Button>
</DataTemplate>
Gluing all together you end up like this:
Now you’re asking yourself, why does the toolbar buttons looks totally different comparing to toolbar without binding?
The answer to this question, like other weirdo things in WPF, hidden inside the control’s code.
Looking with Reflector at ToolBar.PrepareContainerForItemOverride, you find this:
What happens here is that the toolbar picks a well known style-key based on the element type (the container) and not the item type (our CommandModel). For example, if the item added to the toolbar is of type Button, the toolbar picks the ButtonStyleKey, and set the button default-style-key with that key. This is how a button added directly to the toolbar gets a special style.
Using data binding, we are not adding Buttons… we are actually adding CommandModel instances, so the toolbar ignores it, ‘name’ stays null and nothings special is really happens, so our DataTemplate’s button stays with its normal style.
To overcome this issue, we simply set our button style explicitly with the ToolBar’s ready-made button style like this:
<DataTemplate DataType="{x:Type local:CommandModel}">
<Button Command="{Binding Command}"
Style="{DynamicResource ResourceKey={x:Static ToolBar.ButtonStyleKey}}">
<StackPanel>
<Image Source="{Binding Icon}" Width="32" Height="32" />
<TextBlock Text="{Binding Title}" VerticalAlignment="Center" />
</StackPanel>
</Button>
</DataTemplate>
That's it, now our data-bound toolbar works as expected.
Download the code from here.
Abstract
In these post series, I’ll demonstrate how to develop LOB applications for the Windows Phone 7. This series will provide an easy start for iPhone, Android and .NET Programmers.
Introduction
Windows Phone is almost here, and it’s a great timing to learn how to develop applications which target the Windows Phone 7 device.
From my point of view, there are at least three reasons for doing so:
1. Microsoft introduces a market place, so it’s a good opportunity for making easy money :)
2. Develop LOB Applications for Windows Phone, which is part of my job.
3. Just for Fun!
Where to Start
If you’re a .NET Programmer, you’ve already made half of the way. All you have to do is to learn Silverlight and/or XNA for gaming.
If you’re an iPhone programmer and you know Cocoa Touch and Objective C, you’ve to learn: Silverlight, C# and/or XNA for gaming.
If you’re an Android programmer and you know Java or C++, you’ve to learn: Silverlight, C# and/or XNA for gaming.
Whatever kind of programmer you’re, both C# and Silverlight are easy to learn. Just for clarification, C# is a programming language (comparing to Objective C, C++ and Java), where Silverlight is the framework for developing UI and client logic (comparing to Cocoa Touch and Java).
Windows Phone SDK
Before we start, we have to install the free Windows Phone Developer Tools Beta from here.
The Windows Phone Developer Tools Beta includes the following
- Visual Studio 2010 Express for Windows Phone Beta (Development Environment such as Xcode and Eclipse)
- Windows Phone Emulator Beta (Emulator if you don’t have a real device)
- Silverlight for Windows Phone Beta (UI and client logic framework)
- Microsoft Expression Blend for Windows Phone Beta (Great UI design environment)
- XNA Game Studio 4.0 Beta (Platform for game programming)
Note that Visual Studio 2010 Express won’t be installed if you already have Visual Studio 2010.
Windows Phone SDK
After installing the development environment, you can easily create a new Windows Phone project from both Visual Studio and Blend for Windows Phone. So feel free to launch Visual Studio or Blend for Windows Phone from the start menu, then click File –> New Project.
Both Visual Studio and Blend offer three kind of project templates. For the simplicity I’ve chosen the “Windows Phone Application” project template.
Now let’s look at the results. In both Visual Studio and Blend we can find two .xaml files, two .png files and one .jpg file.
The image files are application icon, background and splash screen. Feel free to change them to whatever you like. But just for the beginning, keep the files name and type.
The App.xaml file is a special XML file, represents part of the application class. If you expand it, you’ll see another App.xaml.cs file which is another part of the same application class written in C#. The App.xaml is usually used to add UI resources. Let’s look at the content inside.
As you can see, this XAML file defines the App class located inside FirstApp namespace (like package in Java, but logically).
An interesting part of this XAML file defines a PhoneApplicationService which provides access to various aspects of the application’s lifetime. This includes management of the application’s idle behavior and management of the application’s state when it becomes active or inactive. For example When UserIdleDetectionMode is set to enabled, the operating system will consider an application to be idle when no touch events are detected. When ApplicationIdleDetectionMode is set to enabled, the operating system will pause the active application when the lock screen is engaged.
Looking at the App.xaml.cs file we can find the second part of the App class (there is a third part which is automatically generated by a build tool).

In this part of the App class you can find an empty implementation of all the PhoneApplicationService event handlers (registered from XAML: Launching, Closing, Activated, Deactivated). These event handlers are left empty so you can place your relevant code over there.
Other parts of the implementation are:
* Unhandled exception handling – If Visual Studio debugger is attached to the running application (for example, hitting F5 to run this application) it will break whenever an unhandled exception is cough.
* InitializeComponent – calling this method, loads the BAML (XAML “compiled” content) from the assembly resources.
* InitializePhoneApplication – This method contains the following code:

The main part of the code above is creating a PhoneApplicationFrame which hosts the MainPage.xaml. Setting PhoneApplicationFrame as the root-frame doesn’t renders it until placing it as the root-visual element. This allows the splash screen to remain active until the application is ready to render.
Designing the Main Page
Now let’s look at the MainPage.xaml. Opening it with Blend or the Visual Studio 2010 WP7 Designer, you can see how the main page looks like and design it as well.
Let’s change the “MY APPLICATION” title to “My First WP7 App”, and “page name” to “Hello World!”. To do that, select the “MY APPLICATION” text-block and change its Text property. Repeat these steps for the second text-block.
Now let’s add a several images to this page. To do that, go to the Projects tab in blend, and add an existing image to the project. Now just drag the image file you’ve added to the page. Blend will create an Image object automatically.
Testing the Application
Since currently I don’t have a Windows Phone device, I’ll use the WP7 emulator which arrives with the WP7 SDK.
Hitting F5 from both Visual Studio and Blend will automatically launch the WP7 emulator, then the application we’ve just created.
To exit or stop debugging, you may click the back button, click on the home button or stop the debugging session from Visual Studio. Don’t exit the emulator, just leave it open for next use.
Enjoy your Windows Phone 7 Programming and stay tuned for more.
Thank you for participating my WPF 4 and Blend 3 session at Microsoft, Ranana, Jan-21.
You can download the presentation and demo files from SkyDrive.
Thanks to all of you who participated in my WPF Smart Client session today at Sela. Hope that you enjoyed the session.
As I promised, here is a link to the presentation and demo application written in the class: SkyDrive.
Tomorrow, as part of the SDP conference, I’m having a whole day session dedicated to WPF 4 and LOB applications.
What’s in there for you:
- Short intro to WPF
- Goodies in WPF 4
- Building a Smart Client using WPF 4
- Developing Composite Applications using Prism 2
In addition to all of this great stuff, Bnaya Eshet, my colleague at Sela will talk about MEF and how it’s related to WPF and LOB application.
I’ll be more than happy to see you there.
To all the lucky guys (like me :-) attended to the Microsoft PDC 09 conference last week, and won an acer touch tablet PC, here is how you can use the built-in 3G modem (yes it has such) to connect the Internet using your local cellular vendor.
First, make sure that you have a data package. Now do as follows:
- Turn off your machine, and remove the battery
- Insert your USIM+ card to the sim slot (you may hear the click sound while pushing)
- Connect the battery and turn on your machine
- While logged in to Windows 7 turn on the 3G modem by switching the 3G button located in the front of the laptop panel (push it left)
- Click on the Windows 7 network tray icon and connect
- A dialog may appear, asking for access point. You may call your cellular vendor, asking for details.
- If you’re connected to Orange Israel, just place: uinternet in the access point (no user, no pass)
- Surf the Internet.
In this great session, Glenn Block and my collegue Ariel Ben Horesh have talked about Managed Extensibility Framework for Silverlight 4 for building customizable applications that can easily be extended by third parties. Whether you are building an extensible data grid, a custom rules engine, a pluggable editor, or a composite application such as a pluggable CRM system, you want to learn about MEF. They explained how to use MEF to decouple applications into more maintainable the application into dynamically deployable chunks that download on-demand.
The managed extensibility framework (MEF) is a new library in .NET 4.0 and Silverlight 4 for building applications that can be extensible.
MEF takes parts and tier them together, like LEGO, based on the configuration of the user. The concept is that your application is built up from parts.
The basics, core concept to work with MEF are:
Export it
You can create a part and export it so it could be discovered and import to compose the application.
Import it
I need something, so you can import single or many parts.
Compose it
Now that you’ve got all of the parts, compose them together to compose an application.
For example, you have a dash board built of widgets. You can create widgets and export them. Just decorate the widget with the Export attribute. The widget itself can Import other parts. The dash board now can import one or many exports. In the Silverlight main page you should call PartInitializers.SatisfyImports() to satisfy all imports. This is it. Now MEF will automatically load and compose all parts.
Metadata
Provides meta information for exports, for example where the widget should be located by default, on the top are at the bottom.
To define metadata you should define types an and interface which defines the metadata, then export it using ExportMetadata and acquire it while import. While import you should work with the Lazy<P, M> instead of directly importing the par
Custom Attributes
In MEF, instead of using the out-of-the-box attributes (Import, Export) you can create your own. For example WidgetAttribute. In such case you should create an attribute and derive it from the MEF ExportAttribute.
Recomposing
In MEF there is an option for re-composition, meaning that MEF can be notified while new parts are added at run time. To turn this on you should set the Import.AllowRecomposition to true. Now if you download packages at runtime, MEF will be notified and compose the new parts.
In this session we saw the inside scoop on how Windows Presentation Foundation (WPF) powers all its rich services – like layout, databinding, and animation. There is a lot of heavy lifting done for you under the hood; in this session, we crack open these system components, including the trees (visual, logical, and inheritance), the property system and its change notification, and a few of the routing systems that all messages go through. Bring your hard-hat for this one!
WPF Involves lots of interacting concepts
-
Layout, Animation, Styles, Templates, Binding and Events
Windows constructore calling InitializeComponents, but layout and template expanding and other binding related are differed. We can’t assume that layout worked in the ctor.
Where are properties set?
Animated Value, Local Value, Setter in style trigger, Setter in style, Inherited value
Property values are often sought rather than set!
Set may destroy binding. SetCurrentValue instead of SetValue will do the job.
Binding in general
-
DataContext is inherited – Data template instances given explicit context
-
Some properties bound two-way by default
-
CollectionView – implicitly created when binding to a collection. Tracks “current” item
-
Binding expressions now work with .NET dynamic type
Inheritance
The logical tree is the containment part of the tree.
-
Templates expanded lazily during layout
-
Inherited properties trace inheritance context
-
Freezable subtypes have a special inheritance context
-
In WPF 4.0, InputBinding is now freezable – can take advantages of the inherited context
Dispatcher serializes everything
We can break long tasks into Bite-Sized Pieces.
-
Use Dispatcher.BeingInvoke, process work in priority order
-
Priority can be changed after scheduling
-
DispatcherTimer schedules work as inactive, uses Win32 time to update
Use threads:
-
WPF Render Thread – WPF internals only
-
UI Thread(s) – UI Construction, Event listeners, Layout, Binding etc.
-
Worker Thread Pool – 100% User Code
Long-running and blocking operations belong to worker threads. Avoid DispatcherObject in non-UI threads.
You can use BackgroundWorker to save the threading pain.
Visuals and framework elements do a lot of work. Avoid premature optimization. You can use Snoop with memory and profiling tools to investigate observable issues. Consider OnRender()
Before cutting down the number of visuals in the visual tree, try to figure out where the real problem is. WPF can handle thousands of visuals per second.
Virtualizing Visual Trees
If you replace the items panel in an ItemsControl, try to use the VirtualizationStackPanel instead of StackPanel, it performance much better. DataGrid in WPF 4.0 support VirtualizationPanel.
In this session, John Papa talked about Silverlight application development patterns such as composite applications with Prism, developing using the Model-View-ViewModel (MVVM) pattern, and methods of implementing large, modular, multi-page applications within your team. Also he talked about frameworks created to help assist in rapid development using these patterns without sacrificing good application development patterns.
MVVM is a pattern, there is no specific way to do it right. Also with Silverlight.
MVVM, MVC, MVP and MV??? are all commonly accepted patterns for maintainable, scalable and testable applications. People look for patterns to describe common way for programming UI.
MVVM is a separation of concerns. Provides loosely coupled UI from logic, good for testing.
Model
The model represents the data, it only a data entity. Not required to know where it gets its data from. Easy to test and to maintain.
ViewModel
Main source of logic for the MVVM triad. It connects the Model to the View. It abstracts the View and provide public properties to be bond with the view. This separation is great for unit testing.
MVVM Variations
View First – ViewModel is declared as Static Resource in the View’s XAML. Works well in Expression Blend. Another way is to create ViewModel in the View’s code-behind.
ViewModel First – view is injected into the ViewModel’s constructor. For example, ViewModel is created first then view is bound with the ViewModel.
View and ViewModel using Intermediary
An intermediary creates both the view and view model, then connect them together.
Prism 2
Prism is set of options, you can use what you want and ignore the rest. In the MVVM case you can just use the module catalog but ignore the Event Aggregator.
The rest of the session was what is prism and how to use it. So I’ll save you the pain.
In this nice session David Poll has talked about enhancements to data binding and data validation as well as new support for rich text & printing in the platform that allow you to build compelling LOB user experiences.
Everyday we work with data so we usually deal with Interactivity, Entry and Presentation
In this talk he explained about features added to SL 4
-
SL4 in Visual Studio 2010
-
Data Binding enhancements
-
Data related controls enhancements
-
Input validation
-
Printing a document
David shown an Issue Tracker application as a case study. The application connects to a DB, gets the data from and visualizes it.
Master View Binding
To display a data grid in VS 2010 you can drag-drop a table directly to a canvas. VS 2010 will create a bound data grid automatically. Then you can select the data grid and set its properties using the property grid. You can group items using CollectionViewSource. It now supports grouping!
Details View Binding
Now you can display a details view for item selected inside the grid. Create a simple user control with all the fields then set the master details. VS 2010 provides binding UI provides option to bind to the bound Data Grid selected item. Now both views are synchronized.
Foreign Key Relationship
Using the VS 2010 data binding you can bound an item by support foreign key relationship. You can bind the SelectedValue to the foreign key. Also you can select a string format.
Dictionary Binding
Binding a dictionary is also possible, just bind the element to the string index of the dictionary key.
Command Binding
Continue with the demo, David showed that SL4 supports ICommand. Selecting a button you can bind it via Command property to any command implementing the ICommand, and the command implementation could be implemented by the View Model using MVVM.
INotifyDataError Interface
SL4 is now supporting the INotifyDataError interface for error validation on the data model. So you should only implement the INotifyDataError interface in the model object and that’s it (BindingBase.ValidatesOnNotifyDataErrors is set to true by default so you don’t need to specify it). Also you can add a data validation asynchronously (for example calling a services for validation async, then get the result).
Printing a Page
To print a page using SL4 you should create a PrintDocument instance, initialize it, set properties, events and call Print. You can use any control to render the content for printing. Just create a user control, create an instance of it within the start printing event handler, and set the instance as the PageVisual property of the start printing event argument.
Silverlight 4 added a lot of more interesting features not listed in this session. You may check Alex’s blog for a deeper overview of the new features in SL4.
In this very intersting session, Stan Pennington talked about how Windows 7 adds support in native code for accelerating media transcoding and specific playback experiences through the new asynchronous Media Foundation transform (MFT) model. How to write and use accelerated MFTs, and how to license for preference in Windows Media Player and portable device operations with Windows Shell. He showed a managed sample using the transcoding API, and showed how the new Device Proxy simplifies AVStream driver based video capture in Media Foundation. Talked about in-box support for high-definition UVC webcams and the new extensibility model, along with how the new native Source Reader object allows easy capture integration into existing applications. Finally, demonstrates new tools for developing and debugging in Media Foundation.
MF Provides Hardware Codecs and Async support, HD Webcams support.MF Focused on unmanaged API – coding, transcoding must be really time, buffering, good response to flashing and other. Writing unmanaged you’ll have twice as faster comparing to managed, the GC is non-deterministic.
MF could expose configuration, control and status through managed APIs.
There are four media infrastructures Microsoft deals with:
- Video for Windows – ACM Codecs
- DShow – DVD, TV )Filter, DMO, ACM, VCM)
- Direct Show – WM True Streaming (DMO, ACM Codecs)
- WM FSDK – Key mainstream scenarios & nre features (MFT Codecs)
Media Foundation is the area Microsoft is investigating these days for media.
Typycal Microsoft usage in Windows 7
- MF – Playback for non streaming ASF, MP3, MPEG-4 and selected AVI permutations of digital still cameras
- New metadata handling in Shell Property Handlers
- Transcoding and new media sharing
- DShow – DVD, TV, MPEG-2, MPEG-1, custom I/O, video editing
- FSDK – Best compatibility for ASF true streaming
- Historic integration of ASF read, write.
Microsoft uses the whole three main infrastructure to get best end use experience. Windows media center uses WMP OCX with custom presenter.Window 7 change protected media path (PMP) in WMP and OCX.
Windows Vista PMP used for MF even with unprotected content, providing seamless cross-fade in mixed DRM/non-DRM playlists. Windows 7 PMP only used for DRM-protected content in MF.
Why should we use MF?
- Stream objects (IStream) for media input, output
- Most connectivity and data flow divorced from streaming components, moved to higher layer
- No push-pull component issues
- Better potential for dynamic changes
- Better control of threading
- More constrained components roles and graphs topologies
- Hardware Codecs – transcoding only or general for transcoding and playback
To have WM, you should install Windows 7 SDK.
In this great WPF performance session, Bart De Smet and Eric Harding have talked about WPF performance and demonstrates some of the performance tools the WPF team uses.
One of the important things to do regards performance is to start measure early. Perceived performance, make it feel fast, turn it to an art and not a science. There would be trade offs – CPU versus memory, etc.
Memory
New WPF application called FishBowl has been announced. It’s a small application dealing with facebook as a case study.
To profile memory do:
Cold Start
To profile cold start do:
- Prevent unnecessary DLLs from being loaded
- Set xperf to run at startup – this shows how much CPU by process also disk IO
- Use .NET memory profiler again to know what object was loaded
Warm Start
To profile warm start do:
- Run the application
- Use WPF Perf Visual Profiler, and attach to application to analyze the visual tree (how many elements loaded)
- Use CPU profile such in Visual Studio Profiler to look for the hot path with higher CPU time
Runtime
To profile runtime do:
- Use WPF Perf Visual Profiler to see were CPU spend its time
- Use perforator to see rendering performance
- High IRTs (GPU) may effect frame rate – effects, clips, opacity and opacity mask
- Element count may increase IRTs – input and routed events
- In .NET 4.0 here is a Cache Composition trading video memory with CPU

Runtime Best Practice
- Don’t block UI thread
- Use UI Virtualization and Data Virtualization when possible
- Freeze your freezables – no change notification callbacks
- Hardware vs Software
- RDP, virtual machines, old hardware
- RenderCapability.Tier
- Reduce frame rate, 3D rendering

This is it for this session. In a future post I’ll describe this process in more details.
Paul Harrington talked about the new WPF UI of Visual Studio 2010, the start page and many other designers, displaying the Visual Studio 2010 WPF visual tree using Snoop.
Architectural reason is one of the reasons Visual Studio 2010 has been reprogrammed to use WPF 4.0. Separated presentation and support for long range road map.
He also explained that VS 2010 features really need it: Editors, Architect designer editor, Parallel tools, Workflow designer and more
Another reason is to make it easy to develop new features in VS 2010.
Here are several features added to VS2010 for WPF:
-
Declarative UI using XAML
-
Data binding managed and native data models
-
Styling Templates
-
Application resources
-
Interop with Win32
-
Integration with the message loop
-
New text stack based on DirectWrite
After explaining why using WPF in VS2010 he talked about the how.
-
Defining the data models
-
Replacing the VS main window with WPF (creating window without displaying it)
-
Write new components: Command Bar, hidden behind switches off by default
-
Scouting with selected teams
-
Lot of testing
-
Leaving old presentation for regression testing
-
Removing old code
He mentioned that testing conversion costs, and the main reason was that there are no HWNDs in WPF!
Testing of the new VS 2010 yields unify test frameworks based on UI Automation, and best practices. One of the important one was test at data layer, means Separated Presentation is important!
The challenges the VS 2010 team were:
-
Mixed mode application – native and managed code, WPF and HWNDs
-
Allow new extensions to take advantage of WPF (creating plug-ins for VS using pure WPF)
-
Text clarity since WPF blends colors in small text becomes blurry
-
Performance – Beta 2 is lot more better than Beta 1, and there is lot more work to do. This is the key issue for next
Challenges of Mixed-Mode
-
Managed code binding to native models
-
Interop in the presentation layer (especially in focus mechanism)
-
Text and image clarity stack: TextOptions.TextFormattingMode removes the blur from text
Performance Issues
-
Switching tab – it is highly recommended to keep the load operation atomic as possible. Make sure that the visual tree you switch to would be fully ready before switch
-
Memory usage using tools such as VMMap (look at image load), SOS.dll, !dumpheap-stat
-
Windows performance analyzer (xperf)
-
Hardware vs software rendering (Virtual Machines and Remote Desktop) – Gradient fill is more expensive in remote desktop, using solid brushes instead
-
Scrolling in the editor
Who were involved:
Core team of about 12 people, 7 developers and 5 testers, the WPF Team and the Expression Suite Team
The cloud computing, Windows Azure, System Center and server tools for Windows and more platforms Azure tools for Java and Eclipse are the main topics that Ray Ozzie has mentioned. You can get more details from Noam’s and Alex's blog, he is a great writer :-)
Ray also announced Dallas CTP for discovery, exploring and using data in a new way.
In the bottom line azure is much more mature than the last year, and there are many new tools for hosting applications in the cloud.
Waiting for more information about Windows Phone and Silverlight next.
We are here, 20 people from Sela Group, wearing blue, waiting for the PDC 09 keynote to begin. The hall is full of people, and there are many other entering, seeking a seat.
Comparing to PDC 08, there are less people, and its of course due to the economic situation, but the decoration here in the hall is awesome, and we’ve already got 3D glasses… I’m too curious to know why.
Ozzie is here… please excuse me, I’ve got something to do here… :-)
More Posts
Next page »