Jack @ ASP.NET

As a software engineer, I focus on .NET, especially asp.net, C#, WCF and so on, and I am also very interested in Search Engine Optimization.

Entries Tagged ‘WPF’

Routed Events in WPF

When you are first getting started with WPF, you will likely use routed events without even knowing you are using them. For example, if you add a button to your window in the Visual Studio® designer and name it myButton and then double-click on it, the Click event will get hooked up in your XAML markup and an event handler for the Click event will be added to the codebehind of your Window class. This should feel no different than hooking up events in Windows Forms and ASP.NET. It is actually a little closer to the coding model for ASP.NET but more like the runtime model of Windows Forms.

Routed events normally appear as pair. The first is a tunneling event called PreviewMouseDown and the second is the bubbling called MouseDown. They don’t stop routing if the reach an event handler. To stop routing then you have to set e.Handled = true;

  • Tunneling The event is raised on the root element and navigates down to the visual tree until it reaches the source element or until the tunneling is stopped by marking the event as handeld. By naming convention it is called Preview... and appears before corresponding bubbling event.
  • Bubbling The event is raised on the source element and navigates up to the visual tree until it reaches the root element or until the bubbling is stopped by marking the event as handled. The bubbling event is raised after the tunneling event.
  • Direct The event is raised on the source element and must be handled on the source element itself. This behavior is the same as normal .NET events.

You can think about routed events either from a functional or implementation perspective. Both definitions are presented here, because some people find one or the other definition more useful.

Functional definition: A routed event is a type of event that can invoke handlers on multiple listeners in an element tree, rather than just on the object that raised the event.

Implementation definition: A routed event is a CLR event that is backed by an instance of the RoutedEvent class and is processed by the Windows Presentation Foundation (WPF) event system.

A typical WPF application contains many elements. Whether created in code or declared in XAML, these elements exist in an element tree relationship to each other. The event route can travel in one of two directions depending on the event definition, but generally the route travels from the source element and then "bubbles" upward through the element tree until it reaches the element tree root (typically a page or a window). This bubbling concept might be familiar to you if you have worked with the DHTML object model previously.

A code snippet

   1: <StackPanel Orientation="Horizontal" Button.Click="ButtonCLickHandler">

   2:   <Button Name="btnYes" Width="Auto" >Yes</Button>

   3:   <Button Name="btnNo" Width="Auto" >No</Button>

   4:   <Button Name="btnCancel" Width="Auto" >Cancel</Button>

   5: </StackPanel>

As an application developer, you do not always need to know or care that the event you are handling is implemented as a routed event. Routed events have special behavior, but that behavior is largely invisible if you are handling an event on the element where it is raised.

Where routed events become powerful is if you use any of the suggested scenarios: defining common handlers at a common root, compositing your own control, or defining your own custom control class.

Routed event listeners and routed event sources do not need to share a common event in their hierarchy. Any UIElement or ContentElement can be an event listener for any routed event. Therefore, you can use the full set of routed events available throughout the working API set as a conceptual "interface" whereby disparate elements in the application can exchange event information. This "interface" concept for routed events is particularly applicable for input events.

Routed events can also be used to communicate through the element tree, because the event data for the event is perpetuated to each element in the route. One element could change something in the event data, and that change would be available to the next element in the route.

Other than the routing aspect, there are two other reasons that any given WPF event might be implemented as a routed event instead of a standard CLR event. If you are implementing your own events, you might also consider these principles:

    Certain WPF styling and templating features such as EventSetter and EventTrigger require the referenced event to be a routed event. This is the event identifier scenario mentioned earlier.

    Routed events support a class handling mechanism whereby the class can specify static methods that have the opportunity to handle routed events before any registered instance handlers can access them. This is very useful in control design, because your class can enforce event-driven class behaviors that cannot be accidentally suppressed by handling an event on an instance.

Each of the above considerations is discussed in a separate section of this topic.

MVVM in WPF

Key characteristics of VIEW
? The view is a visual element, such as a window, page, user control, or data template. The view defines the controls contained in the view and their visual layout and styling.
? The view references the view model through its DataContext property. The controls in the view are data bound to the properties and commands exposed by the view model.
? The view may customize the data binding behavior between the view and the view model. For example, the view may use value converters to format the data to be displayed in the UI, or it may use validation rules to provide additional input data validation to the user.
? The view defines and handles UI visual behavior, such as animations or transitions that may be triggered from a state change in the view model or via the user’s interaction with the UI.
? The view’s code-behind may define UI logic to implement visual behavior that is difficult to express in XAML or that requires direct references to the specific UI controls defined in the view.

