It is the responsibility of the view to determine the structure and appearance of what the user sees on the screen. Ideally, the code-behind (background code) of a view contains only the constructor that calls the InitializeComponent method. In some cases, code-behind may contain UI logic code that implements visual behavior that is difficult or inefficient to express in XAML, such as complex animations, or when the code must directly control visual elements that are part of the view. It is not acceptable to put logic code that needs to be tested in a view. Typically, logic code in a code-behind view can be tested through UI automation.
In Silverlight and WPF, data binding expressions in a view are evaluated against its data context. In MVVM, the view model is set as the view’s data context. The view model implements properties and commands to which the view can be bound and notifies the view of any state changes through change notification events. There is usually a direct relationship between a view and its view model.
Typically, views are inherited from the Control or UserControl classes. However, in some cases, a view can be represented by a data template that defines the UI elements that will be used to visually represent the object. Using data templates, a developer can easily specify how a view model will be represented, or can change its default visual representation without changing the underlying object or its behavior directly.
To summarize, a view has the following key characteristics:
- A view is a visual element such as a window, page, custom control, or data template. A view defines the controls, their layout and style;
- A view references the view model through its DataContext property. Controls in a view are bound to the properties and commands of the view model;
- A view can customize the data binding behavior between the view and the view model. For example, the view can use value converters to format the data to be shown in the UI, or use validation rules to provide additional validation of user input;
- The view defines and handles the visual behavior of the UI, such as animations or transitions, which may be triggered by changes in the state of the view model or through user interaction with the UI;
- A code-behind view can define UI logic to implement visual behavior that is difficult to express in XAML, or that requires direct references to specific UI controls defined in the view.