Sequential Workflows

download Sequential Workflows

of 208

Transcript of Sequential Workflows

  • 7/27/2019 Sequential Workflows

    1/208

    Events Overview for Silverlight

    Send Feedbackon this topic to Microsoft.View this topiconlinein your default browser.

    This topic describes the programming concept of events, and how the event concept works in

    Silverlight and its programming models. Silverlight events are essentially the same event concept

    as defined by the common language runtime (CLR) and the .NET Framework. Similar to WPF,you can assign handlers for events as part of the declarations for UI elements in XAML, or you

    can use language-specific syntax to add the handlers in code. Silverlight supports the concept of

    routed events, which is a feature whereby certain input events and data events can be handled by

    objects other than the object that raised the event. Routed events are useful when compositingcontrol templates or when centralizing the event logic of an application page.

    This topic contains the following sections.

    Events as a Programming Concept Button.Click: An Introduction to Using Silverlight Events Defining an Event Handler The sender Parameter and Event Data Adding Event Handlers in Managed Code Routed Events Input Event Handlers in Controls User-Initiated Events Programming Model Alternatives Removing Event Handlers Commanding What's Next Related Topics

    Events as a Programming Concept

    An event is a message sent by an object to signal the occurrence of an action. The action couldbe caused by user interaction, such as a mouse click, or it could be triggered by the internal logicof a class. The object that raises the event is called the event sender. The object that captures the

    event and responds to it is called the event receiver. Basically the purpose of events is tocommunicate time-specific, relatively lightweight information from an object at run time, and

    potentially to deliver that information to other objects in the application.

    mailto:[email protected]?subject=MSDN%5e*cc189018%5e*VS%5e*95%5e*EN-US&body=Visual%20Studio%20feedback%20policy%3a%20http%3a%2f%2fmsdn.microsoft.com%2fEN-US%2flibrary%2fee264131(VS.110).aspxmailto:[email protected]?subject=MSDN%5e*cc189018%5e*VS%5e*95%5e*EN-US&body=Visual%20Studio%20feedback%20policy%3a%20http%3a%2f%2fmsdn.microsoft.com%2fEN-US%2flibrary%2fee264131(VS.110).aspxhttp://msdn.microsoft.com/EN-US/library/cc189018(v=VS.95,d=hv.2).aspxhttp://msdn.microsoft.com/EN-US/library/cc189018(v=VS.95,d=hv.2).aspxhttp://msdn.microsoft.com/EN-US/library/cc189018(v=VS.95,d=hv.2).aspxhttp://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://msdn.microsoft.com/EN-US/library/cc189018(v=VS.95,d=hv.2).aspxmailto:[email protected]?subject=MSDN%5e*cc189018%5e*VS%5e*95%5e*EN-US&body=Visual%20Studio%20feedback%20policy%3a%20http%3a%2f%2fmsdn.microsoft.com%2fEN-US%2flibrary%2fee264131(VS.110).aspx
  • 7/27/2019 Sequential Workflows

    2/208

    Silverlight Events

    Generally speaking, Silverlight events are CLR events, and therefore are events that you canhandle with managed code. If you know how to work with basic CLR events already, you have a

    head start on some of the concepts involved. But you do not necessarily need to know that much

    about the CLR event model in order to perform some basic tasks, such as attaching handlers. (Ifyou want some more conceptual background, see Events, Delegates, and CLR Event System

    Conventions.)

    Because the UI for a typical Silverlight-based application is defined in markup (XAML), some

    of the principles of connecting UI events from markup elements to a runtime code entity aresimilar to other Web technologies, such as ASP.NET, or working with an HTML DOM. In

    Silverlight and WPF, the code that provides the runtime logic for a XAML-defined UI is often

    referred to as code-behind or the code-behind file. In the Visual Studio solution views, this

    relationship is shown graphically, with the code-behind file being a dependent and nested fileversus the XAML page it refers to.

    In addition to the CLR events that act within its own runtime object model, Silverlight also has afew events that can invoke script-based handlers on the plug-in instance itself and at the HTML

    level, such as OnError. These events are exposed and can be handled by any script working

    against the plug-in instance in the HTML DOM. As a general event model for an application,HTML scripting should have first chance to do the handling, and if you handle events in an

    HTML, these events should not be passed on to the managed API.

    Note:

    Because Silverlight often operates within the plug-in architecture of the hosting browser, theinput stimulus for input events is initially handled by the browser host. The input information is

    then sent to the Silverlight plug-in through that browser's API for general plug-in support, and

    you can handle the corresponding events defined in the Silverlight API. Most other non-input

    events in Silverlight do not necessarily have such browser implications.

    Button.Click: An Introduction to Using Silverlight Events

    Because Silverlight is a UI technology, one of the most common tasks you have is to capture

    user input to the UI. For example, your UI might have a button that the user must click to submitinformation or change your application's state.

    Generally, you define the UI for your Silverlight-based application by generating XAML. This

    XAML can be the output from a designer such as Microsoft Expression Blend or from a designsurface in a larger IDE such as Silverlight Designer for Visual Studio. The XAML can also be

    written out in a plaintext editor or a third-party XAML editor. As part of generating that XAML,

    http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/
  • 7/27/2019 Sequential Workflows

    3/208

    you can wire event handlers for individual UI elements at the same time that you define all the

    other attributes that describe that UI element.

    Event wiring in XAML involves specifying the string-form name of the handler method that you

    define in your code-behind. For example, the following XAML defines a Button object with

    some important properties assigned as attributes and wires a handler for the button's Clickevent:

    Copy to Clipboard

    The actual handler is written in one of the programming languages that are supported by the

    .NET Framework for Silverlight, such as Visual Basic or C#. With the attribute

    Click="showUpdatesButton_Click", you have created a contract that when the XAML ismarkup-compiled and parsed, both the XAML markup compile step in your development

    environment's build action and the eventual Silverlight runtime that parses the XAML can find a

    method named showUpdatesButton_Click. Moreover, showUpdatesButton_Click must be amethod that implements a compatible method signature (based on a delegate) for any handler of

    the Clickevent.

    For example, the following code defines the showUpdatesButton_Click handler.

    JavaScript

    C#

    C++

    F#

    JScript

    VB

    Copy to Clipboard

    privatevoid showUpdatesButton_Click (object sender, RoutedEventArgs e) {Button b = e.OriginalSource as Button;//more logic to do here...

    ...

    }

    If you are using Silverlight Designer for Visual Studio, you can use design features that make it

    very simple to wire event handlers from XAML and then define them in code-behind. Thisincludes providing an automatic naming scheme for the handlers. For more information, see

    Walkthrough: Creating Your First Silverlight Application.

    http://copytoclipboard%28%27id113%27%2C%276%27%29/http://copytoclipboard%28%27id113%27%2C%276%27%29/http://changetab%28%27id122%27%2C%27c/#','2','6')http://changetab%28%27id122%27%2C%27c/#','2','6')http://changetab%28%27id122%27%2C%27visual%20basic%27%2C%276%27%2C%276%27%29/http://changetab%28%27id122%27%2C%27visual%20basic%27%2C%276%27%2C%276%27%29/http://copytoclipboard%28%27id122%27%2C%276%27%29/http://copytoclipboard%28%27id122%27%2C%276%27%29/http://copytoclipboard%28%27id122%27%2C%276%27%29/http://changetab%28%27id122%27%2C%27visual%20basic%27%2C%276%27%2C%276%27%29/http://changetab%28%27id122%27%2C%27c/#','2','6')http://copytoclipboard%28%27id113%27%2C%276%27%29/
  • 7/27/2019 Sequential Workflows

    4/208

    You can also use the .NET Framework Class Library for Silverlight documentation to look up a

    specific event and determine its delegate. The handler you write must be compatible with that

    delegate signature. For the previously shown example, the best matching delegate isRoutedEventHandler.

    Note:

    Silverlight event-handler functions cannot be called with parameter values (even empty ones),

    which is a notable difference from event handler syntax in the HTML DOM. The attribute valuein XAML references the handler name only, and other mechanisms, such as the expected input

    parameters of your handler, pass the information.

    Defining an Event Handler

    For objects that are UI and declared in XAML, event handler code must be defined in the partialclass that serves as the code-behind for a XAML page. For more information about how partialclasses and code-behind for XAML work together, see Code-Behind and Partial Classes.

    Event handlers in the partial class are written as methods, based on the CLR delegates that are

    used by that particular event. Your event handler methods can be public, or they can have a

    private access level. Private access works because the handler and instance created by the

    XAML are ultimately joined by code generation. The general recommendation is to not makeyour event handler methods public in the class.

    The sender Parameter and Event Data

    Any handler you write for a managed Silverlight event can access two values that are availableas input for each case where your handler is invoked. The first such value is sender, which is a

    reference to the object where the handler is attached. The sender parameter is typed as the base

    Object type. A common technique in Silverlight and WPF event handling is to cast sender to a

    more precise type. This technique is useful if you expect to check or change state on the senderobject itself. Based on your own application design, you expect a type that is safe to cast sender

    to, based on where the handler is attached or other design specifics.

    The second value is event data, which generally appears in signatures as the e parameter. Per the

    CLR event model, all events send some kind of event data, with that data captured as an instance

    of a class that inherits EventArgs (or is EventArgs itself). You can discover which properties forevent data are available by looking at the e parameter of the delegate that is assigned for the

    specific event you are handling, and then using Intellisense in Visual Studio or the .NET

    Framework Class Library for Silverlight. Some Silverlight events use the EventHandler

  • 7/27/2019 Sequential Workflows

    5/208

    TEventArgs> delegate or other generic handler types. An example is ColumnReordered. In most

    cases, the event definitions constrains the generic with a specific EventArgs derived event data

    class. You should then write the handler method as if it took that EventArgs derived event dataclass directly as the second parameter.

    For some events, the event data in the EventArgs derived class is as important as knowing thatthe event was raised. This is especially true of the input events. For mouse events, the position of

    the mouse when the event occurred might be important. For keyboard events, key presses on the

    keyboard raise the same KeyUp and KeyDown events. In order to determine which key waspressed, you must access the KeyEventArgs that is available to the event handler.

    For more information about handling input events, see Mouse Support and Keyboard Support.Input events and input scenarios often have additional considerations that are not covered in this

    topic, such as mouse capture for mouse events, and modifier keys and platform key codes for

    keyboard events.

    Adding Event Handlers in Managed Code

    XAML is not the only way to assign an event handler to an object. To add event handlers to anygiven object in managed code, including to objects that are not even usable in XAML, you can

    use the CLR language-specific syntax for adding event handlers.

    In C#, the syntax is to use the += operator. You instantiate the handler by declaring a new

    delegate that uses the event handler method name.

    If you are using code to add event handlers to objects that appear in the run-time UI, a common

    practice for Silverlight is to add such handlers in response to an object lifetime event orcallback, such as Loaded orOnApplyTemplate, so that the event handlers on the relevant object

    are ready for user-initiated events at run time. The following example illustrates first the XAML

    outline to give some idea of the structure and then provides the C# language syntax.

    JavaScript

    C#

    C++

    F#

    JScript

    VB

    Copy to Clipboard

    http://void%280%29/http://void%280%29/http://changetab%28%27id199%27%2C%27c/#','2','6')http://changetab%28%27id199%27%2C%27c/#','2','6')http://copytoclipboard%28%27id199%27%2C%276%27%29/http://copytoclipboard%28%27id199%27%2C%276%27%29/http://void%280%29/http://copytoclipboard%28%27id199%27%2C%276%27%29/http://changetab%28%27id199%27%2C%27c/#','2','6')http://void%280%29/
  • 7/27/2019 Sequential Workflows

    6/208

    void LayoutRoot_Loaded(object sender, RoutedEventArgs e){

    textBlock1.MouseEnter += new MouseEventHandler(textBlocks_MouseEnter);textBlock1.MouseLeave += new MouseEventHandler(textBlocks_MouseLeave);

    }

    XAML

    Copy to Clipboard

    Put the mouse over this text

    ...

    There are two possibilities for Visual Basic syntax. One is to parallel the C# syntax and attach

    handlers directly to instances. This requires the AddHandler keyword and also the AddressOfoperator that dereferences the handler method name.

    JavaScript

    C#

    C++

    F#

    JScript

    VB

    Copy to Clipboard

    PrivateSub LayoutRoot_Loaded(ByVal sender As Object, ByVal e AsRoutedEventArgs e)

    AddHandler textBlock1.MouseEnter, AddressOf textBlocks_MouseEnterAddHandler textBlock1.MouseLeave, AddressOf textBlocks_MouseLeave

    EndSub

    The other option for Visual Basic syntax is to use the Handles keyword on event handlers. This

    technique is appropriate for cases where handlers are expected to exist on objects at load timeand persist throughout the object lifetime. Using Handles on an object that is defined in XAML

    requires that you provide a Name / x:Name. This name becomes the instance qualifier that isneeded for the Instance.Event part of the Handles syntax. In this case you do not need an object

    lifetime-based event handler to initiate attaching the other event handlers; the Handlesconnections are created when you compile your XAML page.

    JavaScript

    C#

    http://copytoclipboard%28%27id200%27%2C%276%27%29/http://copytoclipboard%28%27id200%27%2C%276%27%29/http://changetab%28%27id206%27%2C%27visual%20basic%27%2C%276%27%2C%276%27%29/http://changetab%28%27id206%27%2C%27visual%20basic%27%2C%276%27%2C%276%27%29/http://copytoclipboard%28%27id206%27%2C%276%27%29/http://copytoclipboard%28%27id206%27%2C%276%27%29/http://copytoclipboard%28%27id206%27%2C%276%27%29/http://changetab%28%27id206%27%2C%27visual%20basic%27%2C%276%27%2C%276%27%29/http://copytoclipboard%28%27id200%27%2C%276%27%29/
  • 7/27/2019 Sequential Workflows

    7/208

    C++

    F#

    JScript

    VB

    Copy to Clipboard

    Sub textBlock1_MouseEnter(ByVal sender As Object, ByVal e As MouseEventArgs)Handles textBlock1.MouseEnter'....EndSubSub textBlock1_MouseLeave(ByVal sender As Object, ByVal e As MouseEventArgs)Handles textBlock1.MouseLeave'....EndSub

    Note:

    Visual Studio and its XAML design surface generally promote the instance-handling technique

    instead of the Handles keyword. This is because establishing the event handler wiring in XAMLis part of typical designer-developer workflow for Silverlight and WPF, and the Handles

    keyword technique is incompatible with wiring the event handlers in XAML.

    Routed Events

    Silverlight supports the concept of a routed event for several input events that are defined in baseclasses and are present on most UI elements that support user interaction and input. The

    following is a list of input events that are routed events:

    KeyDown KeyUp GotFocus LostFocus MouseLeftButtonDown MouseLeftButtonUp

    MouseRightButtonDown MouseRightButtonUp MouseMove MouseWheel BindingValidationError DragEnter DragLeave DragOver

    http://changetab%28%27id221%27%2C%27visual%20basic%27%2C%276%27%2C%276%27%29/http://changetab%28%27id221%27%2C%27visual%20basic%27%2C%276%27%2C%276%27%29/http://copytoclipboard%28%27id221%27%2C%276%27%29/http://copytoclipboard%28%27id221%27%2C%276%27%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://copytoclipboard%28%27id221%27%2C%276%27%29/http://changetab%28%27id221%27%2C%27visual%20basic%27%2C%276%27%2C%276%27%29/
  • 7/27/2019 Sequential Workflows

    8/208

    DropA routed event is an event that is potentially passed on (routed) from a child object to each of itssuccessive parent objects in the object tree. The object tree in question is approximated by the

    XAML structure of your UI, with the root of that tree being the root element in XAML. The true

    object tree might vary somewhat from the XAML because the object tree does not includeXAML language features such as property element tags. In general you can think of the routed

    events as "bubbling" from XAML object element children that raise the event, toward the parent

    object element that contains them. The event occurrence and its event data continue and arereported to objects along the event route until the root element is reached. (If you have used

    certain Web technologies such as DHTML, the "bubbling" concept might already be familiar to

    you.)

    Note:

    WPF supports an analogous "tunneling" routing strategy, whereby the root of a page / object treehas the first chance to handle a routed event, and the event then "tunnels" down the object tree

    toward its event source. Silverlight does not use "tunneling" routed events. Events in Silverlight

    either follow the "bubbling" routing strategy (and are referred to as routed events) or do not routeat all. There are also other API-level differences in routed event behavior between Silverlight

    and WPF.

    The OriginalSource Property of RoutedEventArgs

    When an event bubbles up an event route, sender is no longer the same object as the event-raising object. Instead, sender is the object where the handler that is being invoked is attached. In

    many cases, sender is not the object of interest, and you are instead interested in knowing

    information such as which of the possible child objects the mouse is over, or which object heldfocus when a keyboard key was pressed. For these cases, the value of the OriginalSourceproperty is the object of interest.

    At all points on the route, OriginalSource reports the original object that raised the event, instead

    of where the handler is attached. For an example scenario where this is useful, consider an

    application where you want certain key combinations to be "hot keys" or accelerators, regardless

    of which control currently holds keyboard focus and initiated the event. In terms of the objecttree, the focused object might be nested within some items list in a list box, or could be one of

    hundreds of objects in the overall UI. Having to attach handlers to every possible focusable

    object in an application to detect your accelerator is obviously impractical. But because the

    keyboard events are bubbling routed events, the event eventually reaches the root object in itsroute. Therefore, you can often attach a single KeyDown handler on the root object and rely on

    the behavior that a KeyDown event eventually bubbles to the root object. Then the handler can

    determine whether that key is the valid combination for an intended accelerator action, orwhether no action is necessary.

  • 7/27/2019 Sequential Workflows

    9/208

    The Handled Property

    Several event data classes for specific routed events contain a property named Handled. Forexamples, see MouseButtonEventArgs. Handled, KeyEventArgs. Handled,

    MouseWheelEventArgs. Handled, DragEventArgs. Handled, and ValidationError EventArgs.Handled.Handled is a settable Boolean property.

    Setting the Handled property to true influences the event system in Silverlight. When you set thevalue to true in event data, the routing stops for most event handlers; the event does not continue

    along the route to notify other attached handlers of that particular event case. What "handled" as

    an action means in the context of the event and how your application responds is up to you.

    However, you should keep in mind the behavior of the Silverlight event system if you setHandled in your event handlers.

    Not all of the routed events are cancellable in this way. GotFocus, LostFocus, and MouseMove

    will always route all the way to the root, and their event data classes do not have a Handledproperty that can influence that behavior. Therefore, checking OriginalSource values for those

    events is often a good idea, to make sure you are not handling an event and making incorrectassumptions about what the event means and here the input event originated in the UI layout.

    Note:

    The concept of a Handled property for routed events also exists in WPF. In WPF, the Handled

    property exists on all routed event-data classes; in Silverlight, only the specific event data classes

    that have their own Handled property can be used to cancel the related event's route.

    Routed Events Outside the Visual Tree

    Certain objects in Silverlight participate in a relationship with the primary visual tree that is

    conceptually like an overlay over the main visuals. These objects are not part of the usual parent-child relationships that connect all tree elements to the visual root. This is the case for any

    displayed Popup orToolTip. If you want to handle routed events from a Popup orToolTip, you

    should place the handlers on specific UI elements that are within the Popup orToolTip and not

    the Popup orToolTip elements themselves. You should not rely on routing inside anycompositing that is performed forPopup orToolTip content. This is because event routing for

    routed events works only along the main visual tree. Popup orToolTip is not considered a parent

    of subsidiary UI elements and never receives the routed event, even if it is trying to use

    something like the Popup default background as the capture area for input events.

    Input Event Handlers in Controls

    http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/
  • 7/27/2019 Sequential Workflows

    10/208

    Specific existing Silverlight controls sometimes use this Handled concept for input eventsinternally. This can give the appearance from user code that an input event never occurs. For

    example, the Button class includes logic that deliberately handles the general input eventMouseLeftButtonDown. It does so because the class raises a Clickevent that is initiated by that

    mouse input. For purposes of the class design, the raw mouse event is conceptually handled, and

    class consumers should instead choose to handle or not handle Click. Reference topics forspecific control classes in the .NET Framework Library often note the event handling behaviorimplemented by the class. In some cases, the behavior can be changed or appended in subclasses

    by overriding OnEvent methods. For example, you can change how yourTextBox derived class

    reacts to key input by overriding TextBox. OnKeyDown.

    Registering Handlers for Already-Handled Routed Events

    Earlier it was stated that setting Handled to true prevented most handlers from acting. The API

    AddHandlerprovides a technique where you can attach a handler that will always be invoked forthe route, even if some other handler earlier in the route has set Handled to true. This technique

    is useful if a control you are using has handled the event in its internal compositing or forcontrol-specific logic but you still want to respond to it on a control instance, or higher in theroute. However, this technique should be used with caution because it can contradict the purpose

    of Handled and possibly violate a control's intended usage or object model.

    For more information including a usage example, see AddHandler.

    User-Initiated Events

    Silverlight enforces that certain operations are only permitted in the context of a handler thathandles a user-initiated event. The following is a list of such operations:

    Setting IsFullScreen. Showing certain dialogs. This includes SaveFileDialog, OpenFileDialog, and the print

    dialog displayed by PrintDocument. Print.

    Navigating from a HyperlinkButton. Accessing the primary Clipboard API.

    Silverlight user-initiated events include the mouse events (such as MouseLeftButtonDown), and

    the keyboard events (such as KeyDown). Events of controls that are based on such events (suchas Click) are also considered user-initiated.

    API calls that require user initiation should be called as soon as possible in an event handler.This is because the Silverlight user initiation concept also requires that the calls occur within a

    certain time window after the event occurrence. In Silverlight 5, this time window is

    approximately one second.

    http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/
  • 7/27/2019 Sequential Workflows

    11/208

    User-initiated event restrictions also apply to usages of JavaScript API for Silverlight.

    When Silverlight is in full-screen mode, some input events are deliberately limited for securityreasons, although this can be mitigated for out-of-browser applications using elevated trust. For

    more information, see Full-Screen Support.

    Programming Model Alternatives

    This topic specifically discusses Silverlight events and the managed API. But you could also usethe JavaScript API for Silverlight to perform event handling for a XAML page. JavaScript API

    for Silverlight is appropriate for a limited range of scenarios such as splash screens or similar

    XAML-based UI that is visual in character but not especially interactive.

    You declare the event handling model (managed API versus JavaScript API) at the page level byincluding or excluding the x:Class attribute on the root element. If the x:Class attribute exists, the

    page uses the managed API. Including x:Class and using managed API is the default for most if

    not all XAML page templates produced by development tools for Silverlight. To use the

    JavaScript API for event handling, make sure the XAML page does not declare an x:Classattribute.

    For a description of the JavaScript API for event handling, see Handling Silverlight Events by

    Using JavaScript.

    Removing Event Handlers

    In some circumstances, you might want to remove event handlers during the application lifetime.To remove event handlers, you use the CLR-language-specific syntax. In C#, you use the -=

    operator. In Visual Basic, you use the RemoveHandler function. In either case, you reference the

    event handler method name

    The following code shows how to remove an event handler named textBlocks_MouseEnter from

    the target object textBlock1.

    JavaScript

    C#

    C++

    F#

    http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://changetab%28%27id527%27%2C%27c/#','2','6')http://changetab%28%27id527%27%2C%27c/#','2','6')http://void%280%29/http://void%280%29/http://changetab%28%27id527%27%2C%27c/#','2','6')http://void%280%29/http://void%280%29/
  • 7/27/2019 Sequential Workflows

    12/208

    JScript

    VB

    Copy to Clipboard

    void Cleanup(){

    textBlock1.MouseEnter -= textBlocks_MouseEnter;}

    You can also remove handlers for cases where the event was added through a XAML attribute.This is easier to do if you provided aName value for the element where the handler was attached

    because that provides an object reference for code later; however, you could also walk the object

    tree in order to find the necessary object reference if you had to.

    Commanding

    In Silverlight 5, a small number of UI elements support commanding. Commanding uses input-related routed events in its underlying implementation and enables processing of related UI input

    (a certain mouse action, a specific accelerator key) by invoking a single command handler. Ifcommanding is available for a UI element, consider using its commanding APIs instead of any

    discrete input events. For more information, see one of the following:

    ButtonBase. Command

    Hyperlink. Command

    What's Next

    If you are interested in defining your own events for your own controls or other types, seeDefining Events for Custom Silverlight Classes.

    If you want to learn more about Silverlight input events specifically, see Mouse Support or

    Keyboard Support. Other types of input that involve events that were not discussed in this topicinclude ink, multi-touch, and mouse wheel events. See Ink Overview, Touch, orMouse Wheel

    Input.

    If you are interested in learning more about the CLR event system concepts that apply to

    Silverlight, see Events, Delegates, and CLR Event System Conventions.

    http://changetab%28%27id527%27%2C%27visual%20basic%27%2C%276%27%2C%276%27%29/http://changetab%28%27id527%27%2C%27visual%20basic%27%2C%276%27%2C%276%27%29/http://copytoclipboard%28%27id527%27%2C%276%27%29/http://copytoclipboard%28%27id527%27%2C%276%27%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://copytoclipboard%28%27id527%27%2C%276%27%29/http://changetab%28%27id527%27%2C%27visual%20basic%27%2C%276%27%2C%276%27%29/
  • 7/27/2019 Sequential Workflows

    13/208

    See Also

    Walkthrough: Displaying Related Data in a WPF

    Application

    Send Feedbackon this topic to Microsoft. View this topiconlinein your default

    browser.

    In this walkthrough, you will create a WPF application that displays data from database tables that have

    a parent/child relationship. The data is encapsulated in entities in an Entity Data Model. The parent

    entity contains overview information for a set of orders. Each property of this entity is bound to a

    different control in the application. The child entity contains details for each order. This set of data is

    bound to a DataGrid control.

    This walkthrough illustrates the following tasks:

    Creating a WPF application and an Entity Data Model that is generated from data in theAdventureWorksLT sample database.

    Creating a set of data-bound controls that display overview information for a set of orders. Youcreate the controls by dragging a parent entity from the Data Sources window to the WPF

    Designer.

    Creating a DataGrid control that displays related details for each selected order. You create thecontrols by dragging a child entity from the Data Sources window to a window in the WPF

    designer.

    Note

    Your computer might show different names or locations for some of the Visual Studio user

    interface elements in the following instructions. The Visual Studio edition that you have and the

    settings that you use determine these elements. For more information, see Visual Studio

    Settings.

    Prerequisites

    You need the following components to complete this walkthrough:

    http://void%280%29/http://void%280%29/mailto:[email protected]?subject=MSDN%5e*dd465158%5e*VS%5e*110%5e*EN-US&body=Visual%20Studio%20feedback%20policy%3a%20http%3a%2f%2fmsdn.microsoft.com%2fEN-US%2flibrary%2fee264131(VS.110).aspxmailto:[email protected]?subject=MSDN%5e*dd465158%5e*VS%5e*110%5e*EN-US&body=Visual%20Studio%20feedback%20policy%3a%20http%3a%2f%2fmsdn.microsoft.com%2fEN-US%2flibrary%2fee264131(VS.110).aspxhttp://msdn.microsoft.com/EN-US/library/dd465158(v=VS.110,d=hv.2).aspxhttp://msdn.microsoft.com/EN-US/library/dd465158(v=VS.110,d=hv.2).aspxhttp://msdn.microsoft.com/EN-US/library/dd465158(v=VS.110,d=hv.2).aspxhttp://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://msdn.microsoft.com/EN-US/library/dd465158(v=VS.110,d=hv.2).aspxmailto:[email protected]?subject=MSDN%5e*dd465158%5e*VS%5e*110%5e*EN-US&body=Visual%20Studio%20feedback%20policy%3a%20http%3a%2f%2fmsdn.microsoft.com%2fEN-US%2flibrary%2fee264131(VS.110).aspxhttp://void%280%29/
  • 7/27/2019 Sequential Workflows

    14/208

    Visual Studio. Access to a running instance of SQL Server or SQL Server Express that has the

    AdventureWorksLT sample database attached to it. You can download the AdventureWorksLT

    database from the CodePlex Web site.

    Prior knowledge of the following concepts is also helpful, but not required to complete the walkthrough:

    Entity Data Models and the ADO.NET Entity Framework. For more information, see Introducingthe Entity Framework.

    Working with the WPF Designer. For more information, see WPF and Silverlight DesignerOverview.

    WPF data binding. For more information, see Data Binding Overview.

    Creating the Project

    Create a new WPF project to display the order records.

    To create a new WPF project

    1. Start Visual Studio.2. On the File menu, point to New, and then click Project.3. Expand Visual C# or Visual Basic, and then select Windows.4. Make sure that .NET Framework 4 is selected in the combo box at the top of the dialog box. The

    DataGrid control that you use in this walkthrough is available only in the .NET Framework 4.

    5. Select the WPF Application project template.6. In the Name box, type AdventureWorksOrdersViewer.7. Click OK.

    Visual Studio creates the AdventureWorksOrdersViewer project.

    Creating an Entity Data Model for the Application

    http://go.microsoft.com/fwlink/?linkid=87843http://go.microsoft.com/fwlink/?linkid=87843http://go.microsoft.com/fwlink/?linkid=87843http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://go.microsoft.com/fwlink/?linkid=87843
  • 7/27/2019 Sequential Workflows

    15/208

    Before you can create data-bound controls, you must define a data model for your application and add

    it to the Data Sources window. In this walkthrough, the data model is an Entity Data Model.

    To create an Entity Data Model

    1. On the Data menu, click Add New Data Source to open the Data Source Configuration Wizard.2. On the Choose a Data Source Type page, click Database, and then click Next.3. On the Choose a Database Model page, click Entity Data Model, and then click Next.4. On the Choose Model Contents page, click Generate from database, and then click Next.5. On the Choose Your Data Connection page, do one of the following:

    o If a data connection to the AdventureWorksLT sample database is available in the drop-down list, select it.

    -or-

    o Click New Connection and create a connection to the AdventureWorksLT database.Make sure that the Save entity connection settings in App.Config as option is selected, and then click

    Next.

    6. On the Choose Your Database Objects page, expand Tables, and then select the following tables:o SalesOrderDetailo SalesOrderHeader

    7. Click Finish.8. Build the project.

    Creating Data-Bound Controls that Display the Orders

    Create controls that display order records by dragging the SalesOrderHeaders entity from the Data

    Sources window to the WPF designer.

    To create data-bound controls that display the order records

    1. In Solution Explorer, double-click MainWindow.xaml.The window opens in the WPF designer.

    http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/
  • 7/27/2019 Sequential Workflows

    16/208

    2. Edit the XAML so the Height and Width properties are set to 8003. In the Data Sources window, click the drop-down menu for the SalesOrderHeaders node and

    select Details.

    4. Expand the SalesOrderHeaders node.5. Click the drop-down menu next to SalesOrderID and select ComboBox.6. For each of the following child nodes of the SalesOrderHeaders node, click the drop-down menu

    next the node and select None:

    o RevisionNumbero OnlineOrderFlago ShipToAddressIDo BillToAddressIDo CreditCardApprovalCodeo SubTotalo TaxAmto Freighto rowguido ModifiedDate

    This action prevents Visual Studio from creating data-bound controls for these nodes in the next step.

    For this walkthrough, it is assumed that the end user does not need to see this data.

    7. From the Data Sources window, drag the SalesOrderHeaders node to the window in the WPFDesigner.

    Visual Studio generates XAML that creates a set of controls that are bound to data in the

    SalesOrderHeaders entity, and code that loads the data. For more information about the generated

    XAML and code, see Binding WPF Controls to Data in Visual Studio.

    8. In the designer, click the combo box next to the Sales Order ID label.9. In the Properties window, select the check box next to the IsReadOnly property.

    Creating a DataGrid that Displays the Order Details

    http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/
  • 7/27/2019 Sequential Workflows

    17/208

    Create a DataGrid control that displays order details by dragging the SalesOrderDetails entity from the

    Data Sources window to the WPF designer.

    To create a DataGrid that displays the order details

    1. In the Data Sources window, locate the SalesOrderDetails node that is a child of theSalesOrderHeaders node.

    Note

    There is also a SalesOrderDetails node that is a peer of the SalesOrderHeaders node. Make sure

    that you select the child node of the SalesOrderHeaders node.

    2. Expand the child SalesOrderDetails node.3. For each of the following child nodes of the SalesOrderDetails node, click the drop-down menu

    next the node and select None:

    o SalesOrderIDo SalesOrderDetailIDo rowguido ModifiedDate

    This action prevents Visual Studio from including this data in the DataGrid control you create in the next

    step. For this walkthrough, it is assumed that the end user does not need to see this data.

    4. From the Data Sources window, drag the child SalesOrderDetails node to the window in theWPF Designer.

    Visual Studio generates XAML to define a new data-bound DataGrid control, and the control appears in

    the designer. Visual Studio also updates the generated GetSalesOrderHeadersQuery method in the

    code-behind file to include the data in the SalesOrderDetails entity.

    Testing the Application

    Build and run the application to verify that it displays the order records.

    To test the application

    http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/
  • 7/27/2019 Sequential Workflows

    18/208

    1. Press F5.The application builds and runs. Verify the following:

    o The Sales Order ID combo box displays 71774. This is the first order ID in the entity.o For each order you select in the Sales Order ID combo box, detailed order information is

    displayed in the DataGrid.

    2. Close the application.

    After completing this walkthrough, learn how to use the Data Sources window in Visual Studio to bind

    WPF controls to other types of data sources. For more information, see Walkthrough: Binding WPF

    Controls to a WCF Data Service and Walkthrough: Binding WPF Controls to a Dataset.

    How to: Display Related Data in WPF Applications

    Send Feedbackon this topic to Microsoft.View this topiconlinein your default browser.

    In some applications, you might want to work with data that comes from multiple tables orentities that are related to each other in a parent-child relationship. For example, you might want

    to display a grid that displays customers from a Customers table. When the user selects a specific

    customer, another grid displays the orders for that customer from a related Orders table.

    You can create data-bound controls that display related data by dragging items from the Data

    Sources window to the WPF Designer.

    To create controls that display related records

    1. On the Data menu, click Show Data Sources to open the Data Sources window.2. Click Add New Data Source and complete the Data Source Configuration Wizard.3. Open the WPF designer, and make sure that the designer contains a container that is a

    valid drop target for the items in the Data Sources window.

    For more information about valid drop targets, see Binding WPF Controls to Data in

    Visual Studio.

    4. In the Data Sources window, expand the node that represents the parent table or object inthe relationship. The parent table or object is on the "one" side of a one-to-many

    relationship.

    mailto:[email protected]?subject=MSDN%5e*dd264862%5e*VS%5e*110%5e*EN-US&body=Visual%20Studio%20feedback%20policy%3a%20http%3a%2f%2fmsdn.microsoft.com%2fEN-US%2flibrary%2fee264131(VS.110).aspxmailto:[email protected]?subject=MSDN%5e*dd264862%5e*VS%5e*110%5e*EN-US&body=Visual%20Studio%20feedback%20policy%3a%20http%3a%2f%2fmsdn.microsoft.com%2fEN-US%2flibrary%2fee264131(VS.110).aspxhttp://msdn.microsoft.com/EN-US/library/dd264862(v=VS.110,d=hv.2).aspxhttp://msdn.microsoft.com/EN-US/library/dd264862(v=VS.110,d=hv.2).aspxhttp://msdn.microsoft.com/EN-US/library/dd264862(v=VS.110,d=hv.2).aspxhttp://msdn.microsoft.com/EN-US/library/dd264862(v=VS.110,d=hv.2).aspxmailto:[email protected]?subject=MSDN%5e*dd264862%5e*VS%5e*110%5e*EN-US&body=Visual%20Studio%20feedback%20policy%3a%20http%3a%2f%2fmsdn.microsoft.com%2fEN-US%2flibrary%2fee264131(VS.110).aspx
  • 7/27/2019 Sequential Workflows

    19/208

    5. Drag the parent node (or any individual items in the parent node) from the Data Sourceswindow onto a valid drop target in the designer.

    Visual Studio generates XAML that creates new data-bound controls for each item that

    you drag. The XAML also adds a new CollectionViewSource for the parent table or

    object to the resources of the drop target. For some data sources, Visual Studio alsogenerates code to load the data into the parent table or object. For more information, see

    Binding WPF Controls to Data in Visual Studio.

    6. In the Data Sources window, locate the related child table or object. Related child tablesand objects appear as expandable nodes at the bottom of the parent node's list of data.

    7. Drag the child node (or any individual items in the child node) from the Data Sourceswindow onto a valid drop target in the designer.

    Visual Studio generates XAML that creates new data-bound controls for each of theitems you drag. The XAML also adds a new CollectionViewSource for the child table or

    object to the resources of the drop target. This new CollectionViewSource is bound to theproperty of the parent table or object that you just dragged to the designer. For some data

    sources, Visual Studio also generates code to load the data into the child table or object.

    The following figure demonstrates the related Orders table of the Customers table in adataset in the Data Sources window.

    See Also

    Tasks

    How to: Bind WPF Controls to Data in Visual Studio

    How to: Create Lookup Tables in WPF Applications

    Walkthrough: Displaying Related Data in a WPF Application

    Concepts

    Binding WPF Controls to Data in Visual Studio

    How to: Bind WPF Controls to Data in Visual Studio

    http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/
  • 7/27/2019 Sequential Workflows

    20/208

    Send Feedbackon this topic to Microsoft.View this topiconlinein your default browser.

    You can create data-bound WPF controls by using the Data Sources window. First, add a data

    source to the Data Sources window. Then, drag items from the Data Sources window to the WPFDesigner.

    Adding a Data Source to the Data Sources Window

    Before you can create data-bound controls, you must first add a data source to the Data Sourceswindow.

    To add a data source to the Data Sources window

    1. On the Data menu, click Show Data Sources to open the Data Sources window.2. Click Add New Data Source and complete the Data Source Configuration Wizard.3. Perform one of the following tasks to create data-bound controls:

    o Creating a control that is bound to a single field of data.o Creating a control that is bound to multiple fields of data.o Creating a set of controls that are bound to multiple fields of data.o Binding data to existing controls in the designer.

    Creating a Control That is Bound to a Single Field of Data

    After you add a data source to the Data Sources window, you can create a new data-boundcontrol that displays a single field of data, such as a ComboBox orTextBox.

    To create a control that is bound to a single field of data

    1. In the Data Sources window, expand an item that represents a table or an object. Locatethe child item that represents the column or property that you want to bind to. For a visual

    example, see Data Sources Window.2. Optionally, select the control to create. Each item in the Data Sources window has a

    default control that is created when you drag the item to the designer. The default controldepends on the underlying data type of the item.

    To choose a different control, click the drop-down arrow next to the item and select acontrol. For more information, see How to: Set the Control to be Created when Dragging

    from the Data Sources Window.

    mailto:[email protected]?subject=MSDN%5e*dd264860%5e*VS%5e*110%5e*EN-US&body=Visual%20Studio%20feedback%20policy%3a%20http%3a%2f%2fmsdn.microsoft.com%2fEN-US%2flibrary%2fee264131(VS.110).aspxmailto:[email protected]?subject=MSDN%5e*dd264860%5e*VS%5e*110%5e*EN-US&body=Visual%20Studio%20feedback%20policy%3a%20http%3a%2f%2fmsdn.microsoft.com%2fEN-US%2flibrary%2fee264131(VS.110).aspxhttp://msdn.microsoft.com/EN-US/library/dd264860(v=VS.110,d=hv.2).aspxhttp://msdn.microsoft.com/EN-US/library/dd264860(v=VS.110,d=hv.2).aspxhttp://msdn.microsoft.com/EN-US/library/dd264860(v=VS.110,d=hv.2).aspxhttp://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://msdn.microsoft.com/EN-US/library/dd264860(v=VS.110,d=hv.2).aspxmailto:[email protected]?subject=MSDN%5e*dd264860%5e*VS%5e*110%5e*EN-US&body=Visual%20Studio%20feedback%20policy%3a%20http%3a%2f%2fmsdn.microsoft.com%2fEN-US%2flibrary%2fee264131(VS.110).aspx
  • 7/27/2019 Sequential Workflows

    21/208

    3. Drag the item to a valid container in the designer, such as a Grid. For more informationabout valid containers, see Binding WPF Controls to Data in Visual Studio.

    Visual Studio creates the new data-bound control and an appropriately titled Label in the

    container. Visual Studio also generates XAML and code to bind the control to the data.

    For more information, see Binding WPF Controls to Data in Visual Studio.

    Creating a Control That is Bound to Multiple Fields of Data

    After you add a data source to the Data Sources window, you can create a new data-boundcontrol that displays multiple fields of data, such as a DataGrid orListView.

    To create a control that is bound to multiple fields of data

    1. In the Data Sources window, select an item that represents a table or object. For a visualexample, see Data Sources Window.

    2. Optionally, select the control to create. By default, each item in the Data Sources windowthat represents a data table or object is set to create a DataGrid (if your project targets

    .NET Framework 4) orListView (for earlier versions of the .NET Framework).

    To select a different control, click the drop-down arrow next to the item and select a

    control. For more information, see How to: Set the Control to be Created when Draggingfrom the Data Sources Window.

    Note

    If you do not want to display a specific column or property, expand the item to display its

    children. Click the drop-down arrow next to the column or property that you do not wantto display, and then click None.

    3. Drag the item to a valid container in the designer, such as a Grid. For more informationabout valid containers, see Binding WPF Controls to Data in Visual Studio.

    Visual Studio creates the new data-bound control in the container. Visual Studio also

    generates XAML and code to bind the control to the data. For more information, seeBinding WPF Controls to Data in Visual Studio.

    Creating a Set of Controls That are Bound to Multiple Fields of Data

    http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/
  • 7/27/2019 Sequential Workflows

    22/208

    After you add a data source to the Data Sources window, you can bind a data table or object to aset of controls. A different control is created for each column or property in the table or object.

    To create a set of controls that are bound to multiple fields of data

    1. In the Data Sources window, select an item that represents a table or object. For a visualexample, see Data Sources Window.2. Click the drop-down arrow next to the item and select Details.

    Note

    If you do not want to display a specific column or property, expand the item to display its

    children. Click the drop-down arrow next to the column or property that you do not want

    to display, and then click None.

    3. Drag the item to a valid container in the designer, such as a Grid. For more informationabout valid containers, see Binding WPF Controls to Data in Visual Studio.

    Visual Studio creates the new data-bound controls in the container. Each control is boundto a different column or property, and each control is accompanied by an appropriately

    titled Label control. Visual Studio also generates XAML and code to bind the controls to

    the data. For more information, see Binding WPF Controls to Data in Visual Studio.

    Binding Data to Existing Controls in the Designer

    After you add a data source to the Data Sources window, you can add a data binding to anexisting control in the desgner.

    To bind data to an existing control in the designer

    1. In the Data Sources window, use one of the following procedures:o To add a data binding to an existing control that displays multiple fields of data,

    such as a DataGrid orListView, select the item that represents the table or objectthat you want to bind to the control.

    o To add a data binding to an existing control that displays a single field of data,such as a ComboBox orTextBox, expand the item that represents the table orobject that contains the data, and then select the item that represents the data that

    you want to bind to the control.

    2. Drag the selected item from the Data Sources window onto an existing control in thedesigner. The control must be a valid drop target. For more information, see Binding

    WPF Controls to Data in Visual Studio.

    http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/
  • 7/27/2019 Sequential Workflows

    23/208

    Visual Studio generates XAML and code to bind the control to the data. For more

    information, see Binding WPF Controls to Data in Visual Studio.

    Note

    If the control is already bound to data, the data binding for the control is reset to the itemthat was dragged onto the control most recently.

    See Also

    Tasks

    Walkthrough: Binding WPF Controls to an Entity Data

    Model

    Send Feedbackon this topic to Microsoft. View this topiconlinein your default

    browser.

    In this walkthrough, you will create a WPF application that contains data-bound controls. The

    controls are bound to customer records that are encapsulated in an Entity Data Model. You willalso add buttons that customers can use to navigate through customer records and save changes

    to records.

    This walkthrough illustrates the following tasks:

    Creating a WPF application and an Entity Data Model that is generated from data in theAdventureWorksLT sample database.

    Creating a set of data-bound controls by dragging an entity from the Data Sourceswindow to a window in the WPF designer.

    Creating buttons that navigate forward and backward through customer records. Creating a button that saves changes in the controls to the Entity Data Model and the

    underlying data source.

    Note

    Your computer might show different names or locations for some of the Visual Studio

    user interface elements in the following instructions. The Visual Studio edition that you

    have and the settings that you use determine these elements. For more information, seeVisual Studio Settings.

    http://void%280%29/http://void%280%29/mailto:[email protected]?subject=MSDN%5e*dd465159%5e*VS%5e*110%5e*EN-US&body=Visual%20Studio%20feedback%20policy%3a%20http%3a%2f%2fmsdn.microsoft.com%2fEN-US%2flibrary%2fee264131(VS.110).aspxmailto:[email protected]?subject=MSDN%5e*dd465159%5e*VS%5e*110%5e*EN-US&body=Visual%20Studio%20feedback%20policy%3a%20http%3a%2f%2fmsdn.microsoft.com%2fEN-US%2flibrary%2fee264131(VS.110).aspxhttp://msdn.microsoft.com/EN-US/library/dd465159(v=VS.110,d=hv.2).aspxhttp://msdn.microsoft.com/EN-US/library/dd465159(v=VS.110,d=hv.2).aspxhttp://msdn.microsoft.com/EN-US/library/dd465159(v=VS.110,d=hv.2).aspxhttp://void%280%29/http://msdn.microsoft.com/EN-US/library/dd465159(v=VS.110,d=hv.2).aspxmailto:[email protected]?subject=MSDN%5e*dd465159%5e*VS%5e*110%5e*EN-US&body=Visual%20Studio%20feedback%20policy%3a%20http%3a%2f%2fmsdn.microsoft.com%2fEN-US%2flibrary%2fee264131(VS.110).aspxhttp://void%280%29/
  • 7/27/2019 Sequential Workflows

    24/208

    Prerequisites

    You need the following components to complete this walkthrough:

    Visual Studio Access to a running instance of SQL Server or SQL Server Express that has the

    AdventureWorksLT sample database attached to it. You can download the

    AdventureWorksLT database from the CodePlex Web site.

    Prior knowledge of the following concepts is also helpful, but not required to complete the

    walkthrough:

    Entity Data Models and the ADO.NET Entity Framework. For more information, seeIntroducing the Entity Framework.

    Working with the WPF designer. For more information, see WPF and SilverlightDesigner Overview.

    WPF data binding. For more information, see Data Binding Overview.

    Creating the Project

    Create a new WPF project to display the customer records.

    To create the project

    1. Start Visual Studio.2. On the File menu, point to New, and then click Project.3. Expand Visual Basic or Visual C#, and then select Windows.4. Select the WPF Application project template.5. In the Name box, type AdventureWorksCustomerEditor and then click OK.

    Visual Studio creates the AdventureWorksCustomerEditor project.

    Creating an Entity Data Model for the Application

    Before you can create data-bound controls, you must define a data model for your applicationand add it to the Data Sources window. In this walkthrough, you create an Entity Data Model.

    http://void%280%29/http://void%280%29/http://go.microsoft.com/fwlink/?linkid=87843http://go.microsoft.com/fwlink/?linkid=87843http://go.microsoft.com/fwlink/?linkid=87843http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://go.microsoft.com/fwlink/?linkid=87843http://void%280%29/
  • 7/27/2019 Sequential Workflows

    25/208

    To create an Entity Data Model

    1. On the Data menu, click Add New Data Source to open the Data Source ConfigurationWizard.

    2. On the Choose a Data Source Type page, click Database, and then click Next.3. On the Choose a Database Model page, click Entity Data Model, and then click Next.4. On the Choose Model Contents page, click Generate from database, and then click Next.5. On the Choose Your Data Connection page, do one of the following:

    o If a data connection to the AdventureWorksLT sample database is available in thedrop-down list, select it.

    -or-

    o Click New Connection and create a connection to the AdventureWorksLTdatabase.

    Make sure that the Save entity connection settings in App.Config as option is selected,and then click Next.

    6. On the Choose Your Database Objects page, expand Tables, and then select the Customertable.

    7. Click Finish.The Model1.edmx file opens in the designer.

    8. Build the project.

    Defining the User Interface of the Window

    Add buttons to the window by modifying the XAML in the WPF Designer.

    To define the user interface of the window

    1. In Solution Explorer, double-click MainWindow.xaml.The window opens in the WPF Designer.

    2. In the XAML view of the designer, add the following code between the tags:Copy to Clipboard

    http://void%280%29/http://void%280%29/http://copytoclipboard%28%27id177%27%2C%276%27%29/http://copytoclipboard%28%27id177%27%2C%276%27%29/http://void%280%29/http://copytoclipboard%28%27id177%27%2C%276%27%29/http://void%280%29/
  • 7/27/2019 Sequential Workflows

    26/208

    Save changes

    3.Build the project.

    Creating Data-Bound Controls

    Create controls that display customer records by dragging objects from the Data Sources windowto the WPF Designer.

    To create data-bound controls

    1. On the Data menu, click Show Data Sources.2. In the Data Sources window, click the drop-down menu for the Customers node and

    select Details.

    3. Expand the Customers node.4. For this example some fields will not be displayed so click the drop-down menu next to

    the following nodes and select None:o NameStyleo PasswordHasho PasswordSalto rowGuido ModifiedDate

    5. From the Data Sources window, drag the Customers node to the area under the buttons.6. In the designer, click the text box next to the Customer ID label.7. In the Properties window, select the check box next to the IsReadOnly property.8. Build the project.

    Navigating Customer Records

    Add code that enables users to scroll through customer records by using the < and > buttons.

    http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/
  • 7/27/2019 Sequential Workflows

    27/208

    To enable users to navigate customer records

    1. In the designer, double-click the < button.Visual Studio opens the code-behind file and creates a new backButton_Click event

    handler for the Clickevent.

    2. Modify the Window_Loaded event handler so the CustomersViewSource andAdventureWorksLTEntities are outside of the method and accessible to the entire form.

    Only declare these global to the form, assign them within the Window_Loaded eventhandler similar to the following:

    JavaScript

    C#

    C++

    F#

    JScript

    VB

    Copy to Clipboard

    private System.Windows.Data.CollectionViewSource customersViewSource;private AdventureWorksCustomerEditor.AdventureWorksLTEntitiesadventureWorksLTEntities;

    privatevoid Window_Loaded(object sender, RoutedEventArgs e){

    adventureWorksLTEntities = newAdventureWorksCustomerEditor.AdventureWorksLTEntities();

    // Load data into Customers. You can modify this code as needed.customersViewSource =

    ((System.Windows.Data.CollectionViewSource)(this.FindResource("customersViewSource")));

    System.Data.Objects.ObjectQuery

    customersQuery = this.GetCustomersQuery(adventureWorksLTEntities);customersViewSource.Source =

    customersQuery.Execute(System.Data.Objects.MergeOption.AppendOnly);}

    3.Add the following code to the backButton_Click event handler:

    http://changetab%28%27id248%27%2C%27c/#','2','6')http://changetab%28%27id248%27%2C%27c/#','2','6')http://changetab%28%27id248%27%2C%27visual%20basic%27%2C%276%27%2C%276%27%29/http://changetab%28%27id248%27%2C%27visual%20basic%27%2C%276%27%2C%276%27%29/http://copytoclipboard%28%27id248%27%2C%276%27%29/http://copytoclipboard%28%27id248%27%2C%276%27%29/http://copytoclipboard%28%27id248%27%2C%276%27%29/http://changetab%28%27id248%27%2C%27visual%20basic%27%2C%276%27%2C%276%27%29/http://changetab%28%27id248%27%2C%27c/#','2','6')
  • 7/27/2019 Sequential Workflows

    28/208

    JavaScript

    C#

    C++

    F#

    JScript

    VB

    Copy to Clipboard

    if (customersViewSource.View.CurrentPosition > 0)customersViewSource.View.MoveCurrentToPrevious();

    4.Return to the designer, and double-click the > button.

    Visual Studio opens the code-behind file and creates a new nextButton_Click event

    handler for the Clickevent.

    5. Add the following code to the nextButton _Click event handler:JavaScript

    C#

    C++

    F#

    JScript

    VB

    Copy to Clipboard

    if (customersViewSource.View.CurrentPosition or < buttons to navigate customer records.

    Saving Changes to Customer Records

    Add code that enables users to save changes to customer records by using the Save changes

    button.

    To add the ability to save changes to customer records

    1. In the designer, double-click the Save changes button.Visual Studio opens the code-behind file and creates a new saveButton_Click event

    handler.

    2. Add the following code to the saveButton_Click event handler:JavaScript

    C#

    C++

    F#

    JScript

    VB

    Copy to Clipboard

    http://void%280%29/http://void%280%29/http://changetab%28%27id299%27%2C%27c/#','2','6')http://changetab%28%27id299%27%2C%27c/#','2','6')http://changetab%28%27id299%27%2C%27visual%20basic%27%2C%276%27%2C%276%27%29/http://changetab%28%27id299%27%2C%27visual%20basic%27%2C%276%27%2C%276%27%29/http://copytoclipboard%28%27id299%27%2C%276%27%29/http://copytoclipboard%28%27id299%27%2C%276%27%29/http://void%280%29/http://copytoclipboard%28%27id299%27%2C%276%27%29/http://changetab%28%27id299%27%2C%27visual%20basic%27%2C%276%27%2C%276%27%29/http://changetab%28%27id299%27%2C%27c/#','2','6')http://void%280%29/
  • 7/27/2019 Sequential Workflows

    30/208

    adventureWorksLTEntities.SaveChanges();

    Testing the Application

    Build and run the application to verify that it displays the customer records and enables you tosave changes to them.

    To test the application

    1. Press F5.2. Edit one of the customer records and then click Save changes.3. Close the application, and then start the application again by pressing F5.4. Navigate to the customer record you changed, and verify that the change has persisted.5. Close the application.

    Next Steps

    After completing this walkthrough, you can perform the following related tasks:

    Learn how to use the Data Sources window in Visual Studio to bind WPF controls toother types of data sources. For more information, see Walkthrough: Binding WPFControls to a WCF Data Service and Walkthrough: Binding WPF Controls to a Dataset.

    Learn how to use the Data Sources window in Visual Studio to display related data (thatis, data in a parent-child relationship) in WPF controls. For more information, seeWalkthrough: Displaying Related Data in a WPF Application.

    See Also

    Walkthrough: Binding WPF Controls to a WCF Data

    Service

    Send Feedbackon this topic to Microsoft. View this topiconlinein your default

    browser.

    http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/mailto:[email protected]?subject=MSDN%5e*dd465161%5e*VS%5e*110%5e*EN-US&body=Visual%20Studio%20feedback%20policy%3a%20http%3a%2f%2fmsdn.microsoft.com%2fEN-US%2flibrary%2fee264131(VS.110).aspxmailto:[email protected]?subject=MSDN%5e*dd465161%5e*VS%5e*110%5e*EN-US&body=Visual%20Studio%20feedback%20policy%3a%20http%3a%2f%2fmsdn.microsoft.com%2fEN-US%2flibrary%2fee264131(VS.110).aspxhttp://msdn.microsoft.com/EN-US/library/dd465161(v=VS.110,d=hv.2).aspxhttp://msdn.microsoft.com/EN-US/library/dd465161(v=VS.110,d=hv.2).aspxhttp://msdn.microsoft.com/EN-US/library/dd465161(v=VS.110,d=hv.2).aspxhttp://void%280%29/http://void%280%29/http://void%280%29/http://msdn.microsoft.com/EN-US/library/dd465161(v=VS.110,d=hv.2).aspxmailto:[email protected]?subject=MSDN%5e*dd465161%5e*VS%5e*110%5e*EN-US&body=Visual%20Studio%20feedback%20policy%3a%20http%3a%2f%2fmsdn.microsoft.com%2fEN-US%2flibrary%2fee264131(VS.110).aspxhttp://void%280%29/http://void%280%29/http://void%280%29/
  • 7/27/2019 Sequential Workflows

    31/208

    In this walkthrough, you will create a WPF application that contains data-bound controls. The

    controls are bound to customer records that are encapsulated in a WCF Data Service. You will

    also add buttons that customers can use to view and update records.

    This walkthrough illustrates the following tasks:

    Creating an Entity Data Model that is generated from data in the AdventureWorksLTsample database.

    Creating a WCF Data Service that exposes the data in the Entity Data Model to a WPFapplication.

    Creating a set of data-bound controls by dragging items from the Data Sources window tothe WPF designer.

    Creating buttons that navigate forward and backward through customer records. Creating a button that saves changes to data in the controls to the WCF Data Service and

    the underlying data source.

    Note

    Your computer might show different names or locations for some of the Visual Studiouser interface elements in the following instructions. The Visual Studio edition that you

    have and the settings that you use determine these elements. For more information, see

    Visual Studio Settings.

    Prerequisites

    You need the following components to complete this walkthrough:

    Visual Studio Access to a running instance of SQL Server or SQL Server Express that has the

    AdventureWorksLT sample database attached to it. You can download the

    AdventureWorksLT database from the CodePlex Web site.

    Prior knowledge of the following concepts is also helpful, but not required to complete thewalkthrough:

    WCF Data Services. For more information, see ADO.NET Data Services FrameworkOverview.

    Data models in WCF Data Services. Entity Data Models and the ADO.NET Entity Framework. For more information, see

    Introducing the Entity Framework.

    Working with the WPF designer. For more information, see WPF and SilverlightDesigner Overview.

    http://void%280%29/http://void%280%29/http://go.microsoft.com/fwlink/?linkid=87843http://go.microsoft.com/fwlink/?linkid=87843http://go.microsoft.com/fwlink/?linkid=87843http://void%280%29/http://go.microsoft.com/fwlink/?linkid=87843http://void%280%29/
  • 7/27/2019 Sequential Workflows

    32/208

    WPF data binding. For more information, see Data Binding Overview.

    Creating the Service Project

    Start this walkthrough by creating a project for a WCF Data Service.

    To create the service project

    1. Start Visual Studio.2. On the File menu, point to New, and then click Project.3. Expand Visual C# or Visual Basic, and then select Web.4. Select the ASP.NET Web Application project template.5. In the Name box, type AdventureWorksService and click OK.

    Visual Studio creates the AdventureWorksService project.

    6. In Solution Explorer, right-click Default.aspx and select Delete. This file is not necessaryin this walkthrough.

    Creating an Entity Data Model for the Service

    To expose data to an application by using a WCF Data Service, you must define a data model forthe service. The WCF Data Service supports two types of data models: Entity Data Models and

    custom data models that are defined by using common language runtime (CLR) objects thatimplement the IQueryable< T> interface. In this walkthrough, you create an Entity Data Model

    for the data model.

    To create an Entity Data Model

    1. On the Project menu, click Add New Item.2. In the Installed Templates list, click Data, and then select the ADO.NET Entity Data

    Model project item.

    3. Change the name to AdventureWorksModel.edmx, and click Add.The Entity Data Model Wizard opens.

    4. On the Choose Model Contents page, click Generate from database, and click Next.5. On the Choose Your Data Connection page, select one of the following options:

    o If a data connection to the AdventureWorksLT sample database is available in thedrop-down list, select it.

    http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/
  • 7/27/2019 Sequential Workflows

    33/208

    -or-

    o Click New Connection and create a connection to the AdventureWorksLTdatabase.

    6. On the Choose Your Data Connection page, make sure that the Save entity connectionsettings in App.Config as option is selected and then click Next.7. On the Choose Your Database Objects page, expand Tables, and then select theSalesOrderHeader table.

    8. Click Finish.

    Creating the Service

    Create a WCF Data Service to expose the data in the Entity Data Model to a WPF application.

    To create the service

    1. On the Project menu, select Add New Item.2. In the Installed Templates list, click Web, and then select the WCF Data Service project

    item.3. In the Name box, type AdventureWorksService.svc and click Add.

    Visual Studio adds the AdventureWorksService.svc to the project.

    Configuring the Service

    You must configure the service to operate on the Entity Data Model that you created.

    To configure the service

    1. In the AdventureWorks.svc code file, replace the AdventureWorksService classdeclaration with the following code.

    JavaScript

    C#

    C++

    F#

    http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://changetab%28%27id210%27%2C%27c/#','2','6')http://changetab%28%27id210%27%2C%27c/#','2','6')http://void%280%29/http://void%280%29/http://changetab%28%27id210%27%2C%27c/#','2','6')http://void%280%29/http://void%280%29/
  • 7/27/2019 Sequential Workflows

    34/208

    JScript

    VB

    Copy to Clipboard

    publicclass AdventureWorksService :DataService{

    // This method is called only once to initialize service-widepolicies.

    publicstaticvoid InitializeService(IDataServiceConfigurationconfig)

    {config.SetEntitySetAccessRule("SalesOrderHeaders",

    EntitySetRights.All);}

    }

    This code updates the AdventureWorksService class so that it derives from a

    DataService< T> that operates on theAdventureWorksLTEntities object context class inyour Entity Data Model. It also updates the InitializeService method to allow clients ofthe service full read/write access to the SalesOrderHeader entity.

    2. Build the project, and verify that it builds without errors.

    Creating the WPF Client Application

    To display the data from the WCF Data Service, create a new WPF application with a datasource that is based on the service. Later in this walkthrough, you will add data-bound controls to

    the application.

    To create the WPF client application

    1. In Solution Explorer, right-click the solution node, click Add, and select New Project.2. In the New Project dialog, expand Visual C# or Visual Basic, and then select Windows.3. Select the WPF Application project template.4. In the Name box, type AdventureWorksSalesEditor and click OK.

    Visual Studio adds the AdventureWorksSalesEditor project to the solution.

    5. On the Data menu, click Show Data Sources.The Data Sources window opens.

    http://changetab%28%27id210%27%2C%27visual%20basic%27%2C%276%27%2C%276%27%29/http://changetab%28%27id210%27%2C%27visual%20basic%27%2C%276%27%2C%276%27%29/http://copytoclipboard%28%27id210%27%2C%276%27%29/http://copytoclipboard%28%27id210%27%2C%276%27%29/http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/http://copytoclipboard%28%27id210%27%2C%276%27%29/http://changetab%28%27id210%27%2C%27visual%20basic%27%2C%276%27%2C%276%27%29/
  • 7/27/2019 Sequential Workflows

    35/208

    6. In the Data Sources window, click Add New Data Source.The Data Source Configuration Wizard opens.

    7. In the Choose a Data Source Type page of the wizard, select Service and then click Next.8.

    In the Add Service Reference dialog box, click Discover.

    Visual Studio searches the current solution for available services, and addsAdventureWorksService.svc to the list of available services in the Services box.

    9. In the Namespace box, type AdventureWorksService.10.In the Services box, click AdventureWorksService.svc and then click OK.

    Visual Studio downloads the service information and then returns to the Data SourceConfiguration Wizard.

    11.In the Add Service Reference page, click Finish.

    Visual Studio adds nodes that represent the data returned by the service to the DataSources window.

    Defining the User Interface of the Window

    Add several buttons to the window by modifying the XAML in the WPF designer. Later in this

    walkthrough, you will add code that enables users to view and update sales records by usingthese buttons.

    To create the window layout

    1. In Solution Explorer, double-click MainWindow.xaml.The window opens in the WPF designer.

    2. In the XAML view of the designer, add the following code between the tags:Copy to Clipboard

    Save changes

    3.Build the project.

    Creating the Data-bound Controls

    Create controls that display customer records by dragging the SalesOrderHeaders node from the

    Data Sources window to the designer.

    To create the data-bound controls

    1. In the Data Sources window, click the drop-down menu for the SalesOrderHeaders nodeand select Details.

    2. Expand the SalesOrderHeaders node.3. For this example some fields will not be displayed so click the drop-down menu next to

    the following nodes and select None:o CreditCardApprovalCodeo ModifiedDateo OnlineOrderFlago RevisionNumbero rowguid

    This action prevents Visual Studio from creating data-bound controls for these nodes inthe next step. For this walkthrough, it is assumed that the end user does not need to see

    this data.

    4. From the Data Sources window, drag the SalesOrderHeaders node to the grid row underthe row that contains the buttons.

    Visual Studio generates XAML and code that creates a set of controls that are bound to

    data in the Product table. For more information about the generated XAML and code, see

    Binding WPF Controls to Data in Visual Studio.

    5. In the designer, click the text box next to the Customer ID label.6. In the Properties window, select the check box next to the IsReadOnly property.7. Set the IsReadOnly property for each of the following text boxes:

    o Purchase Order Numbero Sales Order IDo Sales Order Number

    http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/
  • 7/27/2019 Sequential Workflows

    37/208

  • 7/27/2019 Sequential Workflows

    38/208

    }

    Navigating Sales Records

    Add code that enables users to scroll through sales records by using the < and > buttons.

    To enable users to navigate sales records

    1. In the designer, double-click the < button on the window surface.Visual Studio opens the code-behind file and creates a new backButton_Click event

    handler for the Clickevent.

    2. Add the following code to the generated backButton_Click event handler:JavaScript

    C#

    C++

    F#

    JScript

    VB

    Copy to Clipboard

    if (ordersViewSource.View.CurrentPosition > 0)ordersViewSource.View.MoveCurrentToPrevious();

    3.Return to the designer, and double-click the > button.

    Visual Studio opens the code-behind file and creates a new nextButton_Click eventhandler for the Clickevent.

    4. Add the following code to the generated nextButton_Click event handler:JavaScript

    C#

    http://void%280%29/http://void%280%29/http://changetab%28%27id407%27%2C%27c/#','2','6')http://changetab%28%27id407%27%2C%27c/#','2','6')http://changetab%28%27id407%27%2C%27visual%20basic%27%2C%276%27%2C%276%27%29/http://changetab%28%27id407%27%2C%27visual%20basic%27%2C%276%27%2C%276%27%29/http://copytoclipboard%28%27id407%27%2C%276%27%29/http://copytoclipboard%28%27id407%27%2C%276%27%29/http://changetab%28%27id419%27%2C%27c/#','2','6')http://changetab%28%27id419%27%2C%27c/#','2','6')http://void%280%29/http://changetab%28%27id419%27%2C%27c/#','2','6')http://copytoclipboard%28%27id407%27%2C%276%27%29/http://changetab%28%27id407%27%2C%27visual%20basic%27%2C%276%27%2C%276%27%29/http://changetab%28%27id407%27%2C%27c/#','2','6')http://void%280%29/
  • 7/27/2019 Sequential Workflows

    39/208

    C++

    F#

    JScript

    VB

    Copy to Clipboard

    if (ordersViewSource.View.CurrentPosition . TheCar class implements the

    IComparable< T> interface, which requires that the CompareTo method be implemented.

    Each call to the CompareTo method makes a single comparison that is used for sorting. User-written code in the CompareTo method returns a value for each comparison of the current

    object with another object. The value returned is less than zero if the current object is less than

    the other object, greater than zero if the current object is greater than the other object, and zero if

    they are equal. This enables you to define in code the criteria for greater than, less than, andequal.

    In the ListCars method, the cars.Sort() statement sorts the list. This call to the Sort method of theList< T> causes theCompareTo method to be called automatically for the Car objects in the

    List.

    JavaScriptC#

    C++F#

    JScript

    VBCopy to Clipboardprivatevoid ListCars()

    http://void%280%29/http://void%280%29/http://changetab%28%27id471%27%2C%27c/#','2','6')http://changetab%28%27id471%27%2C%27c/#','2','6')http://changetab%28%27id471%27%2C%27visual%20basic%27%2C%276%27%2C%276%27%29/http://changetab%28%27id471%27%2C%27visual%20basic%27%2C%276%27%2C%276%27%29/http://copytoclipboard%28%27id471%27%2C%276%27%29/http://copytoclipboard%28%27id471%27%2C%276%27%29/http://void%280%29/http://copytoclipboard%28%27id471%27%2C%276%27%29/http://changetab%28%27id471%27%2C%27visual%20basic%27%2C%276%27%2C%276%27%29/http://changetab%28%27id471%27%2C%27c/#','2','6')http://void%280%29/
  • 7/27/2019 Sequential Workflows

    106/208

    {var cars = new List{

    { new Car() { Name = "car1", Color = "blue", Speed = 20}},{ new Car() { Name = "car2", Color = "red", Speed = 50}},{ new Car() { Name = "car3", Color = "green", Speed = 10}},{ new Car() { Name = "car4", Color = "blue", Speed = 50}},{ new Car() { Name = "car5", Color = "blue", Speed = 30}},{ new Car() { Name = "car6", Color = "red", Speed = 60}},{ new Car() { Name = "car7", Color = "green", Speed = 50}}

    };

    // Sort the cars by color alphabetically, and then by speed// in descending order.cars.Sort();

    // View all of the cars.foreach (Car thisCar in cars){

    Console.Write(thisCar.Color.PadRight(5) + " ");

    Console.Write(thisCar.Speed.ToString() + " ");Console.Write(thisCar.Name);Console.WriteLine();

    }

    // Output:// blue 50 car4// blue 30 car5// blue 20 car1// green 50 car7// green 10 car3// red 60 car6// red 50 car2

    }

    publicclass Car : IComparable{

    publicstring Name { get; set; }publicint Speed { get; set; }publicstring Color { get; set; }

    publicint CompareTo(Car other){

    // A call to this method makes a single comparison that is// used for sorting.

    // Determine the relative order of the objects being compared.

    // Sort by color alphabetically, and then by speed in// descending order.

    // Compare the colors.int compare;compare = String.Compare(this.Color, other.Color, true);

    // If the colors are the same, compare the speeds.if (compare == 0){

  • 7/27/2019 Sequential Workflows

    107/208

    compare = this.Speed.CompareTo(other.Speed);

    // Use descending order for speed.compare = -compare;

    }

    return compare;}

    }

    Defining a Custom Collection

    You can define a collection by implementing the IEnumerable< T> orIEnumerable interface.

    For additional information, see Enumerating a Collection and How to: Access a Collection Classwith foreach (C# Programming Guide).

    Although you can define a custom collection, it is usually better to instead use the collections

    that are included in the .NET Framework, which are described in Kinds of Collections earlier inthis topic.

    The following example defines a custom collection class named AllColors. This class

    implements the IEnumerable interface, which requires that the GetEnumeratormethod beimplemented.

    The GetEnumerator method returns an instance of the ColorEnumerator class.ColorEnumerator implements the IEnumeratorinterface, which requires that the Current

    property, MoveNext method, and Reset method be implemented.

    JavaScriptC#

    C++

    F#JScript

    VB

    Copy to Clipboardprivatevoid ListColors(){

    var colors = new AllColors();

    foreach (Color theColor in colors)

    {Console.Write(theColor.Name + " ");

    }Console.WriteLine();// Output: red blue green

    }

    // Collection class.publicclass AllColors : System.Collections.IEnumerable

    http://void%280%29/http://void%280%29/http://changetab%28%27id508%27%2C%27c/#','2','6')http://changetab%28%27id508%27%2C%27c/#','2','6')http://changetab%28%27id508%27%2C%27visual%20basic%27%2C%276%27%2C%276%27%29/http://changetab%28%27id508%27%2C%27visual%20basic%27%2C%276%27%2C%276%27%29/http://copytoclipboard%28%27id508%27%2C%276%27%29/http://copytoclipboard%28%27id508%27%2C%276%27%29/http://void%280%29/http://copytoclipboard%28%27id508%27%2C%276%27%29/http://changetab%28%27id508%27%2C%27visual%20basic%27%2C%276%27%2C%276%27%29/http://changetab%28%27id508%27%2C%27c/#','2','6')http://void%280%29/
  • 7/27/2019 Sequential Workflows

    108/208

    {Color[] _colors ={

    new Color() { Name = "red" },new Color() { Name = "blue" },new Color() { Name = "green" }

    };

    public System.Collections.IEnumerator GetEnumerator(){

    returnnew ColorEnumerator(_colors);

    // Instead of creating a custom enumerator, you could// use the GetEnumerator of the array.//return _colors.GetEnumerator();

    }

    // Custom enumerator.privateclass ColorEnumerator : System.Collections.IEnumerator{

    private Color[] _colors;privateint _position = -1;

    public ColorEnumerator(Color[] colors){

    _colors = colors;}

    object System.Collections.IEnumerator.Current{

    get{

    return _colors[_position];}

    }

    bool System.Collections.IEnumerator.MoveNext(){

    _position++;return (_position < _colors.Length);

    }

    void System.Collections.IEnumerator.Reset(){

    _position = -1;}

    }

    }

    // Element class.publicclass Color{

    publicstring Name { get; set; }}

    Iterators

    http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/
  • 7/27/2019 Sequential Workflows

    109/208

    An iterator is used to perform a custom iteration over a collection. An iterator can be a method ora get accessor. An iterator uses a Yield (Visual Basic) oryield return (C#) statement to return

    each element of the collection one at a time.

    You call an iterator by using a For EachNext (Visual Basic) orforeach (C#) statement. Each

    iteration of the For Each loop calls the iterator. When a Yield or yield return statement is reached

    in the iterator, an expression is returned, and the current location in code is retained. Execution isrestarted from that location the next time that the iterator is called.

    For more information, see Iterators (C# and Visual Basic).

    The following example uses an iterator method. The iterator method has a Yield or yield return

    statement that is inside a ForNext (Visual Basic) orfor(C#) loop. In the ListEvenNumbersmethod, each iteration of the For Each statement body creates a call to the iterator method, which

    proceeds to the next Yield or yield return statement.

    JavaScript

    C#

    C++F#

    JScript

    VBCopy to Clipboardprivatevoid ListEvenNumbers(){

    foreach (int number in EvenSequence(5, 18))

    {Console.Write(number.ToString() + " ");

    }Console.WriteLine();// Output: 6 8 10 12 14 16 18

    }

    privatestatic IEnumerable EvenSequence(int firstNumber, int lastNumber)

    {// Yield even numbers in the range.for (var number = firstNumber; number

  • 7/27/2019 Sequential Workflows

    110/208

    Send Feedbackon this topic to Microsoft. View this topiconlinein yourdefault browser.

    The following code example illustrates how to write a non-generic collection class that can be

    used with foreach. The example defines a string tokenizer class.

    Note

    This example represents recommended practice only when you cannot use a generic collection

    class. For an example of how to implement a type-safe generic collection class that supports

    IEnumerable< T> , see Iterators (C# and Visual Basic).

    In the example, the following code segment uses the Tokens class to break the sentence "This is

    a sample sentence." into tokens by using ' ' and '- ' as separators. The code then displays those

    tokens by using a foreach statement.

    JavaScriptC#

    C++

    F#

    JScriptVB

    Copy to ClipboardTokens f = new Tokens("This is a sample sentence.", newchar[] {' ','-'});

    // Display the tokens.

    foreach (string item in f){System.Console.WriteLine(item);

    }

    Example

    Internally, the Tokens class uses an array to store the tokens. Because arrays implement

    IEnumeratorand IEnumerable, the code example could have used the array's enumerationmethods ( GetEnumerator, MoveNext, Reset, and Current) instead of defining them in the

    Tokens class. The method definitions are included in the example to clarify how they are defined

    and what each does.

    JavaScript

    C#

    C++F#

    JScript

    VB

    mailto:[email protected]?subject=MSDN%5e*9yb8xew9%5e*VS%5e*110%5e*EN-US&body=Visual%20Studio%20feedback%20policy%3a%20http%3a%2f%2fmsdn.microsoft.com%2fEN-US%2flibrary%2fee264131(VS.110).aspxmailto:[email protected]?subject=MSDN%5e*9yb8xew9%5e*VS%5e*110%5e*EN-US&body=Visual%20Studio%20feedback%20policy%3a%20http%3a%2f%2fmsdn.microsoft.com%2fEN-US%2flibrary%2fee264131(VS.110).aspxhttp://msdn.microsoft.com/EN-US/library/9yb8xew9(v=VS.110,d=hv.2).aspxhttp://msdn.microsoft.com/EN-US/library/9yb8xew9(v=VS.110,d=hv.2).aspxhttp://msdn.microsoft.com/EN-US/library/9yb8xew9(v=VS.110,d=hv.2).aspxhttp://changetab%28%27id59%27%2C%27c/#','2','6')http://changetab%28%27id59%27%2C%27c/#','2','6')http://copytoclipboard%28%27id59%27%2C%276%27%29/http://copytoclipboard%28%27id59%27%2C%276%27%29/http://void%280%29/http://void%280%29/http://changetab%28%27id78%27%2C%27c/#','2','6')http://changetab%28%27id78%27%2C%27c/#','2','6')http://void%280%29/http://changetab%28%27id78%27%2C%27c/#','2','6')http://void%280%29/http://copytoclipboard%28%2