Key characteristics of’ ‘VIEWMODEL’
? The view model is a non-visual class and does not derive from any WPF or Silverlight base class. It encapsulates the presentation logic required to support a use case or user task in the application. The view model is testable independently of the view and the model.
? The view model typically does not directly reference the view. It implements properties and commands to which the view can data bind. It notifies the view of any state changes via change notification events via the INotifyPropertyChanged and INotifyCollectionChanged interfaces.
? The view model coordinates the view’s interaction with the model. It may convert or manipulate data so that it can be easily consumed by the view and may implement additional properties that may not be present on the model. It may also implement data validation via the IDataErrorInfo or INotifyDataErrorInfo interfaces.
? The view model may define logical states that the view can represent visually to the user.

Key characteristics of ‘MODEL’
? Model classes are non-visual classes that encapsulate the application’s data and business logic. They are responsible for managing the application’s data and for ensuring its consistency and validity by encapsulating the required business rules and data validation logic.
? The model classes do not directly reference the view or view model classes and have no dependency on how they are implemented.
? The model classes typically provide property and collection change notification events through the INotifyPropertyChanged and INotifyCollectionChanged interfaces. This allows them to be easily data bound in the view. Model classes that represent collections of objects typically derive from the ObservableCollection<T> class.
? The model classes typically provide data validation and error reporting through either the IDataErrorInfo or INotifyDataErrorInfo interfaces.
? The model classes are typically used in conjunction with a service or repository that encapsulates data access and caching.

Overview of Windows Presentation Foundation

WPF is a set of .NET Framework classes that you can use to build attractive and functional UIs for Windows-based client applications.

WPF uses the DirectX graphics engine to provide sophisticated graphics and efficient rendering.

WPF enables you to develop applications by using both declarative markup and managed code.

Typically, you use XAML to implement the appearance of your application and you use a .NET Framework managed programming language, such as C#, to implement behavior.

This separation of appearance from behavior offers many advantages when you build graphical applications.

For example, designers can work on the appearance of an application at the same time as developers independently work on the code-behind functionality.

You can use WPF to create stand-alone applications and applications that are hosted in a Web browser.

When you create stand-alone applications, you use the Window class and you use menu bars, toolbars, and dialog boxes as the building blocks of your application.

When you create browser-hosted applications, you use the Page class as your foundation and you provide hyperlinks to enable users to navigate between the pages in your application.

In both cases, you can use the Application class to share session data, properties, and resources across your application.

WPF includes many other features that enhance the experience of the developer and the end user.

For example, the WPF layout system makes it easy for you to develop controls and layouts that adapt to differing window sizes and display settings.

This is an essential part of the modern user experience.

The WPF data-binding system makes it easy for you to implement two-way data binding between controls and data sources.

Finally, the graphics system includes support for highly sophisticated two-dimensional graphics, three-dimensional graphics, and animations that you can use to create genuinely engaging applications.

Server vs. Client AJAX

It’s important to understand the difference between server-centric “AJAX” and client “pure” AJAX.

In server-centric AJAX applications, even though the application leverages asynchronous calls between client and server, the server is the one that is actually responsible for generating the necessary HTML content before providing it to the client. This leads to heavy bandwidth usage, and lack of responsiveness. In addition, the client application becomes far too reliant on the functionality of the server, and its ability to provide good markup, as opposed to simply requiring data and simple interaction.

In client AJAX applications, the communication with the server is purely for passing data back and forth. All of the rendering and state is maintained within the client environment, and the server is only brought into the picture as needed.

So, “The server should only be concerned with data, not presentation”.

In order to enable our ability to easily create dynamic UI and place the rendering process on the client, we need a way to define templates of markup that represent the UI we wish to create, and allow the runtime to instantiate them for us. This alleviates the need to write a bunch of DOM code or depend on server-rendering.

If you’ve used WebForms before, you’re already familiar with the approach many of its server controls take. You have access to a set of properties that allow you to define arbitrary templates of content, complete with HTML, server controls, and data binding expressions. This model makes it very easy to create dynamic UI that is rendered server-side [Advance Animation].

ASP.NET AJAX 4.0 introduces the ability to define templates as well, but purely client-side. Now you can create the HTML markup you want to use for representing your template, complete with HTML and data binding expressions. In this example, we’ve created an unordered list template whose content is a list item whose content is the value of the Name property of the JSON object that is bound to it. The data binding expression resembles that of WPF.