diff --git a/.ghal.rules.json b/.ghal.rules.json index c783c5375c..eb81642863 100644 --- a/.ghal.rules.json +++ b/.ghal.rules.json @@ -17,17 +17,17 @@ } }, "contentsource": { - "(?i).*master\/docs\/framework\/wpf.*": { - "labels-add": ":books: Area - Framework,:card_file_box: Technology - WPF" + "(?i).*dotnet-desktop-guide\/framework\/wpf.*": { + "labels-add": ":books: Area - .Framework,:card_file_box: Technology - WPF" }, - "(?i).*master\/docs\/framework\/winforms.*": { - "labels-add": ":books: Area - Framework,:card_file_box: Technology - WinForms" + "(?i).*dotnet-desktop-guide\/framework\/winforms.*": { + "labels-add": ":books: Area - .Framework,:card_file_box: Technology - WinForms" }, - "(?i).*master\/docs\/net\/wpf.*": { - "labels-add": ":books: Area - NET,:card_file_box: Technology - WPF" + "(?i).*dotnet-desktop-guide\/net\/wpf.*": { + "labels-add": ":books: Area - .NET,:card_file_box: Technology - WPF" }, - "(?i).*master\/docs\/net\/winforms.*": { - "labels-add": ":books: Area - NET,:card_file_box: Technology - WinForms" + "(?i).*dotnet-desktop-guide\/net\/winforms.*": { + "labels-add": ":books: Area - .NET,:card_file_box: Technology - WinForms" } } } @@ -49,17 +49,17 @@ "processors": { "processor-files": { "changedfile": { - "(?i).*docs\/framework\/wpf.*": { - "labels-add": ":books: Area - Framework,:card_file_box: Technology - WPF" + "(?i).*dotnet-desktop-guide\/framework\/wpf.*": { + "labels-add": ":books: Area - .Framework,:card_file_box: Technology - WPF" }, - "(?i).*docs\/framework\/winforms.*": { - "labels-add": ":books: Area - Framework,:card_file_box: Technology - WinForms" + "(?i).*dotnet-desktop-guide\/framework\/winforms.*": { + "labels-add": ":books: Area - .Framework,:card_file_box: Technology - WinForms" }, - "(?i).*docs\/net\/wpf.*": { - "labels-add": ":books: Area - NET,:card_file_box: Technology - WPF" + "(?i).*dotnet-desktop-guide\/net\/wpf.*": { + "labels-add": ":books: Area - .NET,:card_file_box: Technology - WPF" }, - "(?i).*docs\/net\/winforms.*": { - "labels-add": ":books: Area - NET,:card_file_box: Technology - WinForms" + "(?i).*dotnet-desktop-guide\/net\/winforms.*": { + "labels-add": ":books: Area - .NET,:card_file_box: Technology - WinForms" } } } diff --git a/.github/workflows/markdownlint.yml b/.github/workflows/markdownlint.yml index f41a8c891a..8e7a9afb70 100644 --- a/.github/workflows/markdownlint.yml +++ b/.github/workflows/markdownlint.yml @@ -29,4 +29,4 @@ jobs: run: | echo "::add-matcher::.github/workflows/markdownlint-problem-matcher.json" npm i -g markdownlint-cli - markdownlint "**/*.md" -i "samples/**/*.md" + markdownlint "**/*.md" diff --git a/dotnet-desktop-guide/TOC.yml b/dotnet-desktop-guide/TOC.yml index 65c4660cc4..6f768a1bf6 100644 --- a/dotnet-desktop-guide/TOC.yml +++ b/dotnet-desktop-guide/TOC.yml @@ -6,3 +6,8 @@ items: href: https://docs.microsoft.com/dotnet/desktop/winforms/?view=netdesktop-5.0 - name: .NET Framework href: https://docs.microsoft.com/dotnet/desktop/winforms/?view=netframeworkdesktop-4.8 +- name: Windows Presentation Foundation + expanded: true + items: + - name: .NET Framework + href: https://docs.microsoft.com/dotnet/desktop/wpf/?view=netframeworkdesktop-4.8 \ No newline at end of file diff --git a/dotnet-desktop-guide/framework/breadcrumb/toc.yml b/dotnet-desktop-guide/framework/breadcrumb/toc.yml index 1dac05392a..5673b945fa 100644 --- a/dotnet-desktop-guide/framework/breadcrumb/toc.yml +++ b/dotnet-desktop-guide/framework/breadcrumb/toc.yml @@ -23,3 +23,25 @@ items: - name: Controls tocHref: /dotnet/desktop/winforms/controls/ topicHref: /dotnet/desktop/winforms/controls/index + - name: Windows Presentation Foundation + tocHref: /dotnet/desktop/wpf/ + topicHref: /dotnet/desktop/wpf/index + items: + - name: Advanced + tocHref: /dotnet/desktop/wpf/advanced/ + topicHref: /dotnet/desktop/wpf/advanced/index + - name: Application development + tocHref: /dotnet/desktop/wpf/app-development/ + topicHref: /dotnet/desktop/wpf/app-development/index + - name: Controls + tocHref: /dotnet/desktop/wpf/controls/ + topicHref: /dotnet/desktop/wpf/controls/index + - name: Data + tocHref: /dotnet/desktop/wpf/data/ + topicHref: /dotnet/desktop/wpf/data/index + - name: Get started (WPF) + tocHref: /dotnet/desktop/wpf/getting-started/ + topicHref: /dotnet/desktop/wpf/getting-started/index + - name: Graphics and multimedia + tocHref: /dotnet/desktop/wpf/graphics-multimedia/ + topicHref: /dotnet/desktop/wpf/graphics-multimedia/index diff --git a/dotnet-desktop-guide/framework/wpf/advanced/activate-function-wpf-unmanaged-api-reference.md b/dotnet-desktop-guide/framework/wpf/advanced/activate-function-wpf-unmanaged-api-reference.md new file mode 100644 index 0000000000..de59c7d29c --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/activate-function-wpf-unmanaged-api-reference.md @@ -0,0 +1,51 @@ +--- +title: "Activate Function - WPF unmanaged API reference" +titleSuffix: "" +ms.date: "03/30/2017" +dev_langs: + - "cpp" +api_name: + - "Activate" +api_location: + - "PresentationHost_v0400.dll" +ms.assetid: 1400329c-b598-465f-80f2-e3dabf044811 +--- + +# Activate Function (WPF Unmanaged API Reference) + +This API supports the Windows Presentation Foundation (WPF) infrastructure and is not intended to be used directly from your code. + +Used by the Windows Presentation Foundation (WPF) infrastructure for windows management. + +## Syntax + +```cpp +void Activate( + const ActivateParameters* pParameters, + __deref_out_ecount(1) LPUNKNOWN* ppInner, + ); +``` + +## Parameters + +`pParameters`\ +A pointer to the window's activation parameters. + +`ppInner`\ +A pointer to the address of a single-element buffer that contains a pointer to an object. + +## Requirements + +**Platforms:** See [.NET Framework System Requirements](/dotnet/framework/get-started/system-requirements). + +**DLL:** + +In the .NET Framework 3.0 and 3.5: PresentationHostDLL.dll + +In the .NET Framework 4 and later: PresentationHost_v0400.dll + +**.NET Framework Version:** [!INCLUDE[net_current_v30plus](../../../includes/net-current-v30plus-md.md)] + +## See also + +- [WPF Unmanaged API Reference](wpf-unmanaged-api-reference.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/advanced-ink-handling.md b/dotnet-desktop-guide/framework/wpf/advanced/advanced-ink-handling.md new file mode 100644 index 0000000000..c70a7fca11 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/advanced-ink-handling.md @@ -0,0 +1,21 @@ +--- +title: "Advanced Ink Handling" +ms.date: "03/30/2017" +f1_keywords: + - "AutoGeneratedOrientationPage" +helpviewer_keywords: + - "System.Windows.Input.StylusPlugIns classes" + - "InkCanvas control [WPF]" + - "ink [WPF], advanced handling" +ms.assetid: abc8481a-f983-416f-b051-9168ac8b2ba3 +--- +# Advanced Ink Handling +The [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] ships with the , and is an element you can put in your application to immediately start collecting and displaying ink. However, if the control does not provide a fine enough level of control, you can maintain control at a higher level by customizing your own ink collection and ink rendering classes using . + + The classes provide a mechanism for implementing low-level control over input and dynamically rendering ink. The class provides a mechanism for you to implement custom behavior and apply it to the stream of data coming from the stylus device for optimal performance. The , a specialized , allows you to customize dynamically rendering ink data in real-time which means that the draws digital ink immediately as data is generated, so it appears to "flow" from the stylus device. + +## In This Section + [Custom Rendering Ink](custom-rendering-ink.md) + [Intercepting Input from the Stylus](intercepting-input-from-the-stylus.md) + [Creating an Ink Input Control](creating-an-ink-input-control.md) + [The Ink Threading Model](the-ink-threading-model.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/advanced-text-formatting.md b/dotnet-desktop-guide/framework/wpf/advanced/advanced-text-formatting.md new file mode 100644 index 0000000000..15d4fe1100 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/advanced-text-formatting.md @@ -0,0 +1,91 @@ +--- +title: "Advanced Text Formatting" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "formatting [WPF]" + - "text [WPF]" + - "typography [WPF], text formatting" +ms.assetid: f0a7986e-f5b2-485c-a27d-f8e922022212 +--- +# Advanced Text Formatting +Windows Presentation Foundation (WPF) provides a robust set of APIs for including text in your application. Layout and [!INCLUDE[TLA#tla_ui](../../../includes/tlasharptla-ui-md.md)] APIs, such as , provide the most common and general-use elements for text presentation. Drawing APIs, such as and , provide a means for including formatted text in drawings. At the most advanced level, WPF provides an extensible text formatting engine to control every aspect of text presentation, such as text store management, text run formatting management, and embedded object management. + + This topic provides an introduction to WPF text formatting. It focuses on client implementation and use of the WPF text formatting engine. + +> [!NOTE] +> All code examples within this document can be found in the [Advanced Text Formatting Sample](https://github.com/Microsoft/WPF-Samples/tree/master/PerMonitorDPI/TextFormatting). + + +## Prerequisites + This topic assumes that you are familiar with the higher level APIs used for text presentation. Most user scenarios will not require the advanced text formatting APIs discussed in this topic. For an introduction to the different text APIs, see [Documents in WPF](documents-in-wpf.md). + + +## Advanced Text Formatting + The text layout and [!INCLUDE[TLA2#tla_ui](../../../includes/tla2sharptla-ui-md.md)] controls in WPF provide formatting properties that allow you to easily include formatted text in your application. These controls expose a number of properties to handle the presentation of text, which includes its typeface, size, and color. Under ordinary circumstances, these controls can handle the majority of text presentation in your application. However, some advanced scenarios require the control of text storage as well as text presentation. WPF provides an extensible text formatting engine for this purpose. + + The advanced text formatting features found in WPF consist of a text formatting engine, a text store, text runs, and formatting properties. The text formatting engine, , creates lines of text to be used for presentation. This is achieved by initiating the line formatting process and calling the text formatter's . The text formatter retrieves text runs from your text store by calling the store's method. The objects are then formed into objects by the text formatter and given to your application for inspection or display. + + +## Using the Text Formatter + is the WPF text formatting engine and provides services for formatting and breaking text lines. The text formatter can handle different text character formats and paragraph styles, and includes support for international text layout. + + Unlike a traditional text API, the interacts with a text layout client through a set of callback methods. It requires the client to provide these methods in an implementation of the class. The following diagram illustrates the text layout interaction between the client application and . + + ![Diagram of text layout client and TextFormatter](./media/advanced-text-formatting/text-layout-textformatter-interaction.png) + + The text formatter is used to retrieve formatted text lines from the text store, which is an implementation of . This is done by first creating an instance of the text formatter by using the method. This method creates an instance of the text formatter and sets the maximum line height and width values. As soon as an instance of the text formatter is created, the line creation process is started by calling the method. calls back to the text source to retrieve the text and formatting parameters for the runs of text that form a line. + + In the following example, the process of formatting a text store is shown. The object is used to retrieve text lines from the text store and then format the text line for drawing into the . + + [!code-csharp[TextFormatterExample#100](~/samples/snippets/csharp/VS_Snippets_Wpf/TextFormatterExample/CSharp/Window1.xaml.cs#100)] + [!code-vb[TextFormatterExample#100](~/samples/snippets/visualbasic/VS_Snippets_Wpf/TextFormatterExample/VisualBasic/Window1.xaml.vb#100)] + + +## Implementing the Client Text Store + When you extend the text formatting engine, you are required to implement and manage all aspects of the text store. This is not a trivial task. The text store is responsible for tracking text run properties, paragraph properties, embedded objects, and other similar content. It also provides the text formatter with individual objects which the text formatter uses to create objects. + + To handle the virtualization of the text store, the text store must be derived from . defines the method the text formatter uses to retrieve text runs from the text store. is the method used by the text formatter to retrieve text runs used in line formatting. The call to is repeatedly made by the text formatter until one of the following conditions occurs: + +- A or a subclass is returned. + +- The accumulated width of text runs exceeds the maximum line width specified in either the call to create the text formatter or the call to the text formatter's method. + +- A Unicode newline sequence, such as "CF", "LF", or "CRLF", is returned. + + +## Providing Text Runs + The core of the text formatting process is the interaction between the text formatter and the text store. Your implementation of provides the text formatter with the objects and the properties with which to format the text runs. This interaction is handled by the method, which is called by the text formatter. + + The following table shows some of the predefined objects. + +|TextRun Type|Usage| +|------------------|-----------| +||The specialized text run used to pass a representation of character glyphs back to the text formatter.| +||The specialized text run used to provide content in which measuring, hit testing, and drawing is done in whole, such as a button or image within the text.| +||The specialized text run used to mark the end of a line.| +||The specialized text run used to mark the end of a paragraph.| +||The specialized text run used to mark the end of a segment, such as to end the scope affected by a previous run.| +||The specialized text run used to mark a range of hidden characters.| +||The specialized text run used to modify properties of text runs in its scope. The scope extends to the next matching text run, or the next .| + + Any of the predefined objects can be subclassed. This allows your text source to provide the text formatter with text runs that include custom data. + + The following example demonstrates a method. This text store returns objects to the text formatter for processing. + + [!code-csharp[TextFormatterExample#101](~/samples/snippets/csharp/VS_Snippets_Wpf/TextFormatterExample/CSharp/CustomTextSource.cs#101)] + [!code-vb[TextFormatterExample#101](~/samples/snippets/visualbasic/VS_Snippets_Wpf/TextFormatterExample/VisualBasic/CustomTextSource.vb#101)] + +> [!NOTE] +> In this example, the text store provides the same text properties to all of the text. Advanced text stores would need to implement their own span management to allow individual characters to have different properties. + + +## Specifying Formatting Properties + objects are formatted by using properties provided by the text store. These properties come in two types, and . handle paragraph inclusive properties such as and . are properties that can be different for each text run within a paragraph, such as foreground brush, , and font size. To implement custom paragraph and custom text run property types, your application must create classes that derive from and respectively. + +## See also + +- [Typography in WPF](typography-in-wpf.md) +- [Documents in WPF](documents-in-wpf.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/alignment-margins-and-padding-overview.md b/dotnet-desktop-guide/framework/wpf/advanced/alignment-margins-and-padding-overview.md new file mode 100644 index 0000000000..82df744d3c --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/alignment-margins-and-padding-overview.md @@ -0,0 +1,146 @@ +--- +title: "Alignment, Margins, and Padding Overview" +description: Learn about HorizontalAlignment, Margin, Padding, and VerticalAlignment, which control child element position in Windows Presentation Foundation applications. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "margins [WPF]" + - "padding [WPF]" + - "aligning [WPF]" +ms.assetid: 9c6a2009-9b86-4e40-8605-0a2664dc3973 +--- +# Alignment, Margins, and Padding Overview +The class exposes several properties that are used to precisely position child elements. This topic discusses four of the most important properties: , , , and . The effects of these properties are important to understand, because they provide the basis for controlling the position of elements in [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] applications. + + +## Introduction to Element Positioning + There are numerous ways to position elements using [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)]. However, achieving ideal layout goes beyond simply choosing the right element. Fine control of positioning requires an understanding of the , , , and properties. + + The following illustration shows a layout scenario that utilizes several positioning properties. + + ![WPF Positioning Properties Sample](./media/layout-margins-padding-alignment-graphic1.PNG "layout_margins_padding_alignment_graphic1") + + At first glance, the elements in this illustration may appear to be placed randomly. However, their positions are actually precisely controlled by using a combination of margins, alignments, and padding. + + The following example describes how to create the layout in the preceding illustration. A element encapsulates a parent , with a value of 15 device independent pixels. This accounts for the narrow band that surrounds the child . Child elements of the are used to illustrate each of the various positioning properties that are detailed in this topic. Three elements are used to demonstrate both the and properties. + + [!code-csharp[MPALayoutSampleIntro#1](~/samples/snippets/csharp/VS_Snippets_Wpf/MPALayoutSampleIntro/CSharp/MPA_Layout_Sample_Intro.cs#1)] + [!code-vb[MPALayoutSampleIntro#1](~/samples/snippets/visualbasic/VS_Snippets_Wpf/MPALayoutSampleIntro/VisualBasic/MPALayoutIntro.vb#1)] + + The following diagram provides a close-up view of the various positioning properties that are used in the preceding sample. Subsequent sections in this topic describe in greater detail how to use each positioning property. + + ![Positioning Properties with Screen Call-outs](./media/layout-margins-padding-alignment-graphic2.PNG "layout_margins_padding_alignment_graphic2") + + +## Understanding Alignment Properties + The and properties describe how a child element should be positioned within a parent element's allocated layout space. By using these properties together, you can position child elements precisely. For example, child elements of a can specify four different horizontal alignments: , , or , or to to fill available space. Similar values are available for vertical positioning. + +> [!NOTE] +> Explicitly-set and properties on an element take precedence over the property value. Attempting to set , , and a value of `Stretch` results in the `Stretch` request being ignored. + + +### HorizontalAlignment Property + The property declares the horizontal alignment characteristics to apply to child elements. The following table shows each of the possible values of the property. + +|Member|Description| +|------------|-----------------| +||Child elements are aligned to the left of the parent element's allocated layout space.| +||Child elements are aligned to the center of the parent element's allocated layout space.| +||Child elements are aligned to the right of the parent element's allocated layout space.| +| (Default)|Child elements are stretched to fill the parent element's allocated layout space. Explicit and values take precedence.| + + The following example shows how to apply the property to elements. Each attribute value is shown, to better illustrate the various rendering behaviors. + + [!code-csharp[MPALayoutHorizontalAlignment#2](~/samples/snippets/csharp/VS_Snippets_Wpf/MPALayoutHorizontalAlignment/CSharp/MPA_Layout_HorizontalAlignment.cs#2)] + [!code-vb[MPALayoutHorizontalAlignment#2](~/samples/snippets/visualbasic/VS_Snippets_Wpf/MPALayoutHorizontalAlignment/VisualBasic/MPA_Layout_HorizontalAlignment.vb#2)] + + The preceding code yields a layout similar to the following image. The positioning effects of each value are visible in the illustration. + + ![HorizontalAlignment Sample](./media/layout-horizontal-alignment-graphic.PNG "layout_horizontal_alignment_graphic") + + +### VerticalAlignment Property + The property describes the vertical alignment characteristics to apply to child elements. The following table shows each of the possible values for the property. + +|Member|Description| +|------------|-----------------| +||Child elements are aligned to the top of the parent element's allocated layout space.| +||Child elements are aligned to the center of the parent element's allocated layout space.| +||Child elements are aligned to the bottom of the parent element's allocated layout space.| +| (Default)|Child elements are stretched to fill the parent element's allocated layout space. Explicit and values take precedence.| + + The following example shows how to apply the property to elements. Each attribute value is shown, to better illustrate the various rendering behaviors. For purposes of this sample, a element with visible gridlines is used as the parent, to better illustrate the layout behavior of each property value. + + [!code-csharp[MPALayoutVerticalAlignment#2](~/samples/snippets/csharp/VS_Snippets_Wpf/MPALayoutVerticalAlignment/CSharp/MPA_Layout_VerticalAlignment.cs#2)] + [!code-vb[MPALayoutVerticalAlignment#2](~/samples/snippets/visualbasic/VS_Snippets_Wpf/MPALayoutVerticalAlignment/VisualBasic/MPA_Layout_VerticalAlignment.vb#2)] + [!code-xaml[MPALayoutVerticalAlignment#2](~/samples/snippets/xaml/VS_Snippets_Wpf/MPALayoutVerticalAlignment/XAML/default.xaml#2)] + + The preceding code yields a layout similar to the following image. The positioning effects of each value are visible in the illustration. + + ![VerticalAlignment property sample](./media/layout-vertical-alignment-graphic.PNG "layout_vertical_alignment_graphic") + + +## Understanding Margin Properties + The property describes the distance between an element and its child or peers. values can be uniform, by using syntax like `Margin="20"`. With this syntax, a uniform of 20 device independent pixels would be applied to the element. values can also take the form of four distinct values, each value describing a distinct margin to apply to the left, top, right, and bottom (in that order), like `Margin="0,10,5,25"`. Proper use of the property enables very fine control of an element's rendering position and the rendering position of its neighbor elements and children. + +> [!NOTE] +> A non-zero margin applies space outside the element's and . + + The following example shows how to apply uniform margins around a group of elements. The elements are spaced evenly with a ten-pixel margin buffer in each direction. + + [!code-cpp[MarginPaddingAlignmentSample#1](~/samples/snippets/cpp/VS_Snippets_Wpf/MarginPaddingAlignmentSample/CPP/Margin_Padding_Alignment_Sample.cpp#1)] + [!code-csharp[MarginPaddingAlignmentSample#1](~/samples/snippets/csharp/VS_Snippets_Wpf/MarginPaddingAlignmentSample/CSharp/Margin_Padding_Alignment_Sample.cs#1)] + [!code-vb[MarginPaddingAlignmentSample#1](~/samples/snippets/visualbasic/VS_Snippets_Wpf/MarginPaddingAlignmentSample/VisualBasic/MarginPaddingAlignment.vb#1)] + [!code-xaml[MarginPaddingAlignmentSample#1](~/samples/snippets/xaml/VS_Snippets_Wpf/MarginPaddingAlignmentSample/XAML/default.xaml#1)] + + In many instances, a uniform margin is not appropriate. In these cases, non-uniform spacing can be applied. The following example shows how to apply non-uniform margin spacing to child elements. Margins are described in this order: left, top, right, bottom. + + [!code-cpp[MarginPaddingAlignmentSample#2](~/samples/snippets/cpp/VS_Snippets_Wpf/MarginPaddingAlignmentSample/CPP/Margin_Padding_Alignment_Sample.cpp#2)] + [!code-csharp[MarginPaddingAlignmentSample#2](~/samples/snippets/csharp/VS_Snippets_Wpf/MarginPaddingAlignmentSample/CSharp/Margin_Padding_Alignment_Sample.cs#2)] + [!code-vb[MarginPaddingAlignmentSample#2](~/samples/snippets/visualbasic/VS_Snippets_Wpf/MarginPaddingAlignmentSample/VisualBasic/MarginPaddingAlignment.vb#2)] + [!code-xaml[MarginPaddingAlignmentSample#2](~/samples/snippets/xaml/VS_Snippets_Wpf/MarginPaddingAlignmentSample/XAML/default.xaml#2)] + + +## Understanding the Padding Property + Padding is similar to in most respects. The Padding property is exposed on only on a few classes, primarily as a convenience: , , , and are samples of classes that expose a Padding property. The property enlarges the effective size of a child element by the specified value. + + The following example shows how to apply to a parent element. + + [!code-cpp[MarginPaddingAlignmentSample#3](~/samples/snippets/cpp/VS_Snippets_Wpf/MarginPaddingAlignmentSample/CPP/Margin_Padding_Alignment_Sample.cpp#3)] + [!code-csharp[MarginPaddingAlignmentSample#3](~/samples/snippets/csharp/VS_Snippets_Wpf/MarginPaddingAlignmentSample/CSharp/Margin_Padding_Alignment_Sample.cs#3)] + [!code-vb[MarginPaddingAlignmentSample#3](~/samples/snippets/visualbasic/VS_Snippets_Wpf/MarginPaddingAlignmentSample/VisualBasic/MarginPaddingAlignment.vb#3)] + [!code-xaml[MarginPaddingAlignmentSample#3](~/samples/snippets/xaml/VS_Snippets_Wpf/MarginPaddingAlignmentSample/XAML/default.xaml#3)] + + +## Using Alignment, Margins, and Padding in an Application + , , , and provide the positioning control necessary to create a complex [!INCLUDE[TLA#tla_ui](../../../includes/tlasharptla-ui-md.md)]. You can use the effects of each property to change child-element positioning, enabling flexibility in creating dynamic applications and user experiences. + + The following example demonstrates each of the concepts that are detailed in this topic. Building on the infrastructure found in the first sample in this topic, this example adds a element as a child of the in the first sample. is applied to the parent element. The is used to partition space between three child elements. elements are again used to show the various effects of and . elements are added to each to better define the various properties applied to the elements in each column. + + [!code-cpp[MarginPaddingAlignmentSample#4](~/samples/snippets/cpp/VS_Snippets_Wpf/MarginPaddingAlignmentSample/CPP/Margin_Padding_Alignment_Sample.cpp#4)] + [!code-csharp[MarginPaddingAlignmentSample#4](~/samples/snippets/csharp/VS_Snippets_Wpf/MarginPaddingAlignmentSample/CSharp/Margin_Padding_Alignment_Sample.cs#4)] + [!code-vb[MarginPaddingAlignmentSample#4](~/samples/snippets/visualbasic/VS_Snippets_Wpf/MarginPaddingAlignmentSample/VisualBasic/MarginPaddingAlignment.vb#4)] + [!code-xaml[MarginPaddingAlignmentSample#4](~/samples/snippets/xaml/VS_Snippets_Wpf/MarginPaddingAlignmentSample/XAML/default.xaml#4)] + + When compiled, the preceding application yields a [!INCLUDE[TLA2#tla_ui](../../../includes/tla2sharptla-ui-md.md)] that looks like the following illustration. The effects of the various property values are evident in the spacing between elements, and significant property values for elements in each column are shown within elements. + + ![Several positioning properties in one application](./media/layout-margins-padding-aligment-graphic3.PNG "layout_margins_padding_aligment_graphic3") + + +## What's Next + Positioning properties defined by the class enable fine control of element placement within [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] applications. You now have several techniques you can use to better position elements using [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)]. + + Additional resources are available that explain [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] layout in greater detail. The [Panels Overview](../controls/panels-overview.md) topic contains more detail about the various elements. The topic [Walkthrough: My first WPF desktop application](../getting-started/walkthrough-my-first-wpf-desktop-application.md) introduces advanced techniques that use layout elements to position components and bind their actions to data sources. + +## See also + +- +- +- +- +- [Panels Overview](../controls/panels-overview.md) +- [Layout](layout.md) +- [WPF Layout Gallery Sample](https://go.microsoft.com/fwlink/?LinkID=160054) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/annotations-overview.md b/dotnet-desktop-guide/framework/wpf/advanced/annotations-overview.md new file mode 100644 index 0000000000..7b4754326b --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/annotations-overview.md @@ -0,0 +1,72 @@ +--- +title: "Annotations Overview" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "highlights [WPF]" + - "documents [WPF], annotations" + - "sticky notes [WPF]" +ms.assetid: 716bf474-29bd-4c74-84a4-8e0744bdad62 +--- +# Annotations Overview +Writing notes or comments on paper documents is such a commonplace activity that we almost take it for granted. These notes or comments are "annotations" that we add to a document to flag information or to highlight items of interest for later reference. Although writing notes on printed documents is easy and commonplace, the ability to add personal comments to electronic documents is typically very limited, if available at all. + + This topic reviews several common types of annotations, specifically sticky notes and highlights, and illustrates how the Microsoft Annotations Framework facilitates these types of annotations in applications through the Windows Presentation Foundation (WPF) document viewing controls. WPF document viewing controls that support annotations include and , as well as controls derived from such as and . + + +## Sticky Notes + A typical sticky note contains information written on a small piece of colored paper that is then "stuck" to a document. Digital sticky notes provide similar functionality for electronic documents, but with the added flexibility to include many other types of content such as typed text, handwritten notes (for example, Tablet PC "ink" strokes), or Web links. + + The following illustration shows some examples of highlight, text sticky note, and ink sticky note annotations. + + ![Highlight, text and ink sticky note annotations.](./media/caf-stickynote.jpg "CAF_StickyNote") + + The following example shows the method that you can use to enable annotation support in your application. + + [!code-csharp[DocViewerAnnotationsXml#DocViewXmlStartAnnotations](~/samples/snippets/csharp/VS_Snippets_Wpf/DocViewerAnnotationsXml/CSharp/Window1.xaml.cs#docviewxmlstartannotations)] + [!code-vb[DocViewerAnnotationsXml#DocViewXmlStartAnnotations](~/samples/snippets/visualbasic/VS_Snippets_Wpf/DocViewerAnnotationsXml/visualbasic/window1.xaml.vb#docviewxmlstartannotations)] + + +## Highlights + People use creative methods to draw attention to items of interest when they mark up a paper document, such as underlining, highlighting, circling words in a sentence, or drawing marks or notations in the margin. Highlight annotations in Microsoft Annotations Framework provide a similar feature for marking up information displayed in WPF document viewing controls. + + The following illustration shows an example of a highlight annotation. + + ![Highlight Annotation](./media/caf-callouts.png "CAF_Callouts") + + Users typically create annotations by first selecting some text or an item of interest, and then right-clicking to display a of annotation options. The following example shows the [!INCLUDE[TLA#tla_xaml](../../../includes/tlasharptla-xaml-md.md)] you can use to declare a with routed commands that users can access to create and manage annotations. + + [!code-xaml[DocViewerAnnotationsXps#CreateDeleteAnnotations](~/samples/snippets/csharp/VS_Snippets_Wpf/DocViewerAnnotationsXps/CSharp/Window1.xaml#createdeleteannotations)] + + +## Data Anchoring + The Annotations Framework binds annotations to the data that the user selects, not just to a position on the display view. Therefore, if the document view changes, such as when the user scrolls or resizes the display window, the annotation stays with the data selection to which it is bound. For example, the following graphic illustrates an annotation that the user has made on a text selection. When the document view changes (scrolls, resizes, scales, or otherwise moves), the highlight annotation moves with the original data selection. + + ![Annotation Data Anchoring](./media/caf-dataanchoring.png "CAF_DataAnchoring") + + +## Matching Annotations with Annotated Objects + You can match annotations with the corresponding annotated objects. For example, consider a simple document reader application that has a comments pane. The comments pane might be a list box that displays the text from a list of annotations that are anchored to a document. If the user selects an item in the list box, then the application brings into view the paragraph in the document that the corresponding annotation object is anchored to. + + The following example demonstrates how to implement the event handler of such a list box that serves as the comments pane. + + [!code-csharp[FlowDocumentAnnotatedViewer#Handler](~/samples/snippets/csharp/VS_Snippets_Wpf/FlowDocumentAnnotatedViewer/CSharp/Window1.xaml.cs#handler)] + [!code-vb[FlowDocumentAnnotatedViewer#Handler](~/samples/snippets/visualbasic/VS_Snippets_Wpf/FlowDocumentAnnotatedViewer/visualbasic/window1.xaml.vb#handler)] + + Another example scenario involves applications that enable the exchange of annotations and sticky notes between document readers through email. This feature enables these applications to navigate the reader to the page that contains the annotation that is being exchanged. + +## See also + +- +- +- +- +- +- +- [Annotations Schema](annotations-schema.md) +- [ContextMenu Overview](../controls/contextmenu-overview.md) +- [Commanding Overview](commanding-overview.md) +- [Flow Document Overview](flow-document-overview.md) +- [How to: Add a Command to a MenuItem](https://docs.microsoft.com/previous-versions/dotnet/netframework-3.5/ms741839(v=vs.90)) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/annotations-schema.md b/dotnet-desktop-guide/framework/wpf/advanced/annotations-schema.md new file mode 100644 index 0000000000..9a9ab2bed4 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/annotations-schema.md @@ -0,0 +1,593 @@ +--- +title: "Annotations Schema" +ms.date: "03/30/2017" +helpviewer_keywords: + - "XML schema definition (XSD)" + - "Microsoft Annotations Framework [WPF]" + - "documents [WPF], annotations" +ms.assetid: a893442b-e220-4603-bf6a-b01fefcb4b37 +--- + +# Annotations Schema + +This topic describes the XML schema definition (XSD) used by the Microsoft Annotations Framework to save and retrieve user annotation data. + +The Annotations Framework serializes annotation data from an internal representation to an XML format. The XML format used for this conversion is described by the Annotations Framework XSD Schema. The schema defines the implementation-independent XML format that can be used to exchange annotation data between applications. + +The Annotations Framework XML schema definition consists of two subschemas + +- The Annotations XML Core Schema (Core Schema). + +- The Annotations XML Base Schema (Base Schema). + +The Core Schema defines the primary XML structure of an . The majority of XML elements defined in the Core Schema correspond to types in the namespace. The Core Schema exposes three extension points where applications can add their own XML data. These extension points include the , , and "Content". (Content elements are provided in the form of an list.) + +The Base Schema described in this topic defines the extensions for the , , and Content types included with the initial Windows Presentation Foundation (WPF) release. + + + +## Annotations XML Core Schema + +The Annotations XML Core Schema defines the XML structure that is used to store objects. + +```xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +``` + + + +## Annotations XML Base Schema + +The Base Schema defines the XML structure for the three abstract elements defined in the Core Schema – , , and . + +```xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +``` + + + +## Sample XML Produced by Annotations XmlStreamStore + +The XML that follows shows the output of an Annotations and the organization of a sample file that contains three annotations - a highlight, a text sticky-note, and an ink stick-note. + +```xml + + + + + + + + + + + + + + + + + + + + + + Denise Smith + + + + + + + + + + + + + + + + + + + + + + + + + + Mike Nash + + + + + + + + + + + + + + + + + + + + + + + + +``` + +## See also + +- +- +- +- +- +- [Annotations Overview](annotations-overview.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/annotations.md b/dotnet-desktop-guide/framework/wpf/advanced/annotations.md new file mode 100644 index 0000000000..aedf61b6af --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/annotations.md @@ -0,0 +1,24 @@ +--- +title: "Annotations" +ms.date: "03/30/2017" +helpviewer_keywords: + - "highlights [WPF]" + - "documents [WPF], annotations" + - "sticky notes [WPF]" +ms.assetid: 232ad0d7-2264-4bed-aae3-10dfde116a9c +--- +# Annotations +[!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] provides document viewing controls that support annotating document content. + +## In This Section + [Annotations Overview](annotations-overview.md) + [Annotations Schema](annotations-schema.md) + +## Reference + + + + +## Related Sections + [Documents in WPF](documents-in-wpf.md) + [Flow Document Overview](flow-document-overview.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/application-startup-time.md b/dotnet-desktop-guide/framework/wpf/advanced/application-startup-time.md new file mode 100644 index 0000000000..d378aed79d --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/application-startup-time.md @@ -0,0 +1,127 @@ +--- +title: "Application Startup Time" +ms.date: "03/30/2017" +helpviewer_keywords: + - "splash screen [WPF], startup time" + - "WPF [WPF], startup time" + - "startup time [WPF]" + - "application startup [WPF]" + - "performance [WPF], startup time" +ms.assetid: f0ec58d8-626f-4d8a-9873-c20f95e08b96 +--- +# Application Startup Time +The amount of time that is required for a WPF application to start can vary greatly. This topic describes various techniques for reducing the perceived and actual startup time for a Windows Presentation Foundation (WPF) application. + +## Understanding Cold Startup and Warm Startup + Cold startup occurs when your application starts for the first time after a system reboot, or when you start your application, close it, and then start it again after a long period of time. When an application starts, if the required pages (code, static data, registry, etc) are not present in the Windows memory manager's standby list, page faults occur. Disk access is required to bring the pages into memory. + + Warm startup occurs when most of the pages for the main common language runtime (CLR) components are already loaded in memory, which saves expensive disk access time. That is why a managed application starts faster when it runs a second time. + +## Implement a Splash Screen + In cases where there is a significant, unavoidable delay between starting an application and displaying the first UI, optimize the perceived startup time by using a *splash screen*. This approach displays an image almost immediately after the user starts the application. When the application is ready to display its first UI, the splash screen fades. Starting in the .NET Framework 3.5 SP1, you can use the class to implement a splash screen. For more information, see [Add a Splash Screen to a WPF Application](../app-development/how-to-add-a-splash-screen-to-a-wpf-application.md). + + You can also implement your own splash screen by using native Win32 graphics. Display your implementation before the method is called. + +## Analyze the Startup Code + Determine the reason for a slow cold startup. Disk I/O may be responsible, but this is not always the case. In general, you should minimize the use of external resources, such as network, Web services, or disk. + + Before you test, verify that no other running applications or services use managed code or WPF code. + + Start your WPF application immediately after a reboot, and determine how long it takes to display. If all subsequent launches of your application (warm startup) are much faster, your cold startup issue is most likely caused by I/O. + + If your application's cold startup issue is not related to I/O, it is likely that your application performs some lengthy initialization or computation, waits for some event to complete, or requires a lot of JIT compilation at startup. The following sections describe some of these situations in more detail. + +## Optimize Module Loading + Use tools such as Process Explorer (Procexp.exe) and Tlist.exe to determine which modules your application loads. The command `Tlist ` shows all the modules that are loaded by a process. + + For example, if you are not connecting to the Web and you see that System.Web.dll is loaded, then there is a module in your application that references this assembly. Check to make sure that the reference is necessary. + + If your application has multiple modules, merge them into a single module. This approach requires less CLR assembly-loading overhead. Fewer assemblies also mean that the CLR maintains less state. + +## Defer Initialization Operations + Consider postponing initialization code until after the main application window is rendered. + + Be aware that initialization may be performed inside a class constructor, and if the initialization code references other classes, it can cause a cascading effect in which many class constructors are executed. + +## Avoid Application Configuration + Consider avoiding application configuration. For example, if an application has simple configuration requirements and has strict startup time goals, registry entries or a simple INI file may be a faster startup alternative. + +## Utilize the GAC + If an assembly is not installed in the Global Assembly Cache (GAC), there are delays caused by hash verification of strong-named assemblies and by Ngen image validation if a native image for that assembly is available on the computer. Strong-name verification is skipped for all assemblies installed in the GAC. For more information, see [Gacutil.exe (Global Assembly Cache Tool)](/dotnet/framework/tools/gacutil-exe-gac-tool). + +## Use Ngen.exe + Consider using the Native Image Generator (Ngen.exe) on your application. Using Ngen.exe means trading CPU consumption for more disk access because the native image generated by Ngen.exe is likely to be larger than the MSIL image. + + To improve the warm startup time, you should always use Ngen.exe on your application, because this avoids the CPU cost of JIT compilation of the application code. + + In some cold startup scenarios, using Ngen.exe can also be helpful. This is because the JIT compiler (mscorjit.dll) does not have to be loaded. + + Having both Ngen and JIT modules can have the worst effect. This is because mscorjit.dll must be loaded, and when the JIT compiler works on your code, many pages in the Ngen images must be accessed when the JIT compiler reads the assemblies' metadata. + +### Ngen and ClickOnce + The way you plan to deploy your application can also make a difference in load time. ClickOnce application deployment does not support Ngen. If you decide to use Ngen.exe for your application, you will have to use another deployment mechanism, such as Windows Installer. + + For more information, see [Ngen.exe (Native Image Generator)](/dotnet/framework/tools/ngen-exe-native-image-generator). + +### Rebasing and DLL Address Collisions + If you use Ngen.exe, be aware that rebasing can occur when the native images are loaded in memory. If a DLL is not loaded at its preferred base address because that address range is already allocated, the Windows loader will load it at another address, which can be a time-consuming operation. + + You can use the Virtual Address Dump (Vadump.exe) tool to check if there are modules in which all the pages are private. If this is the case, the module may have been rebased to a different address. Therefore, its pages cannot be shared. + + For more information about how to set the base address, see [Ngen.exe (Native Image Generator)](/dotnet/framework/tools/ngen-exe-native-image-generator). + +## Optimize Authenticode + Authenticode verification adds to the startup time. Authenticode-signed assemblies have to be verified with the certification authority (CA). This verification can be time consuming, because it can require connecting to the network several times to download current certificate revocation lists. It also makes sure that there is a full chain of valid certificates on the path to a trusted root. This can translate to several seconds of delay while the assembly is being loaded. + + Consider installing the CA certificate on the client computer, or avoid using Authenticode when it is possible. If you know that your application does not need the publisher evidence, you do not have to pay the cost of signature verification. + + Starting in .NET Framework 3.5, there is a configuration option that allows the Authenticode verification to be bypassed. To do this, add the following setting to the app.exe.config file: + +```xml + + + + + +``` + + For more information, see [\ Element](/dotnet/framework/configure-apps/file-schema/runtime/generatepublisherevidence-element). + +## Compare Performance on Windows Vista + The memory manager in Windows Vista has a technology called SuperFetch. SuperFetch analyzes memory usage patterns over time to determine the optimal memory content for a specific user. It works continuously to maintain that content at all times. + + This approach differs from the pre-fetch technique used in Windows XP, which preloads data into memory without analyzing usage patterns. Over time, if the user uses your WPF application frequently on Windows Vista, the cold startup time of your application may improve. + +## Use AppDomains Efficiently + If possible, load assemblies into a domain-neutral code area to make sure that the native image, if one exists, is used in all AppDomains created in the application. + + For the best performance, enforce efficient cross-domain communication by reducing cross-domain calls. When possible, use calls without arguments or with primitive type arguments. + +## Use the NeutralResourcesLanguage Attribute + Use the to specify the neutral culture for the . This approach avoids unsuccessful assembly lookups. + +## Use the BinaryFormatter Class for Serialization + If you must use serialization, use the class instead of the class. The class is implemented in the Base Class Library (BCL) in the mscorlib.dll assembly. The is implemented in the System.Xml.dll assembly, which might be an additional DLL to load. + + If you must use the class, you can achieve better performance if you pre-generate the serialization assembly. + +## Configure ClickOnce to Check for Updates After Startup + If your application uses ClickOnce, avoid network access on startup by configuring ClickOnce to check the deployment site for updates after the application starts. + + If you use the XAML browser application (XBAP) model, keep in mind that ClickOnce checks the deployment site for updates even if the XBAP is already in the ClickOnce cache. For more information, see [ClickOnce Security and Deployment](/visualstudio/deployment/clickonce-security-and-deployment). + +## Configure the PresentationFontCache Service to Start Automatically + The first WPF application to run after a reboot is the PresentationFontCache service. The service caches the system fonts, improves font access, and improves overall performance. There is an overhead in starting the service, and in some controlled environments, consider configuring the service to start automatically when the system reboots. + +## Set Data Binding Programmatically + Instead of using XAML to set the declaratively for the main window, consider setting it programmatically in the method. + +## See also + +- +- +- +- +- [Add a Splash Screen to a WPF Application](../app-development/how-to-add-a-splash-screen-to-a-wpf-application.md) +- [Ngen.exe (Native Image Generator)](/dotnet/framework/tools/ngen-exe-native-image-generator) +- [\ Element](/dotnet/framework/configure-apps/file-schema/runtime/generatepublisherevidence-element) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/attached-events-overview.md b/dotnet-desktop-guide/framework/wpf/advanced/attached-events-overview.md new file mode 100644 index 0000000000..b1f50c8274 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/attached-events-overview.md @@ -0,0 +1,92 @@ +--- +title: "Attached Events Overview" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "handling attached events [WPF]" + - "defining attached events as routed events [WPF]" + - "attached events [WPF], scenarios for" + - "attached events vs. routed events [WPF]" + - "backing attached events with routed events [WPF]" + - "attached events [WPF], definition" +ms.assetid: 2c40eae3-80e4-4a45-ae09-df6c9ab4d91e +--- +# Attached Events Overview + +Extensible Application Markup Language (XAML) defines a language component and type of event called an *attached event*. The concept of an attached event enables you to add a handler for a particular event to an arbitrary element rather than to an element that actually defines or inherits the event. In this case, neither the object potentially raising the event nor the destination handling instance defines or otherwise "owns" the event. + + +## Prerequisites + This topic assumes that you have read [Routed Events Overview](routed-events-overview.md) and [XAML Overview (WPF)](/dotnet/desktop-wpf/fundamentals/xaml). + + +## Attached Event Syntax + Attached events have a XAML syntax and a coding pattern that must be used by the backing code in order to support the attached event usage. + + In XAML syntax, the attached event is specified not just by its event name, but by its owning type plus the event name, separated by a dot (.). Because the event name is qualified with the name of its owning type, the attached event syntax allows any attached event to be attached to any element that can be instantiated. + + For example, the following is the XAML syntax for attaching a handler for a custom `NeedsCleaning` attached event: + + [!code-xaml[WPFAquariumSln#AE](~/samples/snippets/csharp/VS_Snippets_Wpf/WPFAquariumSln/CSharp/WPFAquarium/Window1.xaml#ae)] + + Note the `aqua:` prefix; the prefix is necessary in this case because the attached event is a custom event that comes from a custom mapped xmlns. + + +## How WPF Implements Attached Events + +In WPF, attached events are backed by a field and are routed through the tree after they are raised. Typically, the source of the attached event (the object that raises the event) is a system or service source, and the object that runs the code that raises the event is therefore not a direct part of the element tree. + + +## Scenarios for Attached Events + In WPF, attached events are present in certain feature areas where there is service-level abstraction, such as for the events enabled by the static class or the class. Classes that interact with or use the service can either use the event in the attached event syntax, or they can choose to surface the attached event as a routed event that is part of how the class integrates the capabilities of the service. + + Although WPF defines a number of attached events, the scenarios where you will either use or handle the attached event directly are very limited. Generally, the attached event serves an architecture purpose, but is then forwarded to a non-attached (backed with a CLR event "wrapper") routed event. + + For instance, the underlying attached event can more easily be handled on any given by using on that rather than dealing with attached event syntax either in XAML or code. The attached event serves a purpose in the architecture because it allows for future expansion of input devices. The hypothetical device would only need to raise in order to simulate mouse input, and would not need to derive from to do so. However, this scenario involves code handling of the events, and XAML handling of the attached event is not relevant to this scenario. + + +## Handling an Attached Event in WPF + The process for handling an attached event, and the handler code that you will write, is basically the same as for a routed event. + + In general, a WPF attached event is not very different from a WPF routed event. The differences are how the event is sourced and how it is exposed by a class as a member (which also affects the XAML handler syntax). + + However, as noted earlier, the existing WPF attached events are not particularly intended for handling in WPF. More often, the purpose of the event is to enable a composited element to report a state to a parent element in compositing, in which case the event is usually raised in code and also relies on class handling in the relevant parent class. For instance, items within a are expected to raise the attached event, which is then class handled by the class and then potentially converted by the class into a different routed event, . For more information on routed events and class handling, see [Marking Routed Events as Handled, and Class Handling](marking-routed-events-as-handled-and-class-handling.md). + + +## Defining Your Own Attached Events as Routed Events + If you are deriving from common WPF base classes, you can implement your own attached events by including certain pattern methods in your class and by using utility methods that are already present on the base classes. + + The pattern is as follows: + +- A method __Add*EventName*Handler__ with two parameters. The first parameter is the instance to which the event handler is added. The second parameter is the event handler to add. The method must be `public` and `static`, with no return value. + +- A method __Remove*EventName*Handler__ with two parameters. The first parameter is the instance from which the event handler is removed. The second parameter is the event handler to remove. The method must be `public` and `static`, with no return value. + + The __Add*EventName*Handler__ accessor method facilitates XAML processing when attached event handler attributes are declared on an element. The __Add*EventName*Handler__ and __Remove*EventName*Handler__ methods also enable code access to the event handler store for the attached event. + + This general pattern is not yet precise enough for practical implementation in a framework, because any given XAML reader implementation might have different schemes for identifying underlying events in the supporting language and architecture. This is one of the reasons that WPF implements attached events as routed events; the identifier to use for an event () is already defined by the WPF event system. Also, routing an event is a natural implementation extension on the XAML language-level concept of an attached event. + + The __Add*EventName*Handler__ implementation for a WPF attached event consists of calling the with the routed event and handler as arguments. + + This implementation strategy and the routed event system in general restrict handling for attached events to either derived classes or derived classes, because only those classes have implementations. + + For example, the following code defines the `NeedsCleaning` attached event on the owner class `Aquarium`, using the WPF attached event strategy of declaring the attached event as a routed event. + + [!code-csharp[WPFAquariumSln#AECode](~/samples/snippets/csharp/VS_Snippets_Wpf/WPFAquariumSln/CSharp/WPFAquariumObjects/Class1.cs#aecode)] + [!code-vb[WPFAquariumSln#AECode](~/samples/snippets/visualbasic/VS_Snippets_Wpf/WPFAquariumSln/visualbasic/wpfaquariumobjects/class1.vb#aecode)] + + Note that the method used to establish the attached event identifier field, , is actually the same method that is used to register a non-attached routed event. Attached events and routed events all are registered to a centralized internal store. This event store implementation enables the "events as an interface" conceptual consideration that is discussed in [Routed Events Overview](routed-events-overview.md). + + +## Raising a WPF Attached Event + You do not typically need to raise existing WPF-defined attached events from your code. These events follow the general "service" conceptual model, and service classes such as are responsible for raising the events. + + However, if you are defining a custom attached event based on the WPF model of basing attached events on , you can use to raise an attached event from any or . Raising a routed event (attached or not) requires that you declare a particular element in the element tree as the event source; that source is reported as the caller. Determining which element is reported as the source in the tree is your service's responsibility + +## See also + +- [Routed Events Overview](routed-events-overview.md) +- [XAML Syntax In Detail](xaml-syntax-in-detail.md) +- [XAML and Custom Classes for WPF](xaml-and-custom-classes-for-wpf.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/attached-properties-overview.md b/dotnet-desktop-guide/framework/wpf/advanced/attached-properties-overview.md new file mode 100644 index 0000000000..1de581c3b1 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/attached-properties-overview.md @@ -0,0 +1,145 @@ +--- +title: "Attached Properties Overview" +description: Learn about attached properties in Windows Presentation Foundation, which are global properties settable on any object. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "attached properties [WPF Designer]" +ms.assetid: 75928354-dc01-47e8-a018-8409aec1f32d +--- +# Attached Properties Overview + +An attached property is a concept defined by XAML. An attached property is intended to be used as a type of global property that is settable on any object. In [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)], attached properties are typically defined as a specialized form of dependency property that does not have the conventional property "wrapper". + +## Prerequisites + +This article assumes that you understand dependency properties from the perspective of a consumer of existing dependency properties on [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] classes, and have read the [Dependency Properties Overview](dependency-properties-overview.md). To follow the examples in this article, you should also understand XAML and know how to write WPF applications. + +## Why Use Attached Properties + +One purpose of an attached property is to allow different child elements to specify unique values for a property that's defined in a parent element. A specific application of this scenario is having child elements inform the parent element of how they are to be presented in the [!INCLUDE[TLA#tla_ui](../../../includes/tlasharptla-ui-md.md)]. One example is the property. The property is created as an attached property because it is designed to be set on elements that are contained within a rather than on itself. The class defines the static field named , and then provides the and methods as public accessors for the attached property. + +## Attached Properties in XAML + +In XAML, you set attached properties by using the syntax *AttachedPropertyProvider*.*PropertyName* + +The following is an example of how you can set in XAML: + +[!code-xaml[PropertiesOvwSupport#APBasicUsage](~/samples/snippets/csharp/VS_Snippets_Wpf/PropertiesOvwSupport/CSharp/page4.xaml#apbasicusage)] + +The usage is somewhat similar to a static property; you always reference the type that owns and registers the attached property, rather than referring to any instance specified by name. + +Also, because an attached property in XAML is an attribute that you set in markup, only the set operation has any relevance. You cannot directly get a property in XAML, although there are some indirect mechanisms for comparing values, such as triggers in styles (for details, see [Styling and Templating](/dotnet/desktop-wpf/fundamentals/styles-templates-overview)). + +### Attached Property Implementation in WPF + +In [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)], most of the UI-related attached properties on WPF types are implemented as dependency properties. Attached properties are a XAML concept, whereas dependency properties are a WPF concept. Because WPF attached properties are dependency properties, they support dependency property concepts such as property metadata, and default values from that property metadata. + +## How Attached Properties Are Used by the Owning Type + +Although attached properties are settable on any object, that does not automatically mean that setting the property will produce a tangible result, or that the value will ever be used by another object. Generally, attached properties are intended so that objects coming from a wide variety of possible class hierarchies or logical relationships can each report common information to the type that defines the attached property. The type that defines the attached property typically follows one of these models: + +- The type that defines the attached property is designed so that it can be the parent element of the elements that will set values for the attached property. The type then iterates its child objects through internal logic against some object tree structure, obtains the values, and acts on those values in some manner. + +- The type that defines the attached property will be used as the child element for a variety of possible parent elements and content models. + +- The type that defines the attached property represents a service. Other types set values for the attached property. Then, when the element that set the property is evaluated in the context of the service, the attached property values are obtained through internal logic of the service class. + +### An Example of a Parent-Defined Attached Property + +The most typical scenario where WPF defines an attached property is when a parent element supports a child element collection, and also implements a behavior where the specifics of the behavior are reported individually for each child element. + + defines the attached property, and has class-level code as part of its rendering logic (specifically, and ). A instance will always check to see whether any of its immediate child elements have set a value for . If so, those values become input for the rendering logic applied to that particular child element. Nested instances each treat their own immediate child element collections, but that behavior is implementation-specific to how processes values. It is theoretically possible to have attached properties that influence elements beyond the immediate parent. If the attached property is set on an element that has no parent element to act upon it, no error or exception is raised. This simply means that a global property value was set, but it has no current parent that could consume the information. + +## Attached Properties in Code + +Attached properties in WPF do not have the typical CLR "wrapper" methods for easy get/set access. This is because the attached property is not necessarily part of the CLR namespace for instances where the property is set. However, a XAML processor must be able to set those values when XAML is parsed. To support an effective attached property usage, the owner type of the attached property must implement dedicated accessor methods in the form **Get_PropertyName_** and **Set_PropertyName_**. These dedicated accessor methods are also useful to get or set the attached property in code. From a code perspective, an attached property is similar to a backing field that has method accessors instead of property accessors, and that backing field can exist on any object rather than needing to be specifically defined. + +The following example shows how you can set an attached property in code. In this example, `myCheckBox` is an instance of the class. + +[!code-csharp[PropertiesOvwSupport#APCode](~/samples/snippets/csharp/VS_Snippets_Wpf/PropertiesOvwSupport/CSharp/page4.xaml.cs#apcode)] +[!code-vb[PropertiesOvwSupport#APCode](~/samples/snippets/visualbasic/VS_Snippets_Wpf/PropertiesOvwSupport/visualbasic/page4.xaml.vb#apcode)] + +Similar to the XAML case, if `myCheckBox` had not already been added as a child element of `myDockPanel` by the fourth line of code, the fifth line of code would not raise an exception, but the property value would not interact with a parent and thus would do nothing. Only a value set on a child element combined with the presence of a parent element will cause an effective behavior in the rendered application. (In this case, you could set the attached property, then attach to the tree. Or you could attach to the tree then set the attached property. Either action order provides the same result.) + +## Attached Property Metadata + +When registering the property, is set to specify characteristics of the property, such as whether the property affects rendering, measurement, and so on. Metadata for an attached property is generally no different than on a dependency property. If you specify a default value in an override to attached property metadata, that value becomes the default value of the implicit attached property on instances of the overriding class. Specifically, your default value is reported if some process queries for the value of an attached property through the `Get` method accessor for that property, specifying an instance of the class where you specified the metadata, and the value for that attached property was otherwise not set. + +If you want to enable property value inheritance on a property, you should use attached properties rather than non-attached dependency properties. For details, see [Property Value Inheritance](property-value-inheritance.md). + +## Custom Attached Properties + +### When to Create an Attached Property + +You might create an attached property when there is a reason to have a property setting mechanism available for classes other than the defining class. The most common scenario for this is layout. Examples of existing layout properties are , , and . The scenario enabled here is that elements that exist as child elements to layout-controlling elements are able to express layout requirements to their layout parent elements individually, each setting a property value that the parent defined as an attached property. + +Another scenario for using an attached property is when your class represents a service, and you want classes to be able to integrate the service more transparently. + +Yet another scenario is to receive Visual Studio WPF Designer support, such as **Properties** window editing. For more information, see [Control Authoring Overview](../controls/control-authoring-overview.md). + +As mentioned before, you should register as an attached property if you want to use property value inheritance. + +### How to Create an Attached Property + +If your class is defining the attached property strictly for use on other types, then the class does not have to derive from . But you do need to derive from if you follow the overall WPF model of having your attached property also be a dependency property. + +Define your attached property as a dependency property by declaring a `public static readonly` field of type . You define this field by using the return value of the method. The field name must match the attached property name, appended with the string `Property`, to follow the established WPF pattern of naming the identifying fields versus the properties that they represent. The attached property provider must also provide static **Get_PropertyName_** and **Set_PropertyName_** methods as accessors for the attached property; failing to do this results in the property system being unable to use your attached property. + +> [!NOTE] +> If you omit the attached property's get accessor, data binding on the property will not work in design tools, such as Visual Studio and Blend for Visual Studio. + +#### The Get Accessor + +The signature for the **Get_PropertyName_** accessor must be: + +`public static object GetPropertyName(object target)` + +- The `target` object can be specified as a more specific type in your implementation. For example, the method types the parameter as , because the attached property is only intended to be set on instances. + +- The return value can be specified as a more specific type in your implementation. For example, the method types it as , because the value can only be set to that enumeration. + +#### The Set Accessor + +The signature for the **Set_PropertyName_** accessor must be: + +`public static void SetPropertyName(object target, object value)` + +- The `target` object can be specified as a more specific type in your implementation. For example, the method types it as , because the attached property is only intended to be set on instances. + +- The `value` object can be specified as a more specific type in your implementation. For example, the method types it as , because the value can only be set to that enumeration. Remember that the value for this method is the input coming from the XAML loader when it encounters your attached property in an attached property usage in markup. That input is the value specified as a XAML attribute value in markup. Therefore there must be type conversion, value serializer, or markup extension support for the type you use, such that the appropriate type can be created from the attribute value (which is ultimately just a string). + +The following example shows the dependency property registration (using the method), as well as the **Get_PropertyName_** and **Set_PropertyName_** accessors. In the example, the attached property name is `IsBubbleSource`. Therefore, the accessors must be named `GetIsBubbleSource` and `SetIsBubbleSource`. + +[!code-csharp[WPFAquariumSln#RegisterAttachedBubbler](~/samples/snippets/csharp/VS_Snippets_Wpf/WPFAquariumSln/CSharp/WPFAquariumObjects/Class1.cs#registerattachedbubbler)] +[!code-vb[WPFAquariumSln#RegisterAttachedBubbler](~/samples/snippets/visualbasic/VS_Snippets_Wpf/WPFAquariumSln/visualbasic/wpfaquariumobjects/class1.vb#registerattachedbubbler)] + +#### Attached Property Attributes + +WPF defines several .NET attributes that are intended to provide information about attached properties to reflection processes, and to typical users of reflection and property information such as designers. Because attached properties have a type of unlimited scope, designers need a way to avoid overwhelming users with a global list of all the attached properties that are defined in a particular technology implementation that uses XAML. The .NET attributes that WPF defines for attached properties can be used to scope the situations where a given attached property should be shown in a properties window. You might consider applying these attributes for your own custom attached properties also. The purpose and syntax of the .NET attributes is described on the appropriate reference pages: + +- + +- + +- + +- + +## Learning More About Attached Properties + +- For more information on creating an attached property, see [Register an Attached Property](how-to-register-an-attached-property.md). + +- For more advanced usage scenarios for dependency properties and attached properties, see [Custom Dependency Properties](custom-dependency-properties.md). + +- You can also register a property as an attached property, and as a dependency property, but then still expose "wrapper" implementations. In this case, the property can be set either on that element, or on any element through the XAML attached property syntax. An example of a property with an appropriate scenario for both standard and attached usages is . + +## See also + +- +- [Dependency Properties Overview](dependency-properties-overview.md) +- [Custom Dependency Properties](custom-dependency-properties.md) +- [XAML Overview (WPF)](/dotnet/desktop-wpf/fundamentals/xaml) +- [Register an Attached Property](how-to-register-an-attached-property.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/base-elements-how-to-topics.md b/dotnet-desktop-guide/framework/wpf/advanced/base-elements-how-to-topics.md new file mode 100644 index 0000000000..b775a60b5b --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/base-elements-how-to-topics.md @@ -0,0 +1,35 @@ +--- +title: "Base Elements How-to Topics" +ms.date: "03/30/2017" +f1_keywords: + - "AutoGeneratedOrientationPage" +helpviewer_keywords: + - "base elements [WPF]" +ms.assetid: 09f3a88d-b132-4505-a8bb-55cbfc6bb55a +--- +# Base Elements How-to Topics +The topics in this section describe how to use the four WPF base elements: , , , and . + +## In This Section + [Make a UIElement Transparent or Semi-Transparent](how-to-make-a-uielement-transparent-or-semi-transparent.md) + [Animate the Size of a FrameworkElement](how-to-animate-the-size-of-a-frameworkelement.md) + [Determine Whether a Freezable Is Frozen](how-to-determine-whether-a-freezable-is-frozen.md) + [Handle a Loaded Event](how-to-handle-a-loaded-event.md) + [Set Margins of Elements and Controls](how-to-set-margins-of-elements-and-controls.md) + [Make a Freezable Read-Only](how-to-make-a-freezable-read-only.md) + [Obtain a Writable Copy of a Read-Only Freezable](how-to-obtain-a-writable-copy-of-a-read-only-freezable.md) + [Flip a UIElement Horizontally or Vertically](how-to-flip-a-uielement-horizontally-or-vertically.md) + [Use a ThicknessConverter Object](how-to-use-a-thicknessconverter-object.md) + [Handle the ContextMenuOpening Event](how-to-handle-the-contextmenuopening-event.md) + +## Reference + + + + + + + + +## Related Sections + [Base Elements](base-elements.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/base-elements-overview.md b/dotnet-desktop-guide/framework/wpf/advanced/base-elements-overview.md new file mode 100644 index 0000000000..b26717bbde --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/base-elements-overview.md @@ -0,0 +1,98 @@ +--- +title: "Base Elements Overview" +ms.date: "03/30/2017" +helpviewer_keywords: + - "base elements [WPF]" +ms.assetid: 2c997092-72c6-4767-bc84-74267f4eee72 +--- +# Base Elements Overview +A high percentage of classes in [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] are derived from four classes which are commonly referred to in the SDK documentation as the base element classes. These classes are , , , and . The class is also related, because it is a common base class of both and + + +## Base Element APIs in WPF Classes + Both and are derived from , through somewhat different pathways. The split at this level deals with how a or are used in a user interface and what purpose they serve in an application. also has in its class hierarchy, which is a class that exposes the lower-level graphics support underlying the [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)]. provides a rendering framework by defining independent rectangular screen regions. In practice, is for elements that will support a larger object model, are intended to render and layout into regions that can be described as rectangular screen regions, and where the content model is deliberately more open, to allow different combinations of elements. does not derive from ; its model is that a would be consumed by something else, such as a reader or viewer that would then interpret the elements and produce the complete for [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] to consume. Certain classes are intended to be content hosts: they provide the hosting and rendering for one or more classes ( is an example of such a class). is used as base class for elements with somewhat smaller object models and that more address the text, information, or document content that might be hosted within a . + +### Framework-Level and Core-Level + serves as the base class for , and serves as the base class for . The reason for this next level of classes is to support a WPF core level that is separate from a WPF framework level, with this division also existing in how the APIs are divided between the PresentationCore and PresentationFramework assemblies. The WPF framework level presents a more complete solution for basic application needs, including the implementation of the layout manager for presentation. The WPF core level provides a way to use much of [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] without taking the overhead of the additional assembly. The distinction between these levels very rarely matters for most typical application development scenarios, and in general you should think of the [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] APIs as a whole and not concern yourself with the difference between WPF framework level and WPF core level. You might need to know about the level distinctions if your application design chooses to replace substantial quantities of WPF framework level functionality, for instance if your overall solution already has its own implementations of [!INCLUDE[TLA#tla_ui](../../../includes/tlasharptla-ui-md.md)] composition and layout. + + +## Choosing Which Element to Derive From + The most practical way to create a custom class that extends [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] is by deriving from one of the [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] classes where you get as much as possible of your desired functionality through the existing class hierarchy. This section lists the functionality that comes with three of the most important element classes to help you decide which class to inherit from. + + If you are implementing a control, which is really one of the more common reasons for deriving from a [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] class, you probably want to derive from a class that is a practical control, a control family base class, or at least from the base class. For some guidance and practical examples, see [Control Authoring Overview](../controls/control-authoring-overview.md). + + If you are not creating a control and need to derive from a class that is higher in the hierarchy, the following sections are intended as a guide for what characteristics are defined in each base element class. + + If you create a class that derives from , you inherit the following functionality: + +- and support, and general property system support. + +- Ability to use dependency properties and attached properties that are implemented as dependency properties. + + If you create a class that derives from , you inherit the following functionality in addition to that provided by : + +- Basic support for animated property values. For more information, see [Animation Overview](../graphics-multimedia/animation-overview.md). + +- Basic input event support, and commanding support. For more information, see [Input Overview](input-overview.md) and [Commanding Overview](commanding-overview.md). + +- Virtual methods that can be overridden to provide information to a layout system. + + If you create a class that derives from , you inherit the following functionality in addition to that provided by : + +- Support for styling and storyboards. For more information, see and [Storyboards Overview](../graphics-multimedia/storyboards-overview.md). + +- Support for data binding. For more information, see [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview). + +- Support for dynamic resource references. For more information, see [XAML Resources](/dotnet/desktop-wpf/fundamentals/xaml-resources-define). + +- Property value inheritance support, and other flags in the metadata that help report conditions about properties to framework services such as data binding, styles, or the framework implementation of layout. For more information, see [Framework Property Metadata](framework-property-metadata.md). + +- The concept of the logical tree. For more information, see [Trees in WPF](trees-in-wpf.md). + +- Support for the practical WPF framework-level implementation of the layout system, including an override that can detect changes to properties that influence layout. + + If you create a class that derives from , you inherit the following functionality in addition to that provided by : + +- Support for animations. For more information, see [Animation Overview](../graphics-multimedia/animation-overview.md). + +- Basic input event support, and commanding support. For more information, see [Input Overview](input-overview.md) and [Commanding Overview](commanding-overview.md). + + If you create a class that derives from , you get the following functionality in addition to that provided by : + +- Support for styling and storyboards. For more information, see and [Animation Overview](../graphics-multimedia/animation-overview.md). + +- Support for data binding. For more information, see [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview). + +- Support for dynamic resource references. For more information, see [XAML Resources](/dotnet/desktop-wpf/fundamentals/xaml-resources-define). + +- Property value inheritance support, and other flags in the metadata that help report conditions about properties to framework services like data binding, styles, or the framework implementation of layout. For more information, see [Framework Property Metadata](framework-property-metadata.md). + +- You do not inherit access to layout system modifications (such as ). Layout system implementations are only available on . However, you inherit an override that can detect changes to properties that influence layout and report these to any content hosts. + + Content models are documented for a variety of classes. The content model for a class is one possible factor you should consider if you want to find an appropriate class to derive from. For more information, see [WPF Content Model](../controls/wpf-content-model.md). + + +## Other Base Classes + +### DispatcherObject + provides support for the [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] threading model and enables all objects created for [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] applications to be associated with a . Even if you do not derive from , , or , you should consider deriving from in order to get this threading model support. For more information, see [Threading Model](threading-model.md). + +### Visual + implements the concept of a 2D object that generally requires visual presentation in a roughly rectangular region. The actual rendering of a happens in other classes (it is not self-contained), but the class provides a known type that is used by rendering processes at various levels. implements hit testing, but it does not expose events that report hit-testing positives (these are in ). For more information, see [Visual Layer Programming](../graphics-multimedia/visual-layer-programming.md). + +### Freezable + simulates immutability in a mutable object by providing the means to generate copies of the object when an immutable object is required or desired for performance reasons. The type provides a common basis for certain graphics elements such as geometries and brushes, as well as animations. Notably, a is not a ; it can hold properties that become subproperties when the is applied to fill a property value of another object, and those subproperties might affect rendering. For more information, see [Freezable Objects Overview](freezable-objects-overview.md). + + + + is a derived class that specifically adds the animation control layer and some utility members so that currently animated properties can be distinguished from nonanimated properties. + +### Control + is the intended base class for the type of object that is variously termed a control or component, depending on the technology. In general, [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] control classes are classes that either directly represent a UI control or participate closely in control composition. The primary functionality that enables is control templating. + +## See also + +- +- [Dependency Properties Overview](dependency-properties-overview.md) +- [Control Authoring Overview](../controls/control-authoring-overview.md) +- [WPF Architecture](wpf-architecture.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/base-elements.md b/dotnet-desktop-guide/framework/wpf/advanced/base-elements.md new file mode 100644 index 0000000000..438aef7f54 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/base-elements.md @@ -0,0 +1,37 @@ +--- +title: "Base Elements" +ms.date: "03/30/2017" +f1_keywords: + - "AutoGeneratedOrientationPage" +helpviewer_keywords: + - "base elements [WPF]" +ms.assetid: 55034aa5-3c1d-442a-8293-f4692d8ea6ae +--- +# Base Elements +Four key classes--, , , and --implement a substantial percentage of the common element functionality available in WPF programming. These four classes are referred to in this SDK as the base element classes. + +## In This Section + [Base Elements Overview](base-elements-overview.md) + [Freezable Objects Overview](freezable-objects-overview.md) + [Alignment, Margins, and Padding Overview](alignment-margins-and-padding-overview.md) + [How-to Topics](base-elements-how-to-topics.md) + +## Reference + + + + + + + + +## Related Sections + [WPF Architecture](wpf-architecture.md) + [XAML in WPF](xaml-in-wpf.md) + [Element Tree and Serialization](element-tree-and-serialization.md) + [Properties](properties-wpf.md) + [Events](events-wpf.md) + [Input](input-wpf.md) + [Resources](resources-wpf.md) + [Styling and Templating](/dotnet/desktop-wpf/fundamentals/styles-templates-overview) + [Threading Model](threading-model.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/bidirectional-features-in-wpf-overview.md b/dotnet-desktop-guide/framework/wpf/advanced/bidirectional-features-in-wpf-overview.md new file mode 100644 index 0000000000..4cc575bd7d --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/bidirectional-features-in-wpf-overview.md @@ -0,0 +1,266 @@ +--- +title: Bidirectional features overview +ms.date: "03/30/2017" +helpviewer_keywords: + - "Span elements [WPF]" + - "bidirectional features [WPF]" +ms.assetid: fd850e25-7dba-408c-b521-8873e51dc968 +--- +# Bidirectional Features in WPF Overview + +Unlike any other development platform, [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] has many features that support rapid development of bidirectional content, for example, mixed left to right and right to left data in the same document. At the same time, [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] creates an excellent experience for users who require bidirectional features such as Arabic and Hebrew speaking users. + +The following sections explain many bidirectional features together with examples illustrating how to achieve the best display of bidirectional content. Most of the samples use XAML, though you can easily apply the concepts to C# or Microsoft Visual Basic code. + + + +## FlowDirection + +The basic property that defines the content flow direction in a [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] application is . This property can be set to one of two enumeration values, or . The property is available to all [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] elements that inherit from . + +The following examples set the flow direction of a element. + +**Left-to-right flow direction** + +[!code-xaml[LTRRTL#LTR](~/samples/snippets/csharp/VS_Snippets_Wpf/LTRRTL/CS/Pane1.xaml#ltr)] + +**Right-to-left flow direction** + +[!code-xaml[LTRRTL#RTL](~/samples/snippets/csharp/VS_Snippets_Wpf/LTRRTL/CS/Pane1.xaml#rtl)] + +The following graphic shows how the previous code renders. + +![Graphic that illustrates the different flow directions.](./media/bidirectional-features-in-wpf-overview/left-right-right-left.png) + +An element within a [!INCLUDE[TLA#tla_ui](../../../includes/tlasharptla-ui-md.md)] tree will inherit the from its container. In the following example, the is inside a , which resides in a . Setting the for the implies setting it for the and as well. + +The following example demonstrates setting . + +[!code-xaml[FlowDirection#FlowDirection](~/samples/snippets/csharp/VS_Snippets_Wpf/FlowDirection/CS/Window1.xaml#flowdirection)] + +The top level has a , so all elements contained within it also inherit the same . For an element to override a specified it must add an explicit direction change such as the second in the previous example which changes to . When no is defined, the default applies. + +The following graphic shows the output of the previous example: + +![Graphic that illustrates the explicit flow direction change.](./media/bidirectional-features-in-wpf-overview/explicit-direction-change.png) + + + +## FlowDocument + +Many development platforms such as HTML, Win32 and Java provide special support for bidirectional content development. Markup languages such as HTML give content writers the necessary markup to display text in any required direction, for example the HTML 4.0 tag, "dir" that takes "rtl" or "ltr" as values. This tag is similar to the property, but the property works in a more advanced way to layout textual content and can be used for content other than text. + +In [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)], a is a versatile [!INCLUDE[TLA2#tla_ui](../../../includes/tla2sharptla-ui-md.md)] element that can host a combination of text, tables, images and other elements. The samples in the following sections use this element. + +Adding text to a can be done in more that one way. A simple way to do so is through a which is a block-level element used to group content such as text. To add text to inline-level elements the samples use and . is an inline-level flow content element used for grouping other inline elements, while a is an inline-level flow content element intended to contain a run of unformatted text. A can contain multiple elements. + +The first document example contains a document that has a number of network share names; for example `\\server1\folder\file.ext`. Whether you have this network link in an Arabic or English document, you always want it to appear in the same way. The following graphic illustrates using the Span element and shows the link in an Arabic document: + +![Graphic that illustrates using the Span element.](./media/bidirectional-features-in-wpf-overview/flow-direction-span-element.png "FlowDocument") + +Because the text is , all special characters, such as the "\\", separate the text in a right to left order. That results in the link not being shown in the correct order, therefore to solve the problem, the text must be embedded to preserve a separate flowing . Instead of having a separate for each language, a better way to solve the problem is to embed the less frequently used English text into a larger Arabic . + +The following graphic illustrates this by using the Run element embedded in a Span element: + +![Graphic that illustrates the Run element embedded in a Span element.](./media/bidirectional-features-in-wpf-overview/embedded-span-element.png) + +The following example demonstrates using and elements in documents. + +[!code-xaml[RunSpan#RunSpan](~/samples/snippets/csharp/VS_Snippets_Wpf/RunSpan/CS/Window1.xaml#runspan)] + + + +## Span Elements + +The element works as a boundary separator between texts with different flow directions. Even elements with the same flow direction are considered to have different bidirectional scopes which means that the elements are ordered in the container’s , only the content within the element follows the of the . + +The following graphic shows the flow direction of several elements. + +![Graphic that illustrates text blocks with different flow directions.](./media/bidirectional-features-in-wpf-overview/flow-direction-text-blocks.png) + +The following example shows how to use the and elements to produce the results shown in the previous graphic. + +[!code-xaml[Span#Span](~/samples/snippets/csharp/VS_Snippets_Wpf/Span/CS/Window1.xaml#span)] + +In the elements in the sample, the elements are laid out according to the of their parents, but the text within each element flows according to its own . This is applicable to Latin and Arabic – or any other language. + +### Adding xml:lang + +The following graphic shows another example that uses numbers and arithmetic expressions, such as `"200.0+21.4=221.4"`. Notice that only the is set. + +![Graphic that displays numbers using only FlowDirection.](./media/bidirectional-features-in-wpf-overview/numbers-flow-right-left.png) + +Users of this application will be disappointed by the output, even though the is correct the numbers are not shaped as Arabic numbers should be shaped. + +XAML elements can include an XML attribute (`xml:lang`) that defines the language of each element. XAML also supports a XML language principle whereby `xml:lang` values applied to parent elements in the tree are used by child elements. In the previous example, because a language was not defined for the element or any of its top level elements, the default `xml:lang` was used, which is `en-US` for XAML. The internal number shaping algorithm of [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] selects numbers in the corresponding language – in this case English. To make the Arabic numbers render correctly `xml:lang` needs to be set. + +The following graphic shows the example with `xml:lang` added. + +![Graphic that illustrates Arabic numbers that flow from right to left.](./media/bidirectional-features-in-wpf-overview/arabic-numbers-flow-right-left.png) + +The following example adds `xml:lang` to the application. + +[!code-xaml[LangAttribute#LangAttribute](~/samples/snippets/csharp/VS_Snippets_Wpf/LangAttribute/CS/Window1.xaml#langattribute)] + +Be aware that many languages have different `xml:lang` values depending on the targeted region, for example, `"ar-SA"` and `"ar-EG"` represent two variations of Arabic. The previous examples illustrate that you need to define both the `xml:lang` and values. + + + +## FlowDirection with Non-text Elements + + defines not only how text flows in a textual element but also the flow direction of almost every other [!INCLUDE[TLA2#tla_ui](../../../includes/tla2sharptla-ui-md.md)] element. The following graphic shows a that uses a horizontal to draw its background with a left to right gradient. + +![Graphic that shows a toolbar with a left to right gradient.](./media/bidirectional-features-in-wpf-overview/toolbar-left-right-gradient.png) + +After setting the to , not only the buttons are arranged from right to left, but even the realigns its offsets to flow from right to left. + +The following graphic shows the realignment of the . + +![Graphic that shows a toolbar with a right to left gradient.](./media/bidirectional-features-in-wpf-overview/toolbar-right-left-gradient.png) + +The following example draws a . (To draw it left to right, remove the attribute on the . + +[!code-xaml[Gradient#Gradient](~/samples/snippets/csharp/VS_Snippets_Wpf/Gradient/CS/Window1.xaml#gradient)] + + + +### FlowDirection Exceptions + +There are a few cases where does not behave as expected. This section covers two of these exceptions. + +**Image** + +An represents a control that displays an image. In XAML it can be used with a property that defines the uniform resource identifier (URI) of the to display. + +Unlike other [!INCLUDE[TLA2#tla_ui](../../../includes/tla2sharptla-ui-md.md)] elements, an does not inherit the from the container. However, if the is set explicitly to , an is displayed flipped horizontally. This is implemented as a convenient feature for developers of bidirectional content; because in some cases, horizontally flipping the image produces the desired effect. + +The following graphic shows a flipped . + +![Graphic that illustrates a flipped image.](./media/bidirectional-features-in-wpf-overview/flipped-image-example.png) + +The following example demonstrates that the fails to inherit the from the that contains it. + +> [!NOTE] +> You must have a file named **ms_logo.jpg** on your C:\ drive to run this example. + +[!code-xaml[Image#Image](~/samples/snippets/csharp/VS_Snippets_Wpf/Image/CS/Window1.xaml#image)] + +> [!NOTE] +> Included in the download files is an **ms_logo.jpg** file. The code assumes that the .jpg file is not inside your project but somewhere on the C:\ drive. You must copy the .jpg from the project files to your C:\ drive or change the code to look for the file inside the project. To do this change `Source="file://c:/ms_logo.jpg"` to `Source="ms_logo.jpg"`. + +**Paths** + +In addition to an , another interesting element is . A Path is an object that can draw a series of connected lines and curves. It behaves in a manner similar to an regarding its ; for example its is a horizontal mirror of its one. However, unlike an , inherits its from the container and one does not need to specify it explicitly. + +The following example draws a simple arrow using 3 lines. The first arrow inherits the flow direction from the so that its start and end points are measured from a root on the right side. The second arrow which has an explicit also starts on the right side. However, the third arrow has its starting root on the left side. For more information on drawing see and . + +[!code-xaml[Paths#Paths](~/samples/snippets/csharp/VS_Snippets_Wpf/Paths/CS/Window1.xaml#paths)] + +The following graphic shows the output of the previous example with arrows drawn using the `Path` element: + +![Graphic that illustrates arrows drawn using the Path element.](./media/bidirectional-features-in-wpf-overview/arrows-drawn-path-element.png) + +The and are two examples of a how [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] uses . Beside laying out [!INCLUDE[TLA2#tla_ui](../../../includes/tla2sharptla-ui-md.md)] elements in a specific direction within a container, can be used with elements such as which renders ink on a surface, , . Whenever you need a right to left behavior for your content that mimics a left to right behavior, or vice versa, [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] provides that capability. + + + +## Number Substitution + +Historically, Windows has supported number substitution by allowing the representation of different cultural shapes for the same digits while keeping the internal storage of these digits unified among different locales, for example numbers are stored in their well known hexadecimal values, 0x40, 0x41, but displayed according to the selected language. + +This has allowed applications to process numerical values without the need to convert them from one language to another, for example a user can open an Microsoft Excel spreadsheet in a localized Arabic Windows and see the numbers shaped in Arabic, but open it in a European version of Windows and see European representation of the same numbers. This is also necessary for other symbols such as comma separators and percentage symbol because they usually accompany numbers in the same document. + +[!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] continues the same tradition, and adds further support for this feature that allows more user control over when and how substitution is used. While this feature is designed for any language, it is particularly useful in bidirectional content where shaping digits for a specific language is usually a challenge for application developers because of the various cultures an application might run on. + +The core property controlling how number substitution works in [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] is the dependency property. The class specifies how numbers in text are to be displayed. It has three public properties that define its behavior. The following is a summary of each of the properties: + +**CultureSource:** + +This property specifies how the culture for numbers is determined. It takes one of three enumeration values. + +- Override: Number culture is that of property. + +- Text: Number culture is the culture of the text run. In markup, this would be `xml:lang`, or its alias `Language` property ( or ). Also, it is the default for classes deriving from . Such classes include , , and so forth. + +- User: Number culture is the culture of the current thread. This property is the default for all subclasses of such as , and . + +**CultureOverride**: + +The property is used only if the property is set to and is ignored otherwise. It specifies the number culture. A value of `null`, the default value, is interpreted as en-US. + +**Substitution**: + +This property specifies the type of number substitution to perform. It takes one of the following enumeration values: + +- : The substitution method is determined based on the number culture's property. This is the default. + +- : If the number culture is an Arabic or Persian culture, it specifies that the digits depend on the context. + +- : Numbers are always rendered as European digits. + +- : Numbers are rendered using the national digits for the number culture, as specified by the culture's . + +- : Numbers are rendered using the traditional digits for the number culture. For most cultures, this is the same as . However, results in Latin digits for some Arabic cultures, whereas this value results in Arabic digits for all Arabic cultures. + +What do those values mean for a bidirectional content developer? In most cases, the developer might need only to define and the language of each textual [!INCLUDE[TLA2#tla_ui](../../../includes/tla2sharptla-ui-md.md)] element, for example `Language="ar-SA"` and the logic takes care of displaying the numbers according to the correct [!INCLUDE[TLA2#tla_ui](../../../includes/tla2sharptla-ui-md.md)]. The following example demonstrates using Arabic and English numbers in a [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] application running in an Arabic version of Windows. + +[!code-xaml[Numbers#Numbers](~/samples/snippets/csharp/VS_Snippets_Wpf/Numbers/CS/Window1.xaml#numbers)] + +The following graphic shows the output of the previous sample if you're running in an Arabic version of Windows with Arabic and English numbers displayed: + +![Graphic that shows Arabic and English numbers.](./media/bidirectional-features-in-wpf-overview/arabic-english-numbers.png) + +The was important in this case because setting the to instead would have yielded European digits. The following sections discuss how to have a unified display of digits throughout your document. If this example is not running on Arabic Windows, all the digits display as European digits. + +**Defining Substitution Rules** + +In a real application you might need to set the Language programmatically. For example, you want to set the `xml:lang` attribute to be the same as the one used by the system’s [!INCLUDE[TLA2#tla_ui](../../../includes/tla2sharptla-ui-md.md)], or maybe change the language depending on the application state. + +If you want to make changes based on the application's state, make use of other features provided by [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)]. + +First, set the application component’s `NumberSubstitution.CultureSource="Text"`. Using this setting makes sure that the settings do not come from the [!INCLUDE[TLA2#tla_ui](../../../includes/tla2sharptla-ui-md.md)] for text elements that have "User" as the default, such as . + +For example: + +```xaml + + 1234+5679=6913 + +``` + +In the corresponding C# code, set the `Language` property, for example, to `"ar-SA"`. + +```csharp +text1.Language = System.Windows.Markup.XmlLanguage.GetLanguage("ar-SA"); +``` + +If you need to set the `Language` property to the current user’s UI language use the following code. + +```csharp +text1.Language = System.Windows.Markup.XmlLanguage.GetLanguage(System.Globalization.CultureInfo.CurrentUICulture.IetfLanguageTag); +``` + + represents the current culture used by the current thread at run time. + +Your final XAML example should be similar to the following example. + +[!code-xaml[Numbers2#Numbers2](~/samples/snippets/csharp/VS_Snippets_Wpf/Numbers2/CS/Window1.xaml#numbers2)] + +Your final C# example should be similar to the following. + +[!code-csharp[NumbersCSharp#NumbersCSharp](~/samples/snippets/csharp/VS_Snippets_Wpf/NumbersCSharp/CSharp/Window1.xaml.cs#numberscsharp)] + +The following graphic shows what the window looks like for either programming language, displaying Arabic numbers: + +![Graphic that displays Arabic numbers.](./media/bidirectional-features-in-wpf-overview/displays-arabic-numbers.png) + +**Using the Substitution Property** + +The way number substitution works in [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] depends on both the Language of the text element and its . If the is left to right, then European digits are rendered. However if it is preceded by Arabic text, or has the language set to "ar" and the is , Arabic digits are rendered instead. + +In some cases, however, you might want to create a unified application, for example European digits for all users. Or Arabic digits in cells with a specific . One easy way to do that is using the property. + +In the following example, the first does not have the property set, so the algorithm displays Arabic digits as expected. However in the second , the substitution is set to European overriding the default substitution for Arabic numbers, and European digits are displayed. + +[!code-xaml[Numbers3#Numbers3](~/samples/snippets/csharp/VS_Snippets_Wpf/Numbers3/CS/Window1.xaml#numbers3)] diff --git a/dotnet-desktop-guide/framework/wpf/advanced/binding-markup-extension.md b/dotnet-desktop-guide/framework/wpf/advanced/binding-markup-extension.md new file mode 100644 index 0000000000..64379147af --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/binding-markup-extension.md @@ -0,0 +1,124 @@ +--- +title: "Binding Markup Extension" +ms.date: "03/30/2017" +f1_keywords: + - "Binding" +helpviewer_keywords: + - "Binding markup extensions [WPF]" + - "XAML [WPF], Binding markup extension" +ms.assetid: 83d6e2a4-1b0c-4fc8-bd96-b5e98800ab63 +--- +# Binding Markup Extension +Defers a property value to be a data-bound value, creating an intermediate expression object and interpreting the data context that applies to the element and its binding at run time. + +## Binding Expression Usage + +```xaml + +-or- + +-or- + +-or + +``` + +## Syntax Notes + In these syntaxes, the `[]` and `*` are not literals. They are part of a notation to indicate that zero or more *bindProp*`=`*value* pairs can be used, with a `,` separator between them and preceding *bindProp*`=`*value* pairs. + + Any of the properties listed in the "Binding Properties That Can Be Set with the Binding Extension" section could instead be set using attributes of a object element. However, that is not truly the markup extension usage of , it is just the general XAML processing of attributes that set properties of the CLR class. In other words, `` is an equivalent syntax for attributes of object element usage instead of a `Binding` expression usage. To learn about the XAML attribute usage of specific properties of , see the "XAML Attribute Usage" section of the relevant property of in the .NET Framework Class Library. + +## XAML Values + +||| +|-|-| +|`bindProp1, bindPropN`|The name of the or property to set. Not all properties can be set with the `Binding` extension, and some properties are settable within a `Binding` expression only by using further nested markup extensions. See "Binding Properties That Can Be Set with the Binding Extension" section.| +|`value1, valueN`|The value to set the property to. The handling of the attribute value is ultimately specific to the type and logic of the specific property being set.| +|`path`|The path string that sets the implicit property. See also [PropertyPath XAML Syntax](propertypath-xaml-syntax.md).| + +## Unqualified {Binding} + The `{Binding}` usage shown in "Binding Expression Usage" creates a object with default values, which includes an initial of `null`. This is still useful in many scenarios, because the created might be relying on key data binding properties such as and being set in the run-time data context. For more information on the concept of data context, see [Data Binding](/dotnet/desktop-wpf/data/data-binding-overview). + +## Implicit Path + The `Binding` markup extension uses as a conceptual "default property", where `Path=` does not need to appear in the expression. If you specify a `Binding` expression with an implicit path, the implicit path must appear first in the expression, prior to any other `bindProp`=`value` pairs where the property is specified by name. For example: `{Binding PathString}`, where `PathString` is a string that is evaluated to be the value of in the created by the markup extension usage. You can append an implicit path with other named properties after the comma separator, for example, `{Binding LastName, Mode=TwoWay}`. + +## Binding Properties That Can Be Set with the Binding Extension + The syntax shown in this topic uses the generic `bindProp`=`value` approximation, because there are many read/write properties of or that can be set through the `Binding` markup extension / expression syntax. They can be set in any order, with the exception of an implicit . (You do have the option to explicitly specify `Path=`, in which case it can be set in any order). Basically, you can set zero or more of the properties in the list below, using `bindProp`=`value` pairs separated by commas. + + Several of these property values require object types that do not support a native type conversion from a text syntax in XAML, and thus require markup extensions in order to be set as an attribute value. Check the XAML Attribute Usage section in the .NET Framework Class Library for each property for more information; the string you use for XAML attribute syntax with or without further markup extension usage is basically the same as the value you specify in a `Binding` expression, with the exception that you do not place quotation marks around each `bindProp`=`value` in the `Binding` expression. + +- : a string that identifies a possible binding group. This is a relatively advanced binding concept; see reference page for . + +- : Boolean, can be either `true` or `false`. The default is `false`. + +- : can be set as a `bindProp`=`value` string in the expression, but to do so requires an object reference for the value, such as a [StaticResource Markup Extension](staticresource-markup-extension.md). The value in this case is an instance of a custom converter class. + +- : settable in the expression as a standards-based identifier; see the reference topic for . + +- : can be set as a `bindProp`=`value` string in the expression, but this is dependent on the type of the parameter being passed. If passing a reference type for the value, this usage requires an object reference such as a nested [StaticResource Markup Extension](staticresource-markup-extension.md). + +- : mutually exclusive versus and ; each of these binding properties represents a particular binding methodology. See [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview). + +- : can be set as a `bindProp`=`value` string in the expression, but this is dependent on the type of the value being passed. If passing a reference type, requires an object reference such as a nested [StaticResource Markup Extension](staticresource-markup-extension.md). + +- : Boolean, can be either `true` or `false`. The default is `false`. + +- : *value* is a constant name from the enumeration. For example, `{Binding Mode=OneWay}`. + +- : Boolean, can be either `true` or `false`. The default is `false`. + +- : Boolean, can be either `true` or `false`. The default is `false`. + +- : Boolean, can be either `true` or `false`. The default is `false`. + +- : a string that describes a path into a data object or a general object model. The format provides several different conventions for traversing an object model that cannot be adequately described in this topic. See [PropertyPath XAML Syntax](propertypath-xaml-syntax.md). + +- : mutually exclusive versus with and ; each of these binding properties represents a particular binding methodology. See [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview). Requires a nested [RelativeSource MarkupExtension](relativesource-markupextension.md) usage to specify the value. + +- : mutually exclusive versus and ; each of these binding properties represents a particular binding methodology. See [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview). Requires a nested extension usage, typically a [StaticResource Markup Extension](staticresource-markup-extension.md) that refers to an object data source from a keyed resource dictionary. + +- : a string that describes a string format convention for the bound data. This is a relatively advanced binding concept; see reference page for . + +- : can be set as a `bindProp`=`value` string in the expression, but this is dependent on the type of the parameter being passed. If passing a reference type for the value, requires an object reference such as a nested [StaticResource Markup Extension](staticresource-markup-extension.md). + +- : *value* is a constant name from the enumeration. For example, `{Binding UpdateSourceTrigger=LostFocus}`. Specific controls potentially have different default values for this binding property. See . + +- : Boolean, can be either `true` or `false`. The default is `false`. See Remarks. + +- : Boolean, can be either `true` or `false`. The default is `false`. See Remarks. + +- : a string that describes a path into the XMLDOM of an XML data source. See [Bind to XML Data Using an XMLDataProvider and XPath Queries](../data/how-to-bind-to-xml-data-using-an-xmldataprovider-and-xpath-queries.md). + + The following are properties of that cannot be set using the `Binding` markup extension/`{Binding}` expression form. + +- : this property expects a reference to a callback implementation. Callbacks/methods other than event handlers cannot be referenced in XAML syntax. + +- : the property takes a generic collection of objects. This could be expressed as a property element in a object element, but has no readily available attribute-parsing technique for usage in a `Binding` expression. See reference topic for . + +- + +## Remarks + +> [!IMPORTANT] +> In terms of dependency property precedence, a `Binding` expression is equivalent to a locally set value. If you set a local value for a property that previously had a `Binding` expression, the `Binding` is completely removed. For details, see [Dependency Property Value Precedence](dependency-property-value-precedence.md). + + Describing data binding at a basic level is not covered in this topic. See [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview). + +> [!NOTE] +> and do not support a [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] extension syntax. You would instead use property elements. See reference topics for and . + + Boolean values for XAML are case insensitive. For example you could specify either `{Binding NotifyOnValidationError=true}` or `{Binding NotifyOnValidationError=True}`. + + Bindings that involve data validation are typically specified by an explicit `Binding` element rather than as a `{Binding ...}` expression, and setting or in an expression is uncommon. This is because the companion property cannot be readily set in the expression form. For more information, see [Implement Binding Validation](../data/how-to-implement-binding-validation.md). + + `Binding` is a markup extension. Markup extensions are typically implemented when there is a requirement to escape attribute values to be other than literal values or handler names, and the requirement is more global than type converters attributed on certain types or properties. All markup extensions in XAML use the `{` and `}` characters in their attribute syntax, which is the convention by which a XAML processor recognizes that a markup extension must process the string contents. For more information, see [Markup Extensions and WPF XAML](markup-extensions-and-wpf-xaml.md). + + `Binding` is an atypical markup extension in that the class that implements the extension functionality for WPF's XAML implementation also implements several other methods and properties that are not related to XAML. The other members are intended to make a more versatile and self-contained class that can address many data binding scenarios in addition to functioning as a XAML markup extension. + +## See also + +- +- [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview) +- [XAML Overview (WPF)](/dotnet/desktop-wpf/fundamentals/xaml) +- [Markup Extensions and WPF XAML](markup-extensions-and-wpf-xaml.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/cleartype-overview.md b/dotnet-desktop-guide/framework/wpf/advanced/cleartype-overview.md new file mode 100644 index 0000000000..81db869a91 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/cleartype-overview.md @@ -0,0 +1,64 @@ +--- +title: "ClearType Overview" +ms.date: "03/30/2017" +helpviewer_keywords: + - "typography [WPF], ClearType technology" + - "ClearType [WPF], technology" +ms.assetid: 7e2392e0-75dc-463d-a716-908772782431 +--- +# ClearType Overview +This topic provides an overview of the Microsoft ClearType technology found in the [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)]. + + +## Technology Overview + ClearType is a software technology developed by Microsoft that improves the readability of text on existing LCDs (Liquid Crystal Displays), such as laptop screens, Pocket PC screens and flat panel monitors. ClearType works by accessing the individual vertical color stripe elements in every pixel of an LCD screen. Before ClearType, the smallest level of detail that a computer could display was a single pixel, but with ClearType running on an LCD monitor, we can now display features of text as small as a fraction of a pixel in width. The extra resolution increases the sharpness of the tiny details in text display, making it much easier to read over long durations. + + The ClearType available in [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] is the latest generation of ClearType which has several improvements over version found in Microsoft Windows Graphics Device Interface (GDI). + + +## Sub-pixel Positioning + A significant improvement over the previous version of ClearType is the use of sub-pixel positioning. Unlike the ClearType implementation found in GDI, the ClearType found in [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] allows glyphs to start within the pixel and not just the beginning boundary of the pixel. Because of this extra resolution in positioning glyphs, the spacing and proportions of the glyphs is more precise and consistent. + + The following two examples show how glyphs may begin on any sub-pixel boundary when sub-pixel positioning is used. The example on the left is rendered using the earlier version of the ClearType renderer, which did not employ sub-pixel positioning. The example on the right is rendered using the new version of the ClearType renderer, using sub-pixel positioning. Note how each **e** and **l** in the right-hand image is rendered slightly differently because each starts on a different sub-pixel. When viewing the text at its normal size on the screen, this difference is not noticeable because of the high contrast of the glyph image. This is only possible because of sophisticated color filtering that is incorporated in ClearType. + + ![Text displayed with two versions of ClearType](./media/wcpsdk-mmgraphics-text-cleartype-overview-01.png "wcpsdk_mmgraphics_text_cleartype_overview_01") +Text displayed with earlier and later versions of ClearType + + The following two examples compare output from the earlier ClearType renderer with the new version of the ClearType renderer. The subpixel positioning, shown on the right, greatly improves the spacing of type on screen, especially at small sizes where the difference between a sub-pixel and a whole pixel represents a significant proportion of glyph width. Note that spacing between the letters is more even in the second image. The cumulative benefit of sub-pixel positioning to the overall appearance of a screen of text is greatly increased, and represents a significant evolution in ClearType technology. + + ![Text displayed with earlier version of ClearType](./media/wcpsdk-mmgraphics-text-cleartype-overview-02.png "wcpsdk_mmgraphics_text_cleartype_overview_02") +Text with earlier and later versions of ClearType + + +## Y-Direction Antialiasing + Another improvement of ClearType in [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] is y-direction anti-aliasing. The ClearType in GDI without y-direction anti-aliasing provides better resolution on the x-axis but not the y-axis. On the tops and bottoms of shallow curves, the jagged edges detract from its readability. + + The following example shows the effect of having no y-direction antialiasing. In this case, the jagged edges on the top and bottom of the letter are apparent. + + ![Text with jagged edges on shallow curves](./media/wcpsdk-mmgraphics-text-cleartype-overview-03.png "wcpsdk_mmgraphics_text_cleartype_overview_03") +Text with jagged edges on shallow curves + + ClearType in [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] provides antialiasing on the y-direction level to smooth out any jagged edges. This is particularly important for improving the readability of East Asian languages where ideographs have an almost equal amount of horizontal and vertical shallow curves. + + The following example shows the effect of y-direction antialiasing. In this case, the top and bottom of the letter show a smooth curve. + + ![Text with ClearType y-direction anti-aliasing](./media/wcpsdk-mmgraphics-text-cleartype-overview-04.png "wcpsdk_mmgraphics_text_cleartype_overview_04") +Text with ClearType y-direction antialiasing + + +## Hardware Acceleration + ClearType in [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] can take advantage of hardware acceleration for better performance and to reduce CPU load and system memory requirements. By using the pixel shaders and video memory of a graphics card, ClearType provides faster rendering of text, particularly when animation is used. + + ClearType in [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] does not modify the system-wide ClearType settings. Disabling ClearType in Windows sets [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] antialiasing to grayscale mode. In addition, ClearType in [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] does not modify the settings of the [ClearType Tuner PowerToy](https://www.microsoft.com/typography/ClearTypePowerToy.mspx). + + One of the [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] architectural design decisions is to have resolution independent layout better support higher resolution DPI monitors, which are becoming more widespread. This has the consequence of [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] not supporting aliased text rendering or the bitmaps in some East Asian fonts because they are both resolution dependent. + + +## Further Information + [ClearType Information](https://www.microsoft.com/typography/ClearTypeInfo.mspx) + + [ClearType Tuner PowerToy](https://www.microsoft.com/typography/ClearTypePowerToy.mspx) + +## See also + +- [ClearType Registry Settings](cleartype-registry-settings.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/cleartype-registry-settings.md b/dotnet-desktop-guide/framework/wpf/advanced/cleartype-registry-settings.md new file mode 100644 index 0000000000..ed68ea506b --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/cleartype-registry-settings.md @@ -0,0 +1,113 @@ +--- +title: "ClearType Registry Settings" +ms.date: "03/30/2017" +helpviewer_keywords: + - "ClearType [WPF], registry settings" + - "typography [WPF], ClearType registry settings" +ms.assetid: 56f314bb-b30b-4f67-8492-8b8a9fa432ae +--- +# ClearType Registry Settings +This topic provides an overview of the Microsoft ClearType registry settings that are used by WPF applications. + + +## Technology Overview + [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] applications that render text to a display device use ClearType features to provide an enhanced reading experience. ClearType is a software technology developed by Microsoft that improves the readability of text on existing LCDs (Liquid Crystal Displays), such as laptop screens, Pocket PC screens and flat panel monitors. ClearType works by accessing the individual vertical color stripe elements in every pixel of an LCD screen. For more information on ClearType, see [ClearType Overview](cleartype-overview.md). + + Text that is rendered with ClearType can appear significantly different when viewed on various display devices. For example, a small number of monitors implement the color stripe elements in blue, green, red order rather than the more common red, green, blue (RGB) order. + + Text that is rendered with ClearType can also appear significantly different when viewed by individuals with varying levels of color sensitivity. Some individuals can detect slight differences in color better than others. + + In each of these cases, ClearType features need to be modified in order to provide the best reading experience for each individual. + + +## Registry Settings + [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] specifies four registry settings for controlling ClearType features: + +|Setting|Description| +|-------------|-----------------| +|ClearType level|Describes the level of ClearType color clarity.| +|Gamma level|Describes the level of the pixel color component for a display device.| +|Pixel structure|Describes the arrangement of pixels for a display device.| +|Text contrast level|Describes the level of contrast for displayed text.| + + These settings can be accessed by an external configuration utility that knows how to reference the identified [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] ClearType registry settings. These settings can also be created or modified by accessing the values directly by using the Windows Registry Editor. + + If the [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] ClearType registry settings are not set (which is the default state), the [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] application queries the Windows system parameters information for font smoothing settings. + +> [!NOTE] +> For information on enumerating display device names, see the `SystemParametersInfo`Win32 function. + + +## ClearType Level + The ClearType level allows you to adjust the rendering of text based on the color sensitivity and perception of an individual. For some individuals, the rendering of text that uses ClearType at its highest level does not produce the best reading experience. + + The ClearType level is an integer value that ranges from 0 to 100. The default level is 100, which means ClearType uses the maximum capability of the color stripe elements of the display device. However, a ClearType level of 0 renders text as gray scale. By setting the ClearType level somewhere between 0 and 100, you can create an intermediate level that is suitable to an individual's color sensitivity. + +### Registry Setting + The registry setting location for the ClearType level is an individual user setting that corresponds to a specific display device name: + + `HKEY_CURRENT_USER\SOFTWARE\Microsoft\Avalon.Graphics\` + + For each display device name for a user, a `ClearTypeLevel` DWORD value is defined. The following screenshot shows the Registry Editor setting for the ClearType level. + + ![ClearType settings in the Registry Editor.](./media/cleartype-registry-settings/cleartype-settings-registry-editor.png) + +> [!NOTE] +> [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] applications render text in one of either two modes, with and without ClearType. When text is rendered without ClearType, it is referred to as gray scale rendering. + + +## Gamma Level + The gamma level refers to the nonlinear relationship between a pixel value and luminance. The gamma level setting should correspond to the physical characteristics of the display device; otherwise, distortions in rendered output may occur. For example, text may appear too wide or too narrow, or color fringes may appear on the edges of vertical stems of glyphs. + + The gamma level is an integer value that ranges from 1000 to 2200. The default level is 1900. + +### Registry Setting + The registry setting location for the gamma level is a local machine setting that corresponds to a specific display device name: + + `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Avalon.Graphics\` + + For each display device name for a user, a `GammaLevel` DWORD value is defined. The following screenshot shows the Registry Editor setting for the gamma level. + + ![ClearType gamma level settings in the Registry Editor](./media/cleartype-registry-settings/cleartype-gamma-level-settings-registry-editor.png) + + +## Pixel Structure + The pixel structure describes the type of pixels that make up a display device. The pixel structure is defined as one of three types: + +|Type|Value|Description| +|----------|-----------|-----------------| +|Flat|0|The display device has no pixel structure. This means that light sources for each color are spread equally on the pixel area—this is referred to as gray scale rendering. This is how a standard display device works. ClearType is never applied to the rendered text.| +|RGB|1|The display device has pixels that consist of three stripes in the following order: red, green, and blue. ClearType is applied to the rendered text.| +|BGR|2|The display device has pixels that consist of three stripes in the following order: blue, green, and red. ClearType is applied to the rendered text. Notice how the order is inverted from the RGB type.| + + The pixel structure corresponds to an integer value that ranges from 0 to 2. The default level is 0, which represents a flat pixel structure. + +> [!NOTE] +> For information on enumerating display device names, see the `EnumDisplayDevices`Win32 function. + +### Registry Setting + The registry setting location for the pixel structure is a local machine setting that corresponds to a specific display device name: + + `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Avalon.Graphics\` + + For each display device name for a user, a `PixelStructure` DWORD value is defined. The following screenshot shows the Registry Editor setting for the pixel structure. + + ![ClearType gamma level settings in the Registry Editor](./media/cleartype-registry-settings/cleartype-gamma-level-settings-registry-editor.png) + + +## Text Contrast Level + The text contrast level allows you to adjust the rendering of text based on the stem widths of glyphs. The text contrast level is an integer value that ranges from 0 to 6—the larger the integer value, the wider the stem. The default level is 1. + +### Registry Setting + The registry setting location for the text contrast level is an individual user setting that corresponds to a specific display device name: + + `HKEY_CURRENT_USER\Software\Microsoft\Avalon.Graphics\` + + For each display device name for a user, a `TextContrastLevel` DWORD value is defined. The following screenshot shows the Registry Editor setting for the text contrast level. + + ![ClearType settings in the Registry Editor.](./media/cleartype-registry-settings/cleartype-settings-registry-editor.png) + +## See also + +- [ClearType Overview](cleartype-overview.md) +- [ClearType Antialiasing](/windows/desktop/gdi/cleartype-antialiasing) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/code-behind-and-xaml-in-wpf.md b/dotnet-desktop-guide/framework/wpf/advanced/code-behind-and-xaml-in-wpf.md new file mode 100644 index 0000000000..89d3a94c79 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/code-behind-and-xaml-in-wpf.md @@ -0,0 +1,60 @@ +--- +title: "Code-Behind and XAML" +ms.date: "03/30/2017" +helpviewer_keywords: + - "XAML [WPF], code-behind" + - "code-behind files [WPF], XAML" +ms.assetid: 9df6d3c9-aed3-471c-af36-6859b19d999f +--- +# Code-Behind and XAML in WPF + Code-behind is a term used to describe the code that is joined with markup-defined objects, when a [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] page is markup-compiled. This topic describes requirements for code-behind as well as an alternative inline code mechanism for code in [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)]. + + This topic contains the following sections: + +- [Prerequisites](#Prerequisites) + +- [Code-Behind and the XAML Language](#codebehind_and_the_xaml_language) + +- [Code-behind, Event Handler, and Partial Class Requirements in WPF](#Code_behind__Event_Handler__and_Partial_Class) + +- [x:Code](#x_Code) + +- [Inline Code Limitations](#Inline_Code_Limitations) + + +## Prerequisites + This topic assumes that you have read the [XAML Overview (WPF)](/dotnet/desktop-wpf/fundamentals/xaml) and have some basic knowledge of the CLR and object-oriented programming. + + +## Code-Behind and the XAML Language + The XAML language includes language-level features that make it possible to associate code files with markup files, from the markup file side. Specifically, the XAML language defines the language features [x:Class Directive](/dotnet/desktop-wpf/xaml-services/xclass-directive), [x:Subclass Directive](/dotnet/desktop-wpf/xaml-services/xsubclass-directive), and [x:ClassModifier Directive](/dotnet/desktop-wpf/xaml-services/xclassmodifier-directive). Exactly how the code should be produced, and how to integrate markup and code, is not part of what the XAML language specifies. It is left up to frameworks such as WPF to determine how to integrate the code, how to use XAML in the application and programming models, and the build actions or other support that all this requires. + + +## Code-behind, Event Handler, and Partial Class Requirements in WPF + +- The partial class must derive from the type that backs the root element. + +- Note that under the default behavior of the markup compile build actions, you can leave the derivation blank in the partial class definition on the code-behind side. The compiled result will assume the page root's backing type to be the basis for the partial class, even if it not specified. However, relying on this behavior is not a best practice. + +- The event handlers you write in the code-behind must be instance methods and cannot be static methods. These methods must be defined by the partial class within the CLR namespace identified by `x:Class`. You cannot qualify the name of an event handler to instruct a [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] processor to look for an event handler for event wiring in a different class scope. + +- The handler must match the delegate for the appropriate event in the backing type system. + +- For the Microsoft Visual Basic language specifically, you can use the language-specific `Handles` keyword to associate handlers with instances and events in the handler declaration, instead of attaching handlers with attributes in [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)]. However, this technique does have some limitations because the `Handles` keyword cannot support all of the specific features of the [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] event system, such as certain routed event scenarios or attached events. For details, see [Visual Basic and WPF Event Handling](visual-basic-and-wpf-event-handling.md). + + +## x:Code + [x:Code](/dotnet/desktop-wpf/xaml-services/xcode-intrinsic-xaml-type) is a directive element defined in [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)]. An `x:Code` directive element can contain inline programming code. The code that is defined inline can interact with the [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] on the same page. The following example illustrates inline C# code. Notice that the code is inside the `x:Code` element and that the code must be surrounded by `` to escape the contents for XML, so that a [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] processor (interpreting either the [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] schema or the [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] schema) will not try to interpret the contents literally as XML. + + [!code-xaml[XAMLOvwSupport#ButtonWithInlineCode](~/samples/snippets/csharp/VS_Snippets_Wpf/XAMLOvwSupport/CSharp/page4.xaml#buttonwithinlinecode)] + + +## Inline Code Limitations + You should consider avoiding or limiting the use of inline code. In terms of architecture and coding philosophy, maintaining a separation between markup and code-behind keeps the designer and developer roles much more distinct. On a more technical level, the code that you write for inline code can be awkward to write, because you are always writing into the [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] generated partial class, and can only use the default XML namespace mappings. Because you cannot add `using` statements, you must fully qualify many of the API calls that you make. The default [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] mappings include most but not all CLR namespaces that are present in the [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] assemblies; you will have to fully qualify calls to types and members contained within the other CLR namespaces. You also cannot define anything beyond the partial class in the inline code, and all user code entities you reference must exist as a member or variable within the generated partial class. Other language specific programming features, such as macros or `#ifdef` against global variables or build variables, are also not available. For more information, see [x:Code Intrinsic XAML Type](/dotnet/desktop-wpf/xaml-services/xcode-intrinsic-xaml-type). + +## See also + +- [XAML Overview (WPF)](/dotnet/desktop-wpf/fundamentals/xaml) +- [x:Code Intrinsic XAML Type](/dotnet/desktop-wpf/xaml-services/xcode-intrinsic-xaml-type) +- [Building a WPF Application](../app-development/building-a-wpf-application-wpf.md) +- [XAML Syntax In Detail](xaml-syntax-in-detail.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/collecting-ink.md b/dotnet-desktop-guide/framework/wpf/advanced/collecting-ink.md new file mode 100644 index 0000000000..98535df37b --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/collecting-ink.md @@ -0,0 +1,89 @@ +--- +title: Collect digital ink +ms.date: 08/15/2018 +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "ink [WPF], collecting" + - "InkCanvas element [WPF]" + - "properties [WPF], DrawingAttributes" + - "collecting digital ink [WPF]" + - "digital ink [WPF], collecting" + - "properties [WPF], DefaultDrawingAttributes" + - "DefaultDrawingAttributes property [WPF]" +ms.assetid: 66a3129d-9577-43eb-acbd-56c147282016 +--- +# Collect Ink + +The [Windows Presentation Foundation](../index.md) platform collects digital ink as a core part of its functionality. This topic discusses methods for collection of ink in Windows Presentation Foundation (WPF). + +## Prerequisites + +To use the following examples, you must first install Visual Studio and the Windows SDK. You should also understand how to write applications for the WPF. For more information about getting started with WPF, see [Walkthrough: My first WPF desktop application](../getting-started/walkthrough-my-first-wpf-desktop-application.md). + +## Use the InkCanvas Element + +The element provides the easiest way to collect ink in WPF. Use an element to receive and display ink input. You commonly input ink through the use of a stylus, which interacts with a digitizer to produce ink strokes. In addition, a mouse can be used in place of a stylus. The created strokes are represented as objects, and they can be manipulated both programmatically and by user input. The enables users to select, modify, or delete an existing . + +By using XAML, you can set up ink collection as easily as adding an **InkCanvas** element to your tree. The following example adds an to a default WPF project created in Visual Studio: + +[!code-xaml[DigitalInkTopics#6](~/samples/snippets/csharp/VS_Snippets_Wpf/DigitalInkTopics/CSharp/Window2.xaml#6)] + +The **InkCanvas** element can also contain child elements, making it possible to add ink annotation capabilities to almost any type of XAML element. For example, to add inking capabilities to a text element, simply make it a child of an : + +[!code-xaml[DigitalInkTopics#5](~/samples/snippets/csharp/VS_Snippets_Wpf/DigitalInkTopics/CSharp/Window2.xaml#5)] + +Adding support for marking up an image with ink is just as easy: + +[!code-xaml[DigitalInkTopics#7](~/samples/snippets/csharp/VS_Snippets_Wpf/DigitalInkTopics/CSharp/Window2.xaml#7)] + +### InkCollection Modes + +The provides support for various input modes through its property. + +### Manipulate Ink + +The provides support for many ink editing operations. For example, supports back-of-pen erase, and no additional code is needed to add the functionality to the element. + +#### Selection + +Setting selection mode is as simple as setting the property to **Select**. + +The following code sets the editing mode based on the value of a : + +[!code-csharp[DigitalInkTopics#8](~/samples/snippets/csharp/VS_Snippets_Wpf/DigitalInkTopics/CSharp/Window1.xaml.cs#8)] +[!code-vb[DigitalInkTopics#8](~/samples/snippets/visualbasic/VS_Snippets_Wpf/DigitalInkTopics/VisualBasic/Window1.xaml.vb#8)] + +#### DrawingAttributes + +Use the property to change the appearance of ink strokes. For instance, the member of sets the color of the rendered . + +The following example changes the color of the selected strokes to red: + +[!code-csharp[DigitalInkTopics#9](~/samples/snippets/csharp/VS_Snippets_Wpf/DigitalInkTopics/CSharp/Window1.xaml.cs#9)] +[!code-vb[DigitalInkTopics#9](~/samples/snippets/visualbasic/VS_Snippets_Wpf/DigitalInkTopics/VisualBasic/Window1.xaml.vb#9)] + +### DefaultDrawingAttributes + +The property provides access to properties such as the height, width, and color of the strokes to be created in an . Once you change the , all future strokes entered into the are rendered with the new property values. + +In addition to modifying the in the code-behind file, you can use XAML syntax for specifying properties. + +The next example demonstrates how to set the property. To use this code, create a new WPF project called "HelloInkCanvas" in Visual Studio. Replace the code in the *MainWindow.xaml* file with the following code: + +[!code-xaml[HelloInkCanvas#1](~/samples/snippets/csharp/VS_Snippets_Wpf/HelloInkCanvas/CSharp/Window1.xaml#1)] + +Next, add the following button event handlers to the code behind file, inside the MainWindow class: + +[!code-csharp[HelloInkCanvas#2](~/samples/snippets/csharp/VS_Snippets_Wpf/HelloInkCanvas/CSharp/Window1.xaml.cs#2)] + +After copying this code, press **F5** in Visual Studio to run the program in the debugger. + +Notice how the places the buttons on top of the . If you try to ink over the top of the buttons, the collects and renders the ink behind the buttons. This is because the buttons are siblings of the as opposed to children. Also, the buttons are higher in the z-order, so the ink is rendered behind them. + +## See also + +- +- +- diff --git a/dotnet-desktop-guide/framework/wpf/advanced/collection-type-dependency-properties.md b/dotnet-desktop-guide/framework/wpf/advanced/collection-type-dependency-properties.md new file mode 100644 index 0000000000..8829e5b643 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/collection-type-dependency-properties.md @@ -0,0 +1,61 @@ +--- +title: "Collection-Type Dependency Properties" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "properties [WPF], dependency" + - "properties [WPF], collection-type" + - "dependency properties [WPF]" + - "collection-type properties [WPF]" +ms.assetid: 99f96a42-3ab7-4f64-a16b-2e10d654e97c +--- +# Collection-Type Dependency Properties +This topic provides guidance and suggested patterns for how to implement a dependency property where the type of the property is a collection type. + + +## Implementing a Collection-Type Dependency Property + For a dependency property in general, the implementation pattern that you follow is that you define a CLR property wrapper, where that property is backed by a identifier rather than a field or other construct. You follow this same pattern when you implement a collection-type property. However, a collection-type property introduces some complexity to the pattern whenever the type that is contained within the collection is itself a or derived class. + + +## Initializing the Collection Beyond the Default Value + When you create a dependency property, you do not specify the property default value as the initial field value. Instead, you specify the default value through the dependency property metadata. If your property is a reference type, the default value specified in dependency property metadata is not a default value per instance; instead it is a default value that applies to all instances of the type. Therefore you must be careful to not use the singular static collection defined by the collection property metadata as the working default value for newly created instances of your type. Instead, you must make sure that you deliberately set the collection value to a unique (instance) collection as part of your class constructor logic. Otherwise you will have created an unintentional singleton class. + + Consider the following example. The following section of the example shows the definition for a class `Aquarium`, which contains a flaw with the default value. The class defines the collection type dependency property `AquariumObjects`, which uses the generic type with a type constraint. In the call for the dependency property, the metadata establishes the default value to be a new generic . + +> [!WARNING] +> The following code does not behave correctly. + + [!code-csharp[PropertiesOvwSupport2#CollectionProblemDefinition](~/samples/snippets/csharp/VS_Snippets_Wpf/PropertiesOvwSupport2/CSharp/page.xaml.cs#collectionproblemdefinition)] + [!code-vb[PropertiesOvwSupport2#CollectionProblemDefinition](~/samples/snippets/visualbasic/VS_Snippets_Wpf/PropertiesOvwSupport2/visualbasic/page.xaml.vb#collectionproblemdefinition)] + + However, if you just left the code as shown, that single list default value is shared for all instances of `Aquarium`. If you ran the following test code, which is intended to show how you would instantiate two separate `Aquarium` instances and add a single different `Fish` to each of them, you would see a surprising result: + + [!code-csharp[PropertiesOvwSupport#CollectionProblemTestCode](~/samples/snippets/csharp/VS_Snippets_Wpf/PropertiesOvwSupport/CSharp/page4.xaml.cs#collectionproblemtestcode)] + [!code-vb[PropertiesOvwSupport#CollectionProblemTestCode](~/samples/snippets/visualbasic/VS_Snippets_Wpf/PropertiesOvwSupport/visualbasic/page4.xaml.vb#collectionproblemtestcode)] + + Instead of each collection having a count of one, each collection has a count of two! This is because each `Aquarium` added its `Fish` to the default value collection, which resulted from a single constructor call in the metadata and is therefore shared between all instances. This situation is almost never what you want. + + To correct this problem, you must reset the collection dependency property value to a unique instance, as part of the class constructor call. Because the property is a read-only dependency property, you use the method to set it, using the that is only accessible within the class. + + [!code-csharp[PropertiesOvwSupport#CollectionProblemCtor](~/samples/snippets/csharp/VS_Snippets_Wpf/PropertiesOvwSupport/CSharp/page4.xaml.cs#collectionproblemctor)] + [!code-vb[PropertiesOvwSupport#CollectionProblemCtor](~/samples/snippets/visualbasic/VS_Snippets_Wpf/PropertiesOvwSupport/visualbasic/page4.xaml.vb#collectionproblemctor)] + + Now, if you ran that same test code again, you could see more expected results, where each `Aquarium` supported its own unique collection. + + There would be a slight variation on this pattern if you chose to have your collection property be read-write. In that case, you could call the public set accessor from the constructor to do the initialization, which would still be calling the nonkey signature of within your set wrapper, using a public identifier. + +## Reporting Binding Value Changes from Collection Properties + A collection property that is itself a dependency property does not automatically report changes to its subproperties. If you are creating bindings into a collection, this can prevent the binding from reporting changes, thus invalidating some data binding scenarios. However, if you use the collection type as your collection type, then subproperty changes to contained elements in the collection are properly reported, and binding works as expected. + + To enable subproperty binding in a dependency object collection, create the collection property as type , with a type constraint for that collection to any derived class. + +## See also + +- +- [XAML and Custom Classes for WPF](xaml-and-custom-classes-for-wpf.md) +- [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview) +- [Dependency Properties Overview](dependency-properties-overview.md) +- [Custom Dependency Properties](custom-dependency-properties.md) +- [Dependency Property Metadata](dependency-property-metadata.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/colorconvertedbitmap-markup-extension.md b/dotnet-desktop-guide/framework/wpf/advanced/colorconvertedbitmap-markup-extension.md new file mode 100644 index 0000000000..ed8594f9d0 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/colorconvertedbitmap-markup-extension.md @@ -0,0 +1,37 @@ +--- +title: "ColorConvertedBitmap Markup Extension" +ms.date: "03/30/2017" +helpviewer_keywords: + - "XAML [WPF], ColorConvertedBitmap markup extension" + - "ColorConvertedBitmap markup extension [WPF]" +ms.assetid: 18321c18-c898-4470-93fa-a702b47770c1 +--- +# ColorConvertedBitmap Markup Extension +Provides a way to specify a bitmap source that does not have an embedded profile. Color contexts / profiles are specified by URI, as is the image source URI. + +## XAML Attribute Usage + +```xml + +``` + +## XAML Values + +||| +|-|-| +|`imageSource`|The URI of the nonprofiled bitmap.| +|`sourceIIC`|The URI of the source profile configuration.| +|`destinationIIC`|The URI of the destination profile configuration| + +## Remarks + This markup extension is intended to fill a related set of image-source property values such as . + + Attribute syntax is the most common syntax used with this markup extension. `ColorConvertedBitmap` (or `ColorConvertedBitmapExtension`) cannot be used in property element syntax, because the values can only be set as values on the initial constructor, which is the string following the extension identifier. + + `ColorConvertedBitmap` is a markup extension. Markup extensions are typically implemented when there is a requirement to escape attribute values to be other than literal values or handler names, and the requirement is more global than just putting type converters on certain types or properties. All markup extensions in [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] use the { and } characters in their attribute syntax, which is the convention by which a [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] processor recognizes that a markup extension must process the attribute. For more information, see [Markup Extensions and WPF XAML](markup-extensions-and-wpf-xaml.md). + +## See also + +- +- [Markup Extensions and WPF XAML](markup-extensions-and-wpf-xaml.md) +- [Imaging Overview](../graphics-multimedia/imaging-overview.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/commanding-overview.md b/dotnet-desktop-guide/framework/wpf/advanced/commanding-overview.md new file mode 100644 index 0000000000..92616bc52a --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/commanding-overview.md @@ -0,0 +1,191 @@ +--- +title: "Commanding Overview" +description: Learn about commanding, an input mechanism in Windows Presentation Foundation which provides input handling at a more semantic level than device input. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "interfaces [WPF], ICommandSource" + - "command library [WPF]" + - "commands [WPF], definition of" + - "CommandBindings [WPF]" + - "ICommandSource interfaces [WPF]" + - "commanding [WPF]" + - "CommandManager [WPF]" +ms.assetid: bc208dfe-367d-426a-99de-52b7e7511e81 +--- +# Commanding Overview + Commanding is an input mechanism in [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] which provides input handling at a more semantic level than device input. Examples of commands are the **Copy**, **Cut**, and **Paste** operations found on many applications. + + This overview defines what commands are in [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)], which classes are part of the commanding model, and how to use and create commands in your applications. + + This topic contains the following sections: + +- [What Are Commands?](#commands_at_10000_feet) + +- [Simple Command Example in WPF](#simple_command) + +- [Four Main Concepts in WPF Commanding](#Four_main_Concepts) + +- [Command Library](#Command_Library) + +- [Creating Custom Commands](#creating_commands) + + +## What Are Commands? + Commands have several purposes. The first purpose is to separate the semantics and the object that invokes a command from the logic that executes the command. This allows for multiple and disparate sources to invoke the same command logic, and it allows the command logic to be customized for different targets. For example, the editing operations **Copy**, **Cut**, and **Paste**, which are found in many applications, can be invoked by using different user actions if they are implemented by using commands. An application might allow a user to cut selected objects or text by either clicking a button, choosing an item in a menu, or using a key combination, such as CTRL+X. By using commands, you can bind each type of user action to the same logic. + + Another purpose of commands is to indicate whether an action is available. To continue the example of cutting an object or text, the action only makes sense when something is selected. If a user tries to cut an object or text without having anything selected, nothing would happen. To indicate this to the user, many applications disable buttons and menu items so that the user knows whether it is possible to perform an action. A command can indicate whether an action is possible by implementing the method. A button can subscribe to the event and be disabled if returns `false` or be enabled if returns `true`. + + The semantics of a command can be consistent across applications and classes, but the logic of the action is specific to the particular object acted upon. The key combination CTRL+X invokes the **Cut** command in text classes, image classes, and Web browsers, but the actual logic for performing the **Cut** operation is defined by the application that performs the cut. A enables clients to implement the logic. A text object may cut the selected text into the clipboard, while an image object may cut the selected image. When an application handles the event, it has access to the target of the command and can take appropriate action depending on the target's type. + + +## Simple Command Example in WPF + The simplest way to use a command in [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] is to use a predefined from one of the command library classes; use a control that has native support for handling the command; and use a control that has native support for invoking a command. The command is one of the predefined commands in the class. The control has built in logic for handling the command. And the class has native support for invoking commands. + + The following example shows how to set up a so that when it is clicked it will invoke the command on a , assuming the has keyboard focus. + + [!code-xaml[CommandingOverviewSnippets#CommandingOverviewSimpleCommand](~/samples/snippets/csharp/VS_Snippets_Wpf/CommandingOverviewSnippets/CSharp/Window1.xaml#commandingoverviewsimplecommand)] + + [!code-csharp[CommandingOverviewSnippets#CommandingOverviewCommandTargetCodeBehind](~/samples/snippets/csharp/VS_Snippets_Wpf/CommandingOverviewSnippets/CSharp/Window1.xaml.cs#commandingoverviewcommandtargetcodebehind)] + [!code-vb[CommandingOverviewSnippets#CommandingOverviewCommandTargetCodeBehind](~/samples/snippets/visualbasic/VS_Snippets_Wpf/CommandingOverviewSnippets/visualbasic/window1.xaml.vb#commandingoverviewcommandtargetcodebehind)] + + +## Four Main Concepts in WPF Commanding + The routed command model in [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] can be broken up into four main concepts: the command, the command source, the command target, and the command binding: + +- The *command* is the action to be executed. + +- The *command source* is the object which invokes the command. + +- The *command target* is the object that the command is being executed on. + +- The *command binding* is the object which maps the command logic to the command. + + In the previous example, the command is the command, the is the command source, the is the command target, and the command binding is supplied by the control. It is worth noting that it is not always the case that the is supplied by the control that is the command target class. Quite often the must be created by the application developer, or the might be attached to an ancestor of the command target. + + +### Commands + Commands in [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] are created by implementing the interface. exposes two methods, , and , and an event, . performs the actions that are associated with the command. determines whether the command can execute on the current command target. is raised if the command manager that centralizes the commanding operations detects a change in the command source that might invalidate a command that has been raised but not yet executed by the command binding. The [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] implementation of is the class and is the focus of this overview. + + The main sources of input in [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] are the mouse, the keyboard, ink, and routed commands. The more device-oriented inputs use a to notify objects in an application page that an input event has occurred. A is no different. The and methods of a do not contain the application logic for the command, but rather they raise routed events that tunnel and bubble through the element tree until they encounter an object with a . The contains the handlers for these events and it is the handlers that perform the command. For more information on event routing in [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)], see [Routed Events Overview](routed-events-overview.md). + + The method on a raises the and the events on the command target. The method on a raises the and events on the command target. These events tunnel and bubble through the element tree until they encounter an object which has a for that particular command. + + [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] supplies a set of common routed commands spread across several classes: , , , , and . These classes consist only of the objects and not the implementation logic of the command. The implementation logic is the responsibility of the object on which the command is being executed on. + + +### Command Sources + A command source is the object which invokes the command. Examples of command sources are , , and . + + Command sources in [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] generally implement the interface. + + exposes three properties: , , and : + +- is the command to execute when the command source is invoked. + +- is the object on which to execute the command. It is worth noting that in [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] the property on is only applicable when the is a . If the is set on an and the corresponding command is not a , the command target is ignored. If the is not set, the element with keyboard focus will be the command target. + +- is a user-defined data type used to pass information to the handlers implementing the command. + + The [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] classes that implement are , , , and . , , and invoke a command when they are clicked, and an invokes a command when the associated with it is performed. + + The following example shows how to use a in a as a command source for the command. + + [!code-xaml[CommandingOverviewSnippets#CommandingOverviewCmdSourceXAML](~/samples/snippets/csharp/VS_Snippets_Wpf/CommandingOverviewSnippets/CSharp/Window1.xaml#commandingoverviewcmdsourcexaml)] + + [!code-csharp[CommandingOverviewSnippets#CommandingOverviewCmdSource](~/samples/snippets/csharp/VS_Snippets_Wpf/CommandingOverviewSnippets/CSharp/Window1.xaml.cs#commandingoverviewcmdsource)] + [!code-vb[CommandingOverviewSnippets#CommandingOverviewCmdSource](~/samples/snippets/visualbasic/VS_Snippets_Wpf/CommandingOverviewSnippets/visualbasic/window1.xaml.vb#commandingoverviewcmdsource)] + + Typically, a command source will listen to the event. This event informs the command source that the ability of the command to execute on the current command target may have changed. The command source can query the current status of the by using the method. The command source can then disable itself if the command cannot execute. An example of this is a graying itself out when a command cannot execute. + + An can be used as a command source. Two types of input gestures in [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] are the and . You can think of a as a keyboard shortcut, such as CTRL+C. A is comprised of a and a set of . A is comprised of a and an optional set of . + + In order for an to act as a command source, it must be associated with a command. There are a few ways to accomplish this. One way is to use an . + + The following example shows how to create a between a and a . + + [!code-xaml[CommandingOverviewSnippets#CommandingOverviewXAMLKeyBinding](~/samples/snippets/csharp/VS_Snippets_Wpf/CommandingOverviewSnippets/CSharp/Window1.xaml#commandingoverviewxamlkeybinding)] + + [!code-csharp[CommandingOverviewSnippets#CommandingOverviewKeyBinding](~/samples/snippets/csharp/VS_Snippets_Wpf/CommandingOverviewSnippets/CSharp/Window1.xaml.cs#commandingoverviewkeybinding)] + [!code-vb[CommandingOverviewSnippets#CommandingOverviewKeyBinding](~/samples/snippets/visualbasic/VS_Snippets_Wpf/CommandingOverviewSnippets/visualbasic/window1.xaml.vb#commandingoverviewkeybinding)] + + Another way to associate an to a is to add the to the on the . + + The following example shows how to add a to the of a . + + [!code-csharp[CommandingOverviewSnippets#CommandingOverviewKeyGestureOnCmd](~/samples/snippets/csharp/VS_Snippets_Wpf/CommandingOverviewSnippets/CSharp/Window1.xaml.cs#commandingoverviewkeygestureoncmd)] + [!code-vb[CommandingOverviewSnippets#CommandingOverviewKeyGestureOnCmd](~/samples/snippets/visualbasic/VS_Snippets_Wpf/CommandingOverviewSnippets/visualbasic/window1.xaml.vb#commandingoverviewkeygestureoncmd)] + + +### CommandBinding + A associates a command with the event handlers that implement the command. + + The class contains a property, and , , , and events. + + is the command that the is being associated with. The event handlers which are attached to the and events implement the command logic. The event handlers attached to the and events determine if the command can execute on the current command target. + + The following example shows how to create a on the root of an application. The associates the command with and handlers. + + [!code-xaml[commandwithhandler#CommandHandlerCommandBinding](~/samples/snippets/csharp/VS_Snippets_Wpf/commandWithHandler/CSharp/Window1.xaml#commandhandlercommandbinding)] + + [!code-csharp[CommandHandlerProcedural#CommandHandlerBindingInit](~/samples/snippets/csharp/VS_Snippets_Wpf/CommandHandlerProcedural/CSharp/Window1.xaml.cs#commandhandlerbindinginit)] + [!code-vb[CommandHandlerProcedural#CommandHandlerBindingInit](~/samples/snippets/visualbasic/VS_Snippets_Wpf/CommandHandlerProcedural/visualbasic/window1.xaml.vb#commandhandlerbindinginit)] + + Next, the and a are created. The opens a that displays a string saying the command has been executed. The sets the property to `true`. + + [!code-csharp[commandwithhandler#CommandHandlerExecutedHandler](~/samples/snippets/csharp/VS_Snippets_Wpf/commandWithHandler/CSharp/Window1.xaml.cs#commandhandlerexecutedhandler)] + [!code-vb[commandwithhandler#CommandHandlerExecutedHandler](~/samples/snippets/visualbasic/VS_Snippets_Wpf/commandWithHandler/VisualBasic/Window1.xaml.vb#commandhandlerexecutedhandler)] + + [!code-csharp[commandwithhandler#CommandHandlerCanExecuteHandler](~/samples/snippets/csharp/VS_Snippets_Wpf/commandWithHandler/CSharp/Window1.xaml.cs#commandhandlercanexecutehandler)] + [!code-vb[commandwithhandler#CommandHandlerCanExecuteHandler](~/samples/snippets/visualbasic/VS_Snippets_Wpf/commandWithHandler/VisualBasic/Window1.xaml.vb#commandhandlercanexecutehandler)] + + A is attached to a specific object, such as the root of the application or a control. The object that the is attached to defines the scope of the binding. For example, a attached to an ancestor of the command target can be reached by the event, but a attached to a descendant of the command target cannot be reached. This is a direct consequence of the way a tunnels and bubbles from the object that raises the event. + + In some situations the is attached to the command target itself, such as with the class and the , , and commands. Quite often though, it is more convenient to attach the to an ancestor of the command target, such as the main or the Application object, especially if the same can be used for multiple command targets. These are design decisions you will want to consider when you are creating your commanding infrastructure. + + +### Command Target + The command target is the element on which the command is executed. With regards to a , the command target is the element at which routing of the and starts. As noted previously, in [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] the property on is only applicable when the is a . If the is set on an and the corresponding command is not a , the command target is ignored. + + The command source can explicitly set the command target. If the command target is not defined, the element with keyboard focus will be used as the command target. One of the benefits of using the element with keyboard focus as the command target is that it allows the application developer to use the same command source to invoke a command on multiple targets without having to keep track of the command target. For example, if a invokes the **Paste** command in an application that has a control and a control, the target can be either the or depending on which control has keyboard focus. + + The following example shows how to explicitly set the command target in markup and in code behind. + + [!code-xaml[CommandingOverviewSnippets#CommandingOverviewXAMLCommandTarget](~/samples/snippets/csharp/VS_Snippets_Wpf/CommandingOverviewSnippets/CSharp/Window1.xaml#commandingoverviewxamlcommandtarget)] + + [!code-csharp[CommandingOverviewSnippets#CommandingOverviewCommandTargetCodeBehind](~/samples/snippets/csharp/VS_Snippets_Wpf/CommandingOverviewSnippets/CSharp/Window1.xaml.cs#commandingoverviewcommandtargetcodebehind)] + [!code-vb[CommandingOverviewSnippets#CommandingOverviewCommandTargetCodeBehind](~/samples/snippets/visualbasic/VS_Snippets_Wpf/CommandingOverviewSnippets/visualbasic/window1.xaml.vb#commandingoverviewcommandtargetcodebehind)] + + +### The CommandManager + The serves a number of command related functions. It provides a set of static methods for adding and removing , , , and event handlers to and from a specific element. It provides a means to register and objects onto a specific class. The also provides a means, through the event, to notify a command when it should raise the event. + + The method forces the to raise the event. This is useful for conditions that should disable/enable a command but are not conditions that the is aware of. + + +## Command Library + [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] provides a set of predefined commands. The command library consists of the following classes: , , , , and the . These classes provide commands such as , and , , , and . + + Many of these commands include a set of default input bindings. For example, if you specify that your application handles the copy command, you automatically get the keyboard binding "CTRL+C" You also get bindings for other input devices, such as Tablet PC pen gestures and speech information. + + When you reference commands in the various command libraries using [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)], you can usually omit the class name of the library class that exposes the static command property. Generally, the command names are unambiguous as strings, and the owning types exist to provide a logical grouping of commands but are not necessary for disambiguation. For instance, you can specify `Command="Cut"` rather than the more verbose `Command="ApplicationCommands.Cut"`. This is a convenience mechanism that is built in to the [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] processor for commands (more precisely, it is a type converter behavior of , which the [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] processor references at load time). + + +## Creating Custom Commands + If the commands in the command library classes do not meet your needs, then you can create your own commands. There are two ways to create a custom command. The first is to start from the ground up and implement the interface. The other way, and the more common approach, is to create a or a . + + For an example of creating a custom , see [Create a Custom RoutedCommand Sample](https://github.com/Microsoft/WPF-Samples/tree/master/Input%20and%20Commands/CustomRoutedCommand). + +## See also + +- +- +- +- +- [Input Overview](input-overview.md) +- [Routed Events Overview](routed-events-overview.md) +- [Implement ICommandSource](how-to-implement-icommandsource.md) +- [How to: Add a Command to a MenuItem](https://docs.microsoft.com/previous-versions/dotnet/netframework-3.5/ms741839(v=vs.90)) +- [Create a Custom RoutedCommand Sample](https://github.com/Microsoft/WPF-Samples/tree/master/Input%20and%20Commands/CustomRoutedCommand) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/componentresourcekey-markup-extension.md b/dotnet-desktop-guide/framework/wpf/advanced/componentresourcekey-markup-extension.md new file mode 100644 index 0000000000..2774d63701 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/componentresourcekey-markup-extension.md @@ -0,0 +1,77 @@ +--- +title: "ComponentResourceKey Markup Extension" +ms.date: "03/30/2017" +f1_keywords: + - "ComponentResourceKey" + - "ComponentResourceKeyExtension" +helpviewer_keywords: + - "ComponentResourceKey markup extension [WPF]" + - "XAML [WPF], ComponentResourceKey markup extension" +ms.assetid: d6bcdbe6-61b3-40a7-b381-4e02185b5a85 +--- +# ComponentResourceKey Markup Extension +Defines and references keys for resources that are loaded from external assemblies. This enables a resource lookup to specify a target type in an assembly, rather than an explicit resource dictionary in an assembly or on a class. + +## XAML Attribute Usage (setting key, compact) + +```xml + +``` + +## XAML Attribute Usage (setting key, verbose) + +```xml + +``` + +## XAML Attribute Usage (requesting resource, compact) + +```xml + +``` + +## XAML Attribute Usage (requesting resource, verbose) + +```xml + +``` + +## XAML Values + +||| +|-|-| +|`targetTypeName`|The name of the public common language runtime (CLR) type that is defined in the resource assembly.| +|`targetID`|The key for the resource. When resources are looked up, `targetID` will be analogous to the [x:Key Directive](/dotnet/desktop-wpf/xaml-services/xkey-directive) of the resource.| + +## Remarks + As seen in the usages above, a {`ComponentResourceKey`} markup extension usage is found in two places: + +- The definition of a key within a theme resource dictionary, as provided by a control author. + +- Accessing a theme resource from the assembly, when you are retemplating the control but want to use property values that come from resources provided by the control's themes. + + For referencing component resources that come from themes, it is generally recommended that you use `{DynamicResource}` rather than `{StaticResource}`. This is shown in the usages. `{DynamicResource}` is recommended because the theme itself can be changed by the user. If you want the component resource that most closely matches the control author's intent for supporting a theme, you should enable your component resource reference to be dynamic also. + + The identifies a type that exists in the target assembly where the resource is actually defined. A `ComponentResourceKey` can be defined and used independently of knowing exactly where the is defined, but eventually must resolve the type through referenced assemblies. + + A common usage for is to define keys that are then exposed as members of a class. For this usage, you use the class constructor, not the markup extension. For more information, see , or the "Defining and Referencing Keys for Theme Resources" section of the topic [Control Authoring Overview](../controls/control-authoring-overview.md). + + For both establishing keys and referencing keyed resources, attribute syntax is commonly used for the `ComponentResourceKey` markup extension. + + The compact syntax shown relies on the constructor signature and positional parameter usage of a markup extension. The order in which the `targetTypeName` and `targetID` are given is important. The verbose syntax relies on the parameterless constructor, and then sets the and in a way that is analogous to a true attribute syntax on an object element. In the verbose syntax, the order in which the properties are set is not important. The relationship and mechanisms of these two alternatives (compact and verbose) is described in more detail in the topic [Markup Extensions and WPF XAML](markup-extensions-and-wpf-xaml.md). + + Technically, the value for `targetID` can be any object, it does not have to be a string. However, the most common usage in WPF is to align the `targetID` value with forms that are strings, and where such strings are valid in the [XamlName Grammar](/dotnet/desktop-wpf/xaml-services/xamlname-grammar). + + `ComponentResourceKey` can be used in object element syntax. In this case, specifying the value of both the and properties is required to properly initialize the extension. + + In the [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] reader implementation, the handling for this markup extension is defined by the class. + + `ComponentResourceKey` is a markup extension. Markup extensions are typically implemented when there is a requirement to escape attribute values to be other than literal values or handler names, and the requirement is more global than just putting type converters on certain types or properties. All markup extensions in [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] use the { and } characters in their attribute syntax, which is the convention by which a [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] processor recognizes that a markup extension must process the attribute. For more information, see [Markup Extensions and WPF XAML](markup-extensions-and-wpf-xaml.md). + +## See also + +- +- +- [Control Authoring Overview](../controls/control-authoring-overview.md) +- [XAML Overview (WPF)](/dotnet/desktop-wpf/fundamentals/xaml) +- [Markup Extensions and WPF XAML](markup-extensions-and-wpf-xaml.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/createidispatchstaforwarder-function-wpf-unmanaged-api-reference.md b/dotnet-desktop-guide/framework/wpf/advanced/createidispatchstaforwarder-function-wpf-unmanaged-api-reference.md new file mode 100644 index 0000000000..a302d4efea --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/createidispatchstaforwarder-function-wpf-unmanaged-api-reference.md @@ -0,0 +1,49 @@ +--- +title: "CreateIDispatchSTAForwarder Function - WPF unmanaged API reference" +titleSuffix: "" +ms.date: "03/30/2017" +dev_langs: + - "cpp" +api_name: + - "CreateIDispatchSTAForwarder" +api_location: + - "PresentationHost_v0400.dll" +ms.assetid: 57a02dfa-f091-4ace-9c06-1f4ab52b3527 +--- +# CreateIDispatchSTAForwarder Function (WPF Unmanaged API Reference) +This API supports the Windows Presentation Foundation (WPF) infrastructure and is not intended to be used directly from your code. + + Used by the Windows Presentation Foundation (WPF) infrastructure for thread and windows management. + +## Syntax + +```cpp +HRESULT CreateIDispatchSTAForwarder( + __in IDispatch *pDispatchDelegate, + __deref_out IDispatch **ppForwarder +) +``` + +## Parameters + +## Property Value/Return Value + pDispatchDelegate + A pointer to an `IDispatch` interface. + + ppForwarder + A pointer to the address of an `IDispatch` interface. + +## Requirements + **Platforms:** See [.NET Framework System Requirements](/dotnet/framework/get-started/system-requirements). + + **DLL:** + + In the .NET Framework 3.0 and 3.5: PresentationHostDLL.dll + + In the .NET Framework 4 and later: PresentationHost_v0400.dll + + **.NET Framework Version:** [!INCLUDE[net_current_v30plus](../../../includes/net-current-v30plus-md.md)] + +## See also + +- [WPF Unmanaged API Reference](wpf-unmanaged-api-reference.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/creating-an-ink-input-control.md b/dotnet-desktop-guide/framework/wpf/advanced/creating-an-ink-input-control.md new file mode 100644 index 0000000000..5e5aee3c17 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/creating-an-ink-input-control.md @@ -0,0 +1,98 @@ +--- +title: "Creating an Ink Input Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "ink strokes [WPF], managing" + - "managing ink strokes [WPF]" + - "ink input control [WPF]" + - "input from mouse [WPF], accepting" + - "mouse input [WPF], accepting" + - "ink [WPF], rendering" + - "ink strokes [WPF], collecting" + - "rendering ink [WPF]" + - "collecting ink strokes [WPF]" + - "DynamicRenderer objects [WPF]" + - "StylusPlugIn objects [WPF]" +ms.assetid: c31f3a67-cb3f-4ded-af9e-ed21f6575b26 +--- +# Creating an Ink Input Control +You can create a custom control that dynamically and statically renders ink. That is, render ink as a user draws a stroke, causing the ink to appear to "flow" from the tablet pen, and display ink after it is added to the control, either via the tablet pen, pasted from the Clipboard, or loaded from a file. To dynamically render ink, your control must use a . To statically render ink, you must override the stylus event methods (, , and ) to collect data, create strokes, and add them to an (which renders the ink on the control). + + This topic contains the following subsections: + +- [How to: Collect Stylus Point Data and Create Ink Strokes](#CollectingStylusPointDataAndCreatingInkStrokes) + +- [How to: Enable Your Control to Accept Input from the Mouse](#EnablingYourControlToAcceptInputTromTheMouse) + +- [Putting it together](#PuttingItTogether) + +- [Using Additional Plug-ins and DynamicRenderers](#UsingAdditionalPluginsAndDynamicRenderers) + +- [Conclusion](#AdvancedInkHandling_Conclusion) + + +## How to: Collect Stylus Point Data and Create Ink Strokes + To create a control that collects and manages ink strokes do the following: + +1. Derive a class from or one of the classes derived from , such as . + + [!code-csharp[AdvancedInkTopicsSamples#20](~/samples/snippets/csharp/VS_Snippets_Wpf/AdvancedInkTopicsSamples/CSharp/StylusControl.cs#20)] + [!code-csharp[AdvancedInkTopicsSamples#14](~/samples/snippets/csharp/VS_Snippets_Wpf/AdvancedInkTopicsSamples/CSharp/StylusControlSnippets.cs#14)] + [!code-csharp[AdvancedInkTopicsSamples#15](~/samples/snippets/csharp/VS_Snippets_Wpf/AdvancedInkTopicsSamples/CSharp/StylusControlSnippets.cs#15)] + +2. Add an to the class and set the property to the new . + + [!code-csharp[AdvancedInkTopicsSamples#16](~/samples/snippets/csharp/VS_Snippets_Wpf/AdvancedInkTopicsSamples/CSharp/StylusControlSnippets.cs#16)] + +3. Attach the of the to the by calling the method, and add the to the collection. This allows the to display the ink as the stylus point data is collected by your control. + + [!code-csharp[AdvancedInkTopicsSamples#17](~/samples/snippets/csharp/VS_Snippets_Wpf/AdvancedInkTopicsSamples/CSharp/StylusControlSnippets.cs#17)] + [!code-csharp[AdvancedInkTopicsSamples#18](~/samples/snippets/csharp/VS_Snippets_Wpf/AdvancedInkTopicsSamples/CSharp/StylusControlSnippets.cs#18)] + +4. Override the method. In this method, capture the stylus with a call to . By capturing the stylus, your control will to continue to receive and events even if the stylus leaves the control's boundaries. This is not strictly mandatory, but almost always desired for a good user experience. Create a new to gather data. Finally, add the initial set of data to the . + + [!code-csharp[AdvancedInkTopicsSamples#7](~/samples/snippets/csharp/VS_Snippets_Wpf/AdvancedInkTopicsSamples/CSharp/StylusControl.cs#7)] + +5. Override the method and add the data to the object that you created earlier. + + [!code-csharp[AdvancedInkTopicsSamples#8](~/samples/snippets/csharp/VS_Snippets_Wpf/AdvancedInkTopicsSamples/CSharp/StylusControl.cs#8)] + +6. Override the method and create a new with the data. Add the new you created to the collection of the and release stylus capture. + + [!code-csharp[AdvancedInkTopicsSamples#10](~/samples/snippets/csharp/VS_Snippets_Wpf/AdvancedInkTopicsSamples/CSharp/StylusControl.cs#10)] + + +## How to: Enable Your Control to Accept Input from the Mouse + If you add the preceding control to your application, run it, and use the mouse as an input device, you will notice that the strokes are not persisted. To persist the strokes when the mouse is used as the input device do the following: + +1. Override the and create a new Get the position of the mouse when the event occurred and create a using the point data and add the to the . + + [!code-csharp[AdvancedInkTopicsSamples#11](~/samples/snippets/csharp/VS_Snippets_Wpf/AdvancedInkTopicsSamples/CSharp/StylusControl.cs#11)] + +2. Override the method. Get the position of the mouse when the event occurred and create a using the point data. Add the to the object that you created earlier. + + [!code-csharp[AdvancedInkTopicsSamples#12](~/samples/snippets/csharp/VS_Snippets_Wpf/AdvancedInkTopicsSamples/CSharp/StylusControl.cs#12)] + +3. Override the method. Create a new with the data, and add the new you created to the collection of the . + + [!code-csharp[AdvancedInkTopicsSamples#13](~/samples/snippets/csharp/VS_Snippets_Wpf/AdvancedInkTopicsSamples/CSharp/StylusControl.cs#13)] + + +## Putting it together + The following example is a custom control that collects ink when the user uses either the mouse or the pen. + + [!code-csharp[AdvancedInkTopicsSamples#20](~/samples/snippets/csharp/VS_Snippets_Wpf/AdvancedInkTopicsSamples/CSharp/StylusControl.cs#20)] +[!code-csharp[AdvancedInkTopicsSamples#6](~/samples/snippets/csharp/VS_Snippets_Wpf/AdvancedInkTopicsSamples/CSharp/StylusControl.cs#6)] + + +## Using Additional Plug-ins and DynamicRenderers + Like the InkCanvas, your custom control can have custom and additional objects. Add these to the collection. The order of the objects in the affects the appearance of the ink when it is rendered. Suppose you have a called `dynamicRenderer` and a custom called `translatePlugin` that offsets the ink from the tablet pen. If `translatePlugin` is the first in the , and `dynamicRenderer` is the second, the ink that "flows" will be offset as the user moves the pen. If `dynamicRenderer` is first, and `translatePlugin` is second, the ink will not be offset until the user lifts the pen. + + +## Conclusion + You can create a control that collects and renders ink by overriding the stylus event methods. By creating your own control, deriving your own classes, and inserting them the into , you can implement virtually any behavior imaginable with digital ink. You have access to the data as it is generated, giving you the opportunity to customize input and render it on the screen as appropriate for your application. Because you have such low-level access to the data, you can implement ink collection and render it with optimal performance for your application. + +## See also + +- [Advanced Ink Handling](advanced-ink-handling.md) +- [Accessing and Manipulating Pen Input](https://docs.microsoft.com/previous-versions/ms818317(v=msdn.10)) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/custom-dependency-properties.md b/dotnet-desktop-guide/framework/wpf/advanced/custom-dependency-properties.md new file mode 100644 index 0000000000..a4ae060d54 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/custom-dependency-properties.md @@ -0,0 +1,188 @@ +--- +title: "Custom Dependency Properties" +description: Learn about steps to implement a property in Windows Presentation Foundation, and options to improve performance, usability, or versatility of the property. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "implementing [WPF], wrappers" + - "registering properties [WPF]" + - "properties [WPF], metadata" + - "metadata [WPF], for properties" + - "custom dependency properties [WPF]" + - "properties [WPF], registering" + - "wrappers [WPF], implementing" + - "dependency properties [WPF], custom" +ms.assetid: e6bfcfac-b10d-4f58-9f77-a864c2a2938f +--- +# Custom Dependency Properties + +This topic describes the reasons that [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] application developers and component authors might want to create custom dependency property, and describes the implementation steps as well as some implementation options that can improve performance, usability, or versatility of the property. + + + +## Prerequisites + +This topic assumes that you understand dependency properties from the perspective of a consumer of existing dependency properties on [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] classes, and have read the [Dependency Properties Overview](dependency-properties-overview.md) topic. In order to follow the examples in this topic, you should also understand [!INCLUDE[TLA#tla_xaml](../../../includes/tlasharptla-xaml-md.md)] and know how to write [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] applications. + + + +## What Is a Dependency Property? + +You can enable what would otherwise be a common language runtime (CLR) property to support styling, data binding, inheritance, animations, and default values by implementing it as a dependency property. Dependency properties are properties that are registered with the [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] property system by calling the method (or ), and that are backed by a identifier field. Dependency properties can be used only by types, but is quite high in the [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] class hierarchy, so the majority of classes available in [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] can support dependency properties. For more information about dependency properties and some of the terminology and conventions used for describing them in this SDK, see [Dependency Properties Overview](dependency-properties-overview.md). + + + +## Examples of Dependency Properties + +Examples of dependency properties that are implemented on [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] classes include the property, the property, and the property, among many others. Each dependency property exposed by a class has a corresponding public static field of type exposed on that same class. This is the identifier for the dependency property. The identifier is named using a convention: the name of the dependency property with the string `Property` appended to it. For example, the corresponding identifier field for the property is . The identifier stores the information about the dependency property as it was registered, and the identifier is then used later for other operations involving the dependency property, such as calling . + +As mentioned in the [Dependency Properties Overview](dependency-properties-overview.md), all dependency properties in [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] (except most attached properties) are also CLR properties because of the "wrapper" implementation. Therefore, from code, you can get or set dependency properties by calling CLR accessors that define the wrappers in the same manner that you would use other CLR properties. As a consumer of established dependency properties, you do not typically use the methods and , which are the connection point to the underlying property system. Rather, the existing implementation of the CLR properties will have already called and within the `get` and `set` wrapper implementations of the property, using the identifier field appropriately. If you are implementing a custom dependency property yourself, then you will be defining the wrapper in a similar way. + + + +## When Should You Implement a Dependency Property? + +When you implement a property on a class, so long as your class derives from , you have the option to back your property with a identifier and thus to make it a dependency property. Having your property be a dependency property is not always necessary or appropriate, and will depend on your scenario needs. Sometimes, the typical technique of backing your property with a private field is adequate. However, you should implement your property as a dependency property whenever you want your property to support one or more of the following [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] capabilities: + +- You want your property to be settable in a style. For more information, see [Styling and Templating](/dotnet/desktop-wpf/fundamentals/styles-templates-overview). + +- You want your property to support data binding. For more information about data binding dependency properties, see [Bind the Properties of Two Controls](../data/how-to-bind-the-properties-of-two-controls.md). + +- You want your property to be settable with a dynamic resource reference. For more information, see [XAML Resources](/dotnet/desktop-wpf/fundamentals/xaml-resources-define). + +- You want to inherit a property value automatically from a parent element in the element tree. In this case, register with the method, even if you also create a property wrapper for CLR access. For more information, see [Property Value Inheritance](property-value-inheritance.md). + +- You want your property to be animatable. For more information, see [Animation Overview](../graphics-multimedia/animation-overview.md). + +- You want the property system to report when the previous value of the property has been changed by actions taken by the property system, the environment, or the user, or by reading and using styles. By using property metadata, your property can specify a callback method that will be invoked each time the property system determines that your property value was definitively changed. A related concept is property value coercion. For more information, see [Dependency Property Callbacks and Validation](dependency-property-callbacks-and-validation.md). + +- You want to use established metadata conventions that are also used by [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] processes, such as reporting whether changing a property value should require the layout system to recompose the visuals for an element. Or you want to be able to use metadata overrides so that derived classes can change metadata-based characteristics such as the default value. + +- You want properties of a custom control to receive Visual Studio WPF Designer support, such as **Properties** window editing. For more information, see [Control Authoring Overview](../controls/control-authoring-overview.md). + +When you examine these scenarios, you should also consider whether you can achieve your scenario by overriding the metadata of an existing dependency property, rather than implementing a completely new property. Whether a metadata override is practical depends on your scenario and how closely that scenario resembles the implementation in existing [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] dependency properties and classes. For more information about overriding metadata on existing properties, see [Dependency Property Metadata](dependency-property-metadata.md). + + + +## Checklist for Defining a Dependency Property + +Defining a dependency property consists of four distinct concepts. These concepts are not necessarily strict procedural steps, because some of these end up being combined as single lines of code in the implementation: + +- (Optional) Create property metadata for the dependency property. + +- Register the property name with the property system, specifying an owner type and the type of the property value. Also specify the property metadata, if used. + +- Define a identifier as a `public` `static` `readonly` field on the owner type. + +- Define a CLR "wrapper" property whose name matches the name of the dependency property. Implement the CLR "wrapper" property's `get` and `set` accessors to connect with the dependency property that backs it. + + + +### Registering the Property with the Property System + +In order for your property to be a dependency property, you must register that property into a table maintained by the property system, and give it a unique identifier that is used as the qualifier for later property system operations. These operations might be internal operations, or your own code calling property system APIs. To register the property, you call the method within the body of your class (inside the class, but outside of any member definitions). The identifier field is also provided by the method call, as the return value. The reason that the call is done outside of other member definitions is because you use this return value to assign and create a `public` `static` `readonly` field of type as part of your class. This field becomes the identifier for your dependency property. + +[!code-csharp[WPFAquariumSln#RegisterAG](~/samples/snippets/csharp/VS_Snippets_Wpf/WPFAquariumSln/CSharp/WPFAquariumObjects/Class1.cs#registerag)] +[!code-vb[WPFAquariumSln#RegisterAG](~/samples/snippets/visualbasic/VS_Snippets_Wpf/WPFAquariumSln/visualbasic/wpfaquariumobjects/class1.vb#registerag)] + + + +### Dependency Property Name Conventions + +There are established naming conventions regarding dependency properties that you must follow in all but exceptional circumstances. + +The dependency property itself will have a basic name, "AquariumGraphic" as in this example, which is given as the first parameter of . That name must be unique within each registering type. Dependency properties inherited through base types are considered to be already part of the registering type; names of inherited properties cannot be registered again. However, there is a technique for adding a class as owner of a dependency property even when that dependency property is not inherited; for details, see [Dependency Property Metadata](dependency-property-metadata.md). + +When you create the identifier field, name this field by the name of the property as you registered it, plus the suffix `Property`. This field is your identifier for the dependency property, and it will be used later as an input for the and calls you will make in the wrappers, by any other code access to the property by your own code, by any external code access you allow, by the property system, and potentially by [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] processors. + +> [!NOTE] +> Defining the dependency property in the class body is the typical implementation, but it is also possible to define a dependency property in the class static constructor. This approach might make sense if you need more than one line of code to initialize the dependency property. + + + +### Implementing the "Wrapper" + +Your wrapper implementation should call in the `get` implementation, and in the `set` implementation (the original registration call and field are shown here too for clarity). + +In all but exceptional circumstances, your wrapper implementations should perform only the and actions, respectively. The reason for this is discussed in the topic [XAML Loading and Dependency Properties](xaml-loading-and-dependency-properties.md). + +All existing public dependency properties that are provided on the [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] classes use this simple wrapper implementation model; most of the complexity of how dependency properties work is either inherently a behavior of the property system, or is implemented through other concepts such as coercion or property change callbacks through property metadata. + +[!code-csharp[WPFAquariumSln#AGWithWrapper](~/samples/snippets/csharp/VS_Snippets_Wpf/WPFAquariumSln/CSharp/WPFAquariumObjects/Class1.cs#agwithwrapper)] +[!code-vb[WPFAquariumSln#AGWithWrapper](~/samples/snippets/visualbasic/VS_Snippets_Wpf/WPFAquariumSln/visualbasic/wpfaquariumobjects/class1.vb#agwithwrapper)] + +Again, by convention, the name of the wrapper property must be the same as the name chosen and given as first parameter of the call that registered the property. If your property does not follow the convention, this does not necessarily disable all possible uses, but you will encounter several notable issues: + +- Certain aspects of styles and templates will not work. + +- Most tools and designers must rely on the naming conventions to properly serialize [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)], or to provide designer environment assistance at a per-property level. + +- The current implementation of the [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] loader bypasses the wrappers entirely, and relies on the naming convention when processing attribute values. For more information, see [XAML Loading and Dependency Properties](xaml-loading-and-dependency-properties.md). + + + +### Property Metadata for a New Dependency Property + +When you register a dependency property, the registration through the property system creates a metadata object that stores property characteristics. Many of these characteristics have defaults that are set if the property is registered with the simple signatures of . Other signatures of allow you to specify the metadata that you want as you register the property. The most common metadata given for dependency properties is to give them a default value that is applied on new instances that use the property. + +If you are creating a dependency property that exists on a derived class of , you can use the more specialized metadata class rather than the base class. The constructor for the class has several signatures where you can specify various metadata characteristics in combination. If you want to specify the default value only, use the signature that takes a single parameter of type . Pass that object parameter as a type-specific default value for your property (the default value provided must be the type you provided as the `propertyType` parameter in the call). + +For , you can also specify metadata option flags for your property. These flags are converted into discrete properties on the property metadata after registration and are used to communicate certain conditionals to other processes such as the layout engine. + +#### Setting Appropriate Metadata Flags + +- If your property (or changes in its value) affects the [!INCLUDE[TLA#tla_ui](../../../includes/tlasharptla-ui-md.md)], and in particular affects how the layout system should size or render your element in a page, set one or more of the following flags: , , . + + - indicates that a change to this property requires a change to [!INCLUDE[TLA2#tla_ui](../../../includes/tla2sharptla-ui-md.md)] rendering where the containing object might require more or less space within the parent. For example, a "Width" property should have this flag set. + + - indicates that a change to this property requires a change to [!INCLUDE[TLA2#tla_ui](../../../includes/tla2sharptla-ui-md.md)] rendering that typically does not require a change in the dedicated space, but does indicate that the positioning within the space has changed. For example, an "Alignment" property should have this flag set. + + - indicates that some other change has occurred that will not affect layout and measure, but does require another render. An example would be a property that changes a color of an existing element, such as "Background". + + - These flags are often used as a protocol in metadata for your own override implementations of property system or layout callbacks. For instance, you might have an callback that will call if any property of the instance reports a value change and has as `true` in its metadata. + +- Some properties may affect the rendering characteristics of the containing parent element, in ways above and beyond the changes in required size mentioned above. An example is the property used in the flow document model, where changes to that property can change the overall rendering of the flow document that contains the paragraph. Use or to identify similar cases in your own properties. + +- By default, dependency properties support data binding. You can deliberately disable data binding, for cases where there is no realistic scenario for data binding, or where performance in data binding for a large object is recognized as a problem. + +- By default, data binding for dependency properties defaults to . You can always change the binding to be per binding instance; for details, see [Specify the Direction of the Binding](../data/how-to-specify-the-direction-of-the-binding.md). But as the dependency property author, you can choose to make the property use binding mode by default. An example of an existing dependency property is ; the scenario for this property is that the setting logic and the compositing of interact with the default theme style. The property logic uses data binding natively to maintain the state of the property in accordance to other state properties and method calls. Another example property that binds by default is . + +- You can also enable property inheritance in a custom dependency property by setting the flag. Property inheritance is useful for a scenario where parent elements and child elements have a property in common, and it makes sense for the child elements to have that particular property value set to the same value as the parent set it. An example inheritable property is , which is used for binding operations to enable the important master-detail scenario for data presentation. By making inheritable, any child elements inherit that data context also. Because of property value inheritance, you can specify a data context at the page or application root, and do not need to respecify it for bindings in all possible child elements. is also a good example to illustrate that inheritance overrides the default value, but it can always be set locally on any particular child element; for details, see [Use the Master-Detail Pattern with Hierarchical Data](../data/how-to-use-the-master-detail-pattern-with-hierarchical-data.md). Property value inheritance does have a possible performance cost, and thus should be used sparingly; for details, see [Property Value Inheritance](property-value-inheritance.md). + +- Set the flag to indicate if your dependency property should be detected or used by navigation journaling services. An example is the property; any item selected in a selection control should be persisted when the journaling history is navigated. + + + +## Read-Only Dependency Properties + +You can define a dependency property that is read-only. However, the scenarios for why you might define your property as read-only are somewhat different, as is the procedure for registering them with the property system and exposing the identifier. For more information, see [Read-Only Dependency Properties](read-only-dependency-properties.md). + + + +## Collection-Type Dependency Properties + +Collection-type dependency properties have some additional implementation issues to consider. For details, see [Collection-Type Dependency Properties](collection-type-dependency-properties.md). + + + +## Dependency Property Security Considerations + +Dependency properties should be declared as public properties. Dependency property identifier fields should be declared as public static fields. Even if you attempt to declare other access levels (such as protected), a dependency property can always be accessed through the identifier in combination with the property system APIs. Even a protected identifier field is potentially accessible because of metadata reporting or value determination APIs that are part of the property system, such as . For more information, see [Dependency Property Security](dependency-property-security.md). + + + +## Dependency Properties and Class Constructors + +There is a general principle in managed code programming (often enforced by code analysis tools such as FxCop) that class constructors should not call virtual methods. This is because constructors can be called as base initialization of a derived class constructor, and entering the virtual method through the constructor might occur at an incomplete initialization state of the object instance being constructed. When you derive from any class that already derives from , you should be aware that the property system itself calls and exposes virtual methods internally. These virtual methods are part of the [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] property system services. Overriding the methods enables derived classes to participate in value determination. To avoid potential issues with runtime initialization, you should not set dependency property values within constructors of classes, unless you follow a very specific constructor pattern. For details, see [Safe Constructor Patterns for DependencyObjects](safe-constructor-patterns-for-dependencyobjects.md). + +## See also + +- [Dependency Properties Overview](dependency-properties-overview.md) +- [Dependency Property Metadata](dependency-property-metadata.md) +- [Control Authoring Overview](../controls/control-authoring-overview.md) +- [Collection-Type Dependency Properties](collection-type-dependency-properties.md) +- [Dependency Property Security](dependency-property-security.md) +- [XAML Loading and Dependency Properties](xaml-loading-and-dependency-properties.md) +- [Safe Constructor Patterns for DependencyObjects](safe-constructor-patterns-for-dependencyobjects.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/custom-rendering-ink.md b/dotnet-desktop-guide/framework/wpf/advanced/custom-rendering-ink.md new file mode 100644 index 0000000000..4d5280685c --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/custom-rendering-ink.md @@ -0,0 +1,90 @@ +--- +title: "Custom Rendering Ink" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "custom-rendering ink" + - "ink [WPF], custom-rendering" + - "classes [WPF], InkCanvas" +ms.assetid: 65c978a7-0ee0-454f-ac7f-b1bd2efecac5 +--- +# Custom Rendering Ink +The property of a stroke allows you to specify the appearance of a stroke, such as its size, color, and shape, but there may be times that you want to customize the appearance beyond what allow. You may want to customize the appearance of ink by rendering in the appearance of an air brush, oil paint, and many other effects. The Windows Presentation Foundation (WPF) allows you to custom render ink by implementing a custom and object. + + This topic contains the following subsections: + +- [Architecture](#Architecture) + +- [Implementing a Dynamic Renderer](#ImplementingADynamicRenderer) + +- [Implementing Custom Strokes](#ImplementingCustomStrokes) + +- [Implementing a Custom InkCanvas](#ImplementingACustomInkCanvas) + +- [Conclusion](#Conclusion) + + +## Architecture + Ink rendering occurs two times; when a user writes ink to an inking surface, and again after the stroke is added to the ink-enabled surface. The renders the ink when the user moves the tablet pen on the digitizer, and the renders itself once it is added to an element. + + There are three classes to implement when dynamically rendering ink. + +1. **DynamicRenderer**: Implement a class that derives from . This class is a specialized that renders the stroke as it is drawn. The does the rendering on a separate thread, so the inking surface appears to collect ink even when the application user interface (UI) thread is blocked. For more information about the threading model, see [The Ink Threading Model](the-ink-threading-model.md). To customize dynamically rendering a stroke, override the method. + +2. **Stroke**: Implement a class that derives from . This class is responsible for static rendering of the data after it has been converted into a object. Override the method to ensure that static rendering of the stroke is consistent with dynamic rendering. + +3. **InkCanvas:** Implement a class that derives from . Assign the customized to the property. Override the method and add a custom stroke to the property. This ensures that the appearance of the ink is consistent. + + +## Implementing a Dynamic Renderer + Although the class is a standard part of [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)], to perform more specialized rendering, you must create a customized dynamic renderer that derives from the and override the method. + + The following example demonstrates a customized that draws ink with a linear gradient brush effect. + + [!code-csharp[AdvancedInkTopicsSamples#19](~/samples/snippets/csharp/VS_Snippets_Wpf/AdvancedInkTopicsSamples/CSharp/DynamicRenderer.cs#19)] + [!code-vb[AdvancedInkTopicsSamples#19](~/samples/snippets/visualbasic/VS_Snippets_Wpf/AdvancedInkTopicsSamples/VisualBasic/DynamicRenderer.vb#19)] +[!code-csharp[AdvancedInkTopicsSamples#1](~/samples/snippets/csharp/VS_Snippets_Wpf/AdvancedInkTopicsSamples/CSharp/DynamicRenderer.cs#1)] +[!code-vb[AdvancedInkTopicsSamples#1](~/samples/snippets/visualbasic/VS_Snippets_Wpf/AdvancedInkTopicsSamples/VisualBasic/DynamicRenderer.vb#1)] + + +## Implementing Custom Strokes + Implement a class that derives from . This class is responsible for rendering data after it has been converted into a object. Override the class to do the actual drawing. + + Your Stroke class can also store custom data by using the method. This data is stored with the stroke data when persisted. + + The class can also perform hit testing. You can also implement your own hit testing algorithm by overriding the method in the current class. + + The following C# code demonstrates a custom class that renders data as a 3D stroke. + + [!code-csharp[AdvancedInkTopicsSamples#19](~/samples/snippets/csharp/VS_Snippets_Wpf/AdvancedInkTopicsSamples/CSharp/DynamicRenderer.cs#19)] + [!code-vb[AdvancedInkTopicsSamples#19](~/samples/snippets/visualbasic/VS_Snippets_Wpf/AdvancedInkTopicsSamples/VisualBasic/DynamicRenderer.vb#19)] +[!code-csharp[AdvancedInkTopicsSamples#2](~/samples/snippets/csharp/VS_Snippets_Wpf/AdvancedInkTopicsSamples/CSharp/DynamicRenderer.cs#2)] +[!code-vb[AdvancedInkTopicsSamples#2](~/samples/snippets/visualbasic/VS_Snippets_Wpf/AdvancedInkTopicsSamples/VisualBasic/DynamicRenderer.vb#2)] + + +## Implementing a Custom InkCanvas + The easiest way to use your customized and stroke is to implement a class that derives from and uses these classes. The has a property that specifies how the stroke is rendered when the user is drawing it. + + To custom render strokes on an do the following: + +- Create a class that derives from the . + +- Assign your customized to the property. + +- Override the method. In this method, remove the original stroke that was added to the InkCanvas. Then create a custom stroke, add it to the property, and call the base class with a new that contains the custom stroke. + + The following C# code demonstrates a custom class that uses a customized and collects custom strokes. + + [!code-csharp[AdvancedInkTopicsSamples#9](~/samples/snippets/csharp/VS_Snippets_Wpf/AdvancedInkTopicsSamples/CSharp/Window1.xaml.cs#9)] + + An can have more than one . You can add multiple objects to the by adding them to the property. + + +## Conclusion + You can customize the appearance of ink by deriving your own , , and classes. Together, these classes ensure that the appearance of the stroke is consistent when the user draws the stroke and after it is collected. + +## See also + +- [Advanced Ink Handling](advanced-ink-handling.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/data-and-data-objects.md b/dotnet-desktop-guide/framework/wpf/advanced/data-and-data-objects.md new file mode 100644 index 0000000000..94c0bf18d3 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/data-and-data-objects.md @@ -0,0 +1,91 @@ +--- +title: "Data and Data Objects" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "data transfer [WPF], drag-and-drop" + - "DataFormats class [WPF]" + - "DataObject class [WPF]" +ms.assetid: 5967d557-1867-420f-a524-ae3af78402da +--- +# Data and Data Objects +Data that is transferred as part of a drag-and-drop operation is stored in a data object. Conceptually, a data object consists of one or more of the following pairs: + +- An that contains the actual data. + +- A corresponding data format identifier. + + The data itself can consist of anything that can be represented as a base . The corresponding data format is a string or that provides a hint about what format the data is in. Data objects support hosting multiple data/data format pairs; this enables a single data object to provide data in multiple formats. + + +## Data Objects + All data objects must implement the interface, which provides the following standard set of methods that enable and facilitate data transfer. + +|Method|Summary| +|------------|-------------| +||Retrieves a data object in a specified data format.| +||Checks to see whether the data is available in, or can be converted to, a specified format.| +||Returns a list of formats that the data in this data object is stored in, or can be converted to.| +||Stores the specified data in this data object.| + + [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] provides a basic implementation of in the class. The stock class is sufficient for many common data transfer scenarios. + + There are several pre-defined formats, such as bitmap, CSV, file, HTML, RTF, string, text, and audio. For information about pre-defined data formats provided with [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)], see the class reference topic. + + Data objects commonly include a facility for automatically converting data stored in one format to a different format while extracting data; this facility is referred to as auto-convert. When querying for the data formats available in a data object, auto-convertible data formats can be filtered from native data formats by calling the or method and specifying the `autoConvert` parameter as `false`. When adding data to a data object with the method, auto-conversion of data can be prohibited by setting the `autoConvert` parameter to `false`. + + +## Working with Data Objects + This section describes common techniques for creating and working with data objects. + +### Creating New Data Objects + The class provides several overloaded constructors that facilitate populating a new instance with a single data/data format pair. + + The following example code creates a new data object and uses one of the overloaded constructors () to initialize the data object with a string and a specified data format. In this case, the data format is specified by a string; the class provides a set of pre-defined type strings. Auto-conversion of the stored data is allowed by default. + + [!code-csharp[DragDrop_DragDropMiscCode#_DragDrop_CreateDataObject_TypeString](~/samples/snippets/csharp/VS_Snippets_Wpf/DragDrop_DragDropMiscCode/CSharp/Window1.xaml.cs#_dragdrop_createdataobject_typestring)] + [!code-vb[DragDrop_DragDropMiscCode#_DragDrop_CreateDataObject_TypeString](~/samples/snippets/visualbasic/VS_Snippets_Wpf/DragDrop_DragDropMiscCode/visualbasic/window1.xaml.vb#_dragdrop_createdataobject_typestring)] + + For more examples of code that creates a data object, see [Create a Data Object](how-to-create-a-data-object.md). + +### Storing Data in Multiple Formats + A single data object is able to store data in multiple formats. Strategic use of multiple data formats within a single data object potentially makes the data object consumable by a wider variety of drop targets than if only a single data format could be represented. Note that, in general, a drag source must be agnostic about the data formats that are consumable by potential drop targets. + + The following example shows how to use the method to add data to a data object in multiple formats. + + [!code-csharp[DragDrop_DragDropMiscCode#_DragDrop_StoreMultipleFormats](~/samples/snippets/csharp/VS_Snippets_Wpf/DragDrop_DragDropMiscCode/CSharp/Window1.xaml.cs#_dragdrop_storemultipleformats)] + [!code-vb[DragDrop_DragDropMiscCode#_DragDrop_StoreMultipleFormats](~/samples/snippets/visualbasic/VS_Snippets_Wpf/DragDrop_DragDropMiscCode/visualbasic/window1.xaml.vb#_dragdrop_storemultipleformats)] + +### Querying a Data Object for Available Formats + Because a single data object can contain an arbitrary number of data formats, data objects include facilities for retrieving a list of available data formats. + + The following example code uses the overload to get an array of strings denoting all data formats available in a data object (both native and by auto-convert). + + [!code-csharp[DragDrop_DragDropMiscCode#_DragDrop_GetAllDataFormats](~/samples/snippets/csharp/VS_Snippets_Wpf/DragDrop_DragDropMiscCode/CSharp/Window1.xaml.cs#_dragdrop_getalldataformats)] + [!code-vb[DragDrop_DragDropMiscCode#_DragDrop_GetAllDataFormats](~/samples/snippets/visualbasic/VS_Snippets_Wpf/DragDrop_DragDropMiscCode/visualbasic/window1.xaml.vb#_dragdrop_getalldataformats)] + + For more examples of code that queries a data object for available data formats, see [List the Data Formats in a Data Object](how-to-list-the-data-formats-in-a-data-object.md). For examples of querying a data object for the presence of a particular data format, see [Determine if a Data Format is Present in a Data Object](how-to-determine-if-a-data-format-is-present-in-a-data-object.md). + +### Retrieving Data from a Data Object + Retrieving data from a data object in a particular format simply involves calling one of the methods and specifying the desired data format. One of the methods can be used to check for the presence of a particular data format. returns the data in an ; depending on the data format, this object can be cast to a type-specific container. + + The following example code uses the overload to check if a specified data format is available (native or by auto-convert). If the specified format is available, the example retrieves the data by using the method. + + [!code-csharp[DragDrop_DragDropMiscCode#_DragDrop_GetSpecificDataFormat](~/samples/snippets/csharp/VS_Snippets_Wpf/DragDrop_DragDropMiscCode/CSharp/Window1.xaml.cs#_dragdrop_getspecificdataformat)] + [!code-vb[DragDrop_DragDropMiscCode#_DragDrop_GetSpecificDataFormat](~/samples/snippets/visualbasic/VS_Snippets_Wpf/DragDrop_DragDropMiscCode/visualbasic/window1.xaml.vb#_dragdrop_getspecificdataformat)] + + For more examples of code that retrieves data from a data object, see [Retrieve Data in a Particular Data Format](how-to-retrieve-data-in-a-particular-data-format.md). + +### Removing Data From a Data Object + Data cannot be directly removed from a data object. To effectively remove data from a data object, follow these steps: + +1. Create a new data object that will contain only the data you want to retain. + +2. "Copy" the desired data from the old data object to the new data object. To copy the data, use one of the methods to retrieve an that contains the raw data, and then use one of the methods to add the data to the new data object. + +3. Replace the old data object with the new one. + +> [!NOTE] +> The methods only add data to a data object; they do not replace data, even if the data and data format are exactly the same as a previous call. Calling twice for the same data and data format will result in the data/data format being present twice in the data object. diff --git a/dotnet-desktop-guide/framework/wpf/advanced/datetime-xaml-syntax.md b/dotnet-desktop-guide/framework/wpf/advanced/datetime-xaml-syntax.md new file mode 100644 index 0000000000..29b40c1643 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/datetime-xaml-syntax.md @@ -0,0 +1,72 @@ +--- +title: "DateTime XAML Syntax" +ms.date: "03/30/2017" +helpviewer_keywords: + - "DateTime XAML syntax [WPF], strings for" + - "DateTime XAML syntax [WPF], where used" + - "short date format [WPF], DateTime" + - "DateTime XAML syntax [WPF]" + - "DateTime XAML text [WPF]" + - "DateTime XAML syntax [WPF], format strings for" +ms.assetid: 5901710a-609b-40c8-9d65-f0016cd9090b +--- +# DateTime XAML Syntax +Some controls, such as and , have properties that use the type. Although you typically specify an initial date or time for these controls in the code-behind at run time, you can specify an initial date or time in XAML. The WPF XAML parser handles parsing of values using a built-in XAML text syntax. This topic describes the specifics of the XAML text syntax. + + +## When To Use DateTime XAML Syntax + Setting dates in XAML is not always necessary and may not even be desirable. For example, you could use the property to initialize a date at run time, or you could do all your date adjustments for a calendar in the code-behind based on user input. However, there are scenarios where you may want to hard-code dates into a and in a control template. The XAML syntax must be used for these scenarios. + +### DateTime XAML Syntax is a Native Behavior + is a class that is defined in the base class libraries of the CLR. Because of how the base class libraries relate to the rest of the CLR, it is not possible to apply to the class and use a type converter to process strings from XAML and convert them to in the run time object model. There is no `DateTimeConverter` class that provides the conversion behavior; the conversion behavior described in this topic is native to the WPF XAML parser. + + +## Format Strings for DateTime XAML Syntax + You can specify the format of a with a format string. Format strings formalize the text syntax that can be used to create a value. values for the existing WPF controls generally only use the date components of and not the time components. + + When specifying a in XAML, you can use any of the format strings interchangeably. + + You can also use formats and format strings that are not specifically shown in this topic. Technically, the XAML for any value that is specified and then parsed by the WPF XAML parser uses an internal call to , therefore you could use any string accepted by for your XAML input. For more information, see . + +> [!IMPORTANT] +> The DateTime XAML syntax always uses `en-us` as the for its native conversion. This is not influenced by value or `xml:lang` value in the XAML, because XAML attribute-level type conversion acts without that context. Do not attempt to interpolate the format strings shown here due to cultural variations, such as the order in which day and month appear. The format strings shown here are the exact format strings used when parsing the XAML regardless of other culture settings. + + The following sections describe some of the common format strings. + +### Short Date Pattern ("d") + The following shows the short date format for a in XAML: + + `M/d/YYYY` + + This is the simplest form that specifies all necessary information for typical usages by WPF controls, and cannot be influenced by accidental time zone offsets versus a time component, and is therefore recommended over the other formats. + + For example, to specify the date of June 1, 2010, use the following string: + + `3/1/2010` + + For more information, see . + +### Sortable DateTime Pattern ("s") + The following shows the sortable pattern in XAML: + + `yyyy'-'MM'-'dd'T'HH':'mm':'ss` + + For example, to specify the date of June 1, 2010, use the following string (time components are all entered as 0): + + `2010-06-01T000:00:00` + +### RFC1123 Pattern ("r") + The RFC1123 pattern is useful because it could be a string input from other date generators that also use the RFC1123 pattern for culture invariant reasons. The following shows the RFC1123 pattern in XAML: + + `ddd, dd MMM yyyy HH':'mm':'ss 'UTC'` + + For example, to specify the date of June 1, 2010, use the following string (time components are all entered as 0): + + `Mon, 01 Jun 2010 00:00:00 UTC` + +### Other Formats and Patterns + As stated previously, a in XAML can be specified as any string that is acceptable as input for . This includes other formalized formats (for example ), and formats that are not formalized as a particular form. For example, the form `YYYY/mm/dd` is acceptable as input for . This topic does not attempt to describe all possible formats that work, and instead recommends the short date pattern as a standard practice. + +## See also + +- [XAML Overview (WPF)](/dotnet/desktop-wpf/fundamentals/xaml) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/deactivate-function-wpf-unmanaged-api-reference.md b/dotnet-desktop-guide/framework/wpf/advanced/deactivate-function-wpf-unmanaged-api-reference.md new file mode 100644 index 0000000000..9dce8e3ec1 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/deactivate-function-wpf-unmanaged-api-reference.md @@ -0,0 +1,37 @@ +--- +title: "Deactivate Function - WPF unmanaged API reference" +titleSuffix: "" +ms.date: "03/30/2017" +dev_langs: + - "cpp" +api_name: + - "Deactivate" +api_location: + - "PresentationHost_v0400.dll" +ms.assetid: 3e81be16-24c7-4399-b242-6268feaa49d7 +--- +# Deactivate Function (WPF Unmanaged API Reference) +This API supports the Windows Presentation Foundation (WPF) infrastructure and is not intended to be used directly from your code. + + Used by the Windows Presentation Foundation (WPF) infrastructure for windows management. + +## Syntax + +```cpp +void Deactivate() +``` + +## Requirements + **Platforms:** See [.NET Framework System Requirements](/dotnet/framework/get-started/system-requirements). + + **DLL:** + + In the .NET Framework 3.0 and 3.5: PresentationHostDLL.dll + + In the .NET Framework 4 and later: PresentationHost_v0400.dll + + **.NET Framework Version:** [!INCLUDE[net_current_v30plus](../../../includes/net-current-v30plus-md.md)] + +## See also + +- [WPF Unmanaged API Reference](wpf-unmanaged-api-reference.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/dependency-properties-overview.md b/dotnet-desktop-guide/framework/wpf/advanced/dependency-properties-overview.md new file mode 100644 index 0000000000..eb5228a617 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/dependency-properties-overview.md @@ -0,0 +1,198 @@ +--- +title: "Dependency properties overview" +description: A property that is backed by the WPF property system is known as a dependency property. This overview describes the WPF property system and the capabilities of a dependency property. +ms.date: "06/06/2018" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "properties [WPF], attached" + - "properties [WPF], overview" + - "styles [WPF]" + - "attached properties [WPF]" + - "data binding [WPF]" + - "dependency properties [WPF]" + - "resources [WPF], references to" +ms.assetid: d119d00c-3afb-48d6-87a0-c4da4f83dee5 +--- +# Dependency properties overview + +Windows Presentation Foundation (WPF) provides a set of services that can be used to extend the functionality of a type's [property](/dotnet/standard/base-types/common-type-syste#properties). Collectively, these services are typically referred to as the WPF property system. A property that is backed by the WPF property system is known as a dependency property. This overview describes the WPF property system and the capabilities of a dependency property. This includes how to use existing dependency properties in XAML and in code. This overview also introduces specialized aspects of dependency properties, such as dependency property metadata, and how to create your own dependency property in a custom class. + +## Prerequisites +This topic assumes that you have some basic knowledge of the .NET type system and object-oriented programming. In order to follow the examples in this topic, you should also understand XAML and know how to write WPF applications. For more information, see [Walkthrough: My first WPF desktop application](../getting-started/walkthrough-my-first-wpf-desktop-application.md). + +## Dependency properties and CLR properties + In WPF, properties are typically exposed as standard .NET [properties](/dotnet/standard/base-types/common-type-syste#properties). At a basic level, you could interact with these properties directly and never know that they are implemented as a dependency property. However, you should become familiar with some or all of the features of the WPF property system, so that you can take advantage of these features. + +The purpose of dependency properties is to provide a way to compute the value of a property based on the value of other inputs. These other inputs might include system properties such as themes and user preference, just-in-time property determination mechanisms such as data binding and animations/storyboards, multiple-use templates such as resources and styles, or values known through parent-child relationships with other elements in the element tree. In addition, a dependency property can be implemented to provide self-contained validation, default values, callbacks that monitor changes to other properties, and a system that can coerce property values based on potentially runtime information. Derived classes can also change some specific characteristics of an existing property by overriding dependency property metadata, rather than overriding the actual implementation of existing properties or creating new properties. + +In the SDK reference, you can identify which property is a dependency property by the presence of the Dependency Property Information section on the managed reference page for that property. The Dependency Property Information section includes a link to the identifier field for that dependency property, and also includes a list of the metadata options that are set for that property, per-class override information, and other details. + +## Dependency properties back CLR properties +Dependency properties and the WPF property system extend property functionality by providing a type that backs a property, as an alternative implementation to the standard pattern of backing the property with a private field. The name of this type is . The other important type that defines the WPF property system is . defines the base class that can register and own a dependency property. + +The following lists the terminology that is used with dependency properties: + +- **Dependency property:** A property that is backed by a . + +- **Dependency property identifier:** A instance, which is obtained as a return value when registering a dependency property, and then stored as a static member of a class. This identifier is used as a parameter for many of the APIs that interact with the WPF property system. + +- **CLR "wrapper":** The actual get and set implementations for the property. These implementations incorporate the dependency property identifier by using it in the and calls, thus providing the backing for the property using the WPF property system. + +The following example defines the `IsSpinning` dependency property, and shows the relationship of the identifier to the property that it backs. + +[!code-csharp[PropertiesOvwSupport#DPFormBasic](~/samples/snippets/csharp/VS_Snippets_Wpf/PropertiesOvwSupport/CSharp/page4.xaml.cs#dpformbasic)] +[!code-vb[PropertiesOvwSupport#DPFormBasic](~/samples/snippets/visualbasic/VS_Snippets_Wpf/PropertiesOvwSupport/visualbasic/page4.xaml.vb#dpformbasic)] + +The naming convention of the property and its backing field is important. The name of the field is always the name of the property, with the suffix `Property` appended. For more information about this convention and the reasons for it, see [Custom Dependency Properties](custom-dependency-properties.md). + +## Setting property values +You can set properties either in code or in XAML. + +### Setting property values in XAML +The following XAML example specifies the background color of a button as red. This example illustrates a case where the simple string value for a XAML attribute is type-converted by the WPF XAML parser into a WPF type (a , by way of a ) in the generated code. + +[!code-xaml[PropertiesOvwSupport#MostBasicProperty](~/samples/snippets/csharp/VS_Snippets_Wpf/PropertiesOvwSupport/CSharp/Page1.xaml#mostbasicproperty)] + +XAML supports a variety of syntax forms for setting properties. Which syntax to use for a particular property will depend on the value type that a property uses, as well as other factors such as the presence of a type converter. For more information on XAML syntax for property setting, see [XAML Overview (WPF)](/dotnet/desktop-wpf/fundamentals/xaml) and [XAML Syntax In Detail](xaml-syntax-in-detail.md). + +As an example of non-attribute syntax, the following XAML example shows another button background. This time rather than setting a simple solid color, the background is set to an image, with an element representing that image and the source of that image specified as an attribute of the nested element. This is an example of property element syntax. + +[!code-xaml[PropertiesOvwSupport#PESyntaxProperty](~/samples/snippets/csharp/VS_Snippets_Wpf/PropertiesOvwSupport/CSharp/Page1.xaml#pesyntaxproperty)] + +### Setting properties in code + Setting dependency property values in code is typically just a call to the set implementation exposed by the CLR "wrapper". + +[!code-csharp[PropertiesOvwSupport#ProceduralPropertySet](~/samples/snippets/csharp/VS_Snippets_Wpf/PropertiesOvwSupport/CSharp/Page1.xaml.cs#proceduralpropertyset)] +[!code-vb[PropertiesOvwSupport#ProceduralPropertySet](~/samples/snippets/visualbasic/VS_Snippets_Wpf/PropertiesOvwSupport/visualbasic/page1.xaml.vb#proceduralpropertyset)] + +Getting a property value is also essentially a call to the get "wrapper" implementation: + +[!code-csharp[PropertiesOvwSupport#ProceduralPropertyGet](~/samples/snippets/csharp/VS_Snippets_Wpf/PropertiesOvwSupport/CSharp/Page1.xaml.cs#proceduralpropertyget)] + [!code-vb[PropertiesOvwSupport#ProceduralPropertyGet](~/samples/snippets/visualbasic/VS_Snippets_Wpf/PropertiesOvwSupport/visualbasic/page1.xaml.vb#proceduralpropertyget)] + +You can also call the property system APIs and directly. This is not typically necessary if you are using existing properties (the wrappers are more convenient, and provide better exposure of the property for developer tools), but calling the APIs directly is appropriate for certain scenarios. + +Properties can be also set in XAML and then accessed later in code, through code-behind. For details, see [Code-Behind and XAML in WPF](code-behind-and-xaml-in-wpf.md). + +## Property functionality provided by a dependency property +A dependency property provides functionality that extends the functionality of a property as opposed to a property that is backed by a field. Often, such functionality represents or supports one of the following specific features: + +- [Resources](#resources) + +- [Data binding](#data-binding) + +- [Styles](#styles) + +- [Animations](#animations) + +- [Metadata overrides](#metadata-overrides) + +- [Property value inheritance](#property-value-inheritance) + +- [WPF Designer integration](#wpf-designer-integration) + +### Resources +A dependency property value can be set by referencing a resource. Resources are typically specified as the `Resources` property value of a page root element, or of the application (these locations enable the most convenient access to the resource). The following example shows how to define a resource. + +[!code-xaml[PropertiesOvwSupport#ResourcesResource](~/samples/snippets/csharp/VS_Snippets_Wpf/PropertiesOvwSupport/CSharp/page2.xaml#resourcesresource)] + +Once the resource is defined, you can reference the resource and use it to provide a property value: + +[!code-xaml[PropertiesOvwSupport#ResourcesReference](~/samples/snippets/csharp/VS_Snippets_Wpf/PropertiesOvwSupport/CSharp/page2.xaml#resourcesreference)] + +This particular resource is referenced as a [DynamicResource Markup Extension](dynamicresource-markup-extension.md) (in WPF XAML, you can use either a static or dynamic resource reference). To use a dynamic resource reference, you must be setting to a dependency property, so it is specifically the dynamic resource reference usage that is enabled by the WPF property system. For more information, see [XAML Resources](/dotnet/desktop-wpf/fundamentals/xaml-resources-define). + +> [!NOTE] +> Resources are treated as a local value, which means that if you set another local value, you will eliminate the resource reference. For more information, see [Dependency Property Value Precedence](dependency-property-value-precedence.md). + +### Data binding +A dependency property can reference a value through data binding. Data binding works through a specific markup extension syntax in XAML, or the object in code. With data binding, the final property value determination is deferred until run time, at which time the value is obtained from a data source. + +The following example sets the property for a , using a binding declared in XAML. The binding uses an inherited data context and an data source (not shown). The binding itself specifies the desired source property by within the data source. + +[!code-xaml[PropertiesOvwSupport#BasicInlineBinding](~/samples/snippets/csharp/VS_Snippets_Wpf/PropertiesOvwSupport/CSharp/page3.xaml#basicinlinebinding)] + +> [!NOTE] +> Bindings are treated as a local value, which means that if you set another local value, you will eliminate the binding. For details, see [Dependency Property Value Precedence](dependency-property-value-precedence.md). + +Dependency properties, or the class, do not natively support for purposes of producing notifications of changes in source property value for data binding operations. For more information on how to create properties for use in data binding that can report changes to a data binding target, see [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview). + +### Styles +Styles and templates are two of the chief motivating scenarios for using dependency properties. Styles are particularly useful for setting properties that define application [!INCLUDE[TLA#tla_ui](../../../includes/tlasharptla-ui-md.md)]. Styles are typically defined as resources in XAML. Styles interact with the property system because they typically contain "setters" for particular properties, as well as "triggers" that change a property value based on the real-time value for another property. + +The following example creates a simple style (which would be defined inside a dictionary, not shown), then applies that style directly to the property for a . The setter within the style sets the property for a styled to green. + +[!code-xaml[PropertiesOvwSupport#SimpleStyleDef](~/samples/snippets/csharp/VS_Snippets_Wpf/PropertiesOvwSupport/CSharp/page3.xaml#simplestyledef)] + +[!code-xaml[PropertiesOvwSupport#SimpleStyle](~/samples/snippets/csharp/VS_Snippets_Wpf/PropertiesOvwSupport/CSharp/page3.xaml#simplestyle)] + +For more information, see [Styling and Templating](/dotnet/desktop-wpf/fundamentals/styles-templates-overview). + +### Animations +Dependency properties can be animated. When an animation is applied and is running, the animated value operates at a higher precedence than any value (such as a local value) that the property otherwise has. + +The following example animates the on a property (technically, the is animated by using property element syntax to specify a blank as the , then the property of that is the property that is directly animated). + +[!code-xaml[PropertiesOvwSupport#MiniAnimate](~/samples/snippets/csharp/VS_Snippets_Wpf/PropertiesOvwSupport/CSharp/page3.xaml#minianimate)] + +For more information on animating properties, see [Animation Overview](../graphics-multimedia/animation-overview.md) and [Storyboards Overview](../graphics-multimedia/storyboards-overview.md). + +### Metadata overrides +You can change certain behaviors of a dependency property by overriding the metadata for that property when you derive from the class that originally registers the dependency property. Overriding metadata relies on the identifier. Overriding metadata does not require reimplementing the property. The metadata change is handled natively by the property system; each class potentially holds individual metadata for all properties that are inherited from base classes, on a per-type basis. + +The following example overrides metadata for a dependency property . Overriding this particular dependency property metadata is part of an implementation pattern that creates controls that can use default styles from themes. + +[!code-csharp[PropertiesOvwSupport#OverrideMetadata](~/samples/snippets/csharp/VS_Snippets_Wpf/PropertiesOvwSupport/CSharp/page3.xaml.cs#overridemetadata)] +[!code-vb[PropertiesOvwSupport#OverrideMetadata](~/samples/snippets/visualbasic/VS_Snippets_Wpf/PropertiesOvwSupport/visualbasic/page3.xaml.vb#overridemetadata)] + +For more information about overriding or obtaining property metadata, see [Dependency Property Metadata](dependency-property-metadata.md). + +### Property value inheritance +An element can inherit the value of a dependency property from its parent in the object tree. + +> [!NOTE] +> Property value inheritance behavior is not globally enabled for all dependency properties, because the calculation time for inheritance does have some performance impact. Property value inheritance is typically only enabled for properties where a particular scenario suggests that property value inheritance is appropriate. You can determine whether a dependency property inherits by looking at the **Dependency Property Information** section for that dependency property in the SDK reference. + +The following example shows a binding, and sets the property that specifies the source of the binding, which was not shown in the earlier binding example. Any subsequent bindings in child objects do not need to specify the source, they can use the inherited value from in the parent object. (Alternatively, a child object could instead choose to directly specify its own or a in the , and to deliberately not use the inherited value for data context of its bindings.) + +[!code-xaml[PropertiesOvwSupport#InheritanceContext](~/samples/snippets/csharp/VS_Snippets_Wpf/PropertiesOvwSupport/CSharp/page3.xaml#inheritancecontext)] + +For more information, see [Property Value Inheritance](property-value-inheritance.md). + +### WPF designer integration +A custom control with properties that are implemented as dependency properties will receive appropriate WPF Designer for Visual Studio support. One example is the ability to edit direct and attached dependency properties with the **Properties** window. For more information, see [Control Authoring Overview](../controls/control-authoring-overview.md). + +## Dependency property value precedence +When you get the value of a dependency property, you are potentially obtaining a value that was set on that property through any one of the other property-based inputs that participate in the WPF property system. Dependency property value precedence exists so that a variety of scenarios for how properties obtain their values can interact in a predictable way. + +Consider the following example. The example includes a style that applies to all buttons and their properties, but then also specifies one button with a locally set value. + +> [!NOTE] +> The SDK documentation uses the terms "local value" or "locally set value" occasionally when discussing dependency properties. A locally set value is a property value that is set directly on an object instance in code, or as an attribute on an element in XAML. + +In principle, for the first button, the property is set twice, but only one value applies: the value with the highest precedence. A locally set value has the highest precedence (except for a running animation, but no animation applies in this example) and thus the locally set value is used instead of the style setter value for the background on the first button. The second button has no local value (and no other value with higher precedence than a style setter) and thus the background in that button comes from the style setter. + +[!code-xaml[PropertiesOvwSupport#MiniPrecedence](~/samples/snippets/csharp/VS_Snippets_Wpf/PropertiesOvwSupport/CSharp/page3.xaml#miniprecedence)] + +### Why does dependency property precedence exist? +Typically, you would not want styles to always apply and to obscure even a locally set value of an individual element (otherwise, it would be difficult to use either styles or elements in general). Therefore, the values that come from styles operate at a lower precedent than a locally set value. For a more thorough listing of dependency properties and where a dependency property effective value might come from, see [Dependency Property Value Precedence](dependency-property-value-precedence.md). + +> [!NOTE] +> There are a number of properties defined on WPF elements that are not dependency properties. By and large, properties were implemented as dependency properties only when there were needs to support at least one of the scenarios enabled by the property system: data binding, styling, animation, default value support, inheritance, attached properties, or invalidation. + +## Learning more about dependency properties + +- An attached property is a type of property that supports a specialized syntax in XAML. An attached property often does not have a 1:1 correspondence with a common language runtime (CLR) property, and is not necessarily a dependency property. The typical purpose of an attached property is to allow child elements to report property values to a parent element, even if the parent element and child element do not both possess that property as part of the class members listings. One primary scenario is to enable child elements to inform the parent how they should be presented in [!INCLUDE[TLA2#tla_ui](../../../includes/tla2sharptla-ui-md.md)]; for an example, see or . For details, see [Attached Properties Overview](attached-properties-overview.md). + +- Component developers or application developers may wish to create their own dependency property, in order to enable capabilities such as data binding or styles support, or for invalidation and value coercion support. For details, see [Custom Dependency Properties](custom-dependency-properties.md). + +- Consider dependency properties to be public properties, accessible or at least discoverable by any caller that has access to an instance. For more information, see [Dependency Property Security](dependency-property-security.md). + +## See also + +- [Custom Dependency Properties](custom-dependency-properties.md) +- [Read-Only Dependency Properties](read-only-dependency-properties.md) +- [XAML Overview (WPF)](/dotnet/desktop-wpf/fundamentals/xaml) +- [WPF Architecture](wpf-architecture.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/dependency-property-callbacks-and-validation.md b/dotnet-desktop-guide/framework/wpf/advanced/dependency-property-callbacks-and-validation.md new file mode 100644 index 0000000000..a904e0f65b --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/dependency-property-callbacks-and-validation.md @@ -0,0 +1,79 @@ +--- +title: "Dependency Property Callbacks and Validation" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "dependency properties [WPF], validation" + - "coerce value callbacks [WPF]" + - "callbacks [WPF], validation" + - "dependency properties [WPF], callbacks" + - "validation of dependency properties [WPF]" +ms.assetid: 48db5fb2-da7f-49a6-8e81-3540e7b25825 +--- +# Dependency Property Callbacks and Validation +This topic describes how to create dependency properties using alternative custom implementations for property-related features such as validation determination, callbacks that are invoked whenever the property's effective value is changed, and overriding possible outside influences on value determination. This topic also discusses scenarios where expanding on the default property system behaviors by using these techniques is appropriate. + + +## Prerequisites + This topic assumes that you understand the basic scenarios of implementing a dependency property, and how metadata is applied to a custom dependency property. See [Custom Dependency Properties](custom-dependency-properties.md) and [Dependency Property Metadata](dependency-property-metadata.md) for context. + + +## Validation Callbacks + Validation callbacks can be assigned to a dependency property when you first register it. The validation callback is not part of property metadata; it is a direct input of the method. Therefore, once a validation callback is created for a dependency property, it cannot be overridden by a new implementation. + + [!code-csharp[DPCallbackOverride#CurrentDefinitionWithWrapper](~/samples/snippets/csharp/VS_Snippets_Wpf/DPCallbackOverride/CSharp/SDKSampleLibrary/class1.cs#currentdefinitionwithwrapper)] + [!code-vb[DPCallbackOverride#CurrentDefinitionWithWrapper](~/samples/snippets/visualbasic/VS_Snippets_Wpf/DPCallbackOverride/visualbasic/sdksamplelibrary/class1.vb#currentdefinitionwithwrapper)] + + The callbacks are implemented such that they are provided an object value. They return `true` if the provided value is valid for the property; otherwise, they return `false`. It is assumed that the property is of the correct type per the type registered with the property system, so checking type within the callbacks is not ordinarily done. The callbacks are used by the property system in a variety of different operations. This includes the initial type initialization by default value, programmatic change by invoking , or attempts to override metadata with new default value provided. If the validation callback is invoked by any of these operations, and returns `false`, then an exception will be raised. Application writers must be prepared to handle these exceptions. A common use of validation callbacks is validating enumeration values, or constraining values of integers or doubles when the property sets measurements that must be zero or greater. + + Validation callbacks specifically are intended to be class validators, not instance validators. The parameters of the callback do not communicate a specific on which the properties to validate are set. Therefore the validation callbacks are not useful for enforcing the possible "dependencies" that might influence a property value, where the instance-specific value of a property is dependent on factors such as instance-specific values of other properties, or run-time state. + + The following is example code for a very simple validation callback scenario: validating that a property that is typed as the primitive is not or . + + [!code-csharp[DPCallbackOverride#ValidateValueCallback](~/samples/snippets/csharp/VS_Snippets_Wpf/DPCallbackOverride/CSharp/SDKSampleLibrary/class1.cs#validatevaluecallback)] + [!code-vb[DPCallbackOverride#ValidateValueCallback](~/samples/snippets/visualbasic/VS_Snippets_Wpf/DPCallbackOverride/visualbasic/sdksamplelibrary/class1.vb#validatevaluecallback)] + + +## Coerce Value Callbacks and Property Changed Events + Coerce value callbacks do pass the specific instance for properties, as do implementations that are invoked by the property system whenever the value of a dependency property changes. Using these two callbacks in combination, you can create a series of properties on elements where changes in one property will force a coercion or reevaluation of another property. + + A typical scenario for using a linkage of dependency properties is when you have a user interface driven property where the element holds one property each for the minimum and maximum value, and a third property for the actual or current value. Here, if the maximum was adjusted in such a way that the current value exceeded the new maximum, you would want to coerce the current value to be no greater than the new maximum, and a similar relationship for minimum to current. + + The following is very brief example code for just one of the three dependency properties that illustrate this relationship. The example shows how the `CurrentReading` property of a Min/Max/Current set of related *Reading properties is registered. It uses the validation as shown in the previous section. + + [!code-csharp[DPCallbackOverride#CurrentDefinitionWithWrapper](~/samples/snippets/csharp/VS_Snippets_Wpf/DPCallbackOverride/CSharp/SDKSampleLibrary/class1.cs#currentdefinitionwithwrapper)] + [!code-vb[DPCallbackOverride#CurrentDefinitionWithWrapper](~/samples/snippets/visualbasic/VS_Snippets_Wpf/DPCallbackOverride/visualbasic/sdksamplelibrary/class1.vb#currentdefinitionwithwrapper)] + + The property changed callback for Current is used to forward the change to other dependent properties, by explicitly invoking the coerce value callbacks that are registered for those other properties: + + [!code-csharp[DPCallbackOverride#OnPCCurrent](~/samples/snippets/csharp/VS_Snippets_Wpf/DPCallbackOverride/CSharp/SDKSampleLibrary/class1.cs#onpccurrent)] + [!code-vb[DPCallbackOverride#OnPCCurrent](~/samples/snippets/visualbasic/VS_Snippets_Wpf/DPCallbackOverride/visualbasic/sdksamplelibrary/class1.vb#onpccurrent)] + + The coerce value callback checks the values of properties that the current property is potentially dependent upon, and coerces the current value if necessary: + + [!code-csharp[DPCallbackOverride#CoerceCurrent](~/samples/snippets/csharp/VS_Snippets_Wpf/DPCallbackOverride/CSharp/SDKSampleLibrary/class1.cs#coercecurrent)] + [!code-vb[DPCallbackOverride#CoerceCurrent](~/samples/snippets/visualbasic/VS_Snippets_Wpf/DPCallbackOverride/visualbasic/sdksamplelibrary/class1.vb#coercecurrent)] + +> [!NOTE] +> Default values of properties are not coerced. A property value equal to the default value might occur if a property value still has its initial default, or through clearing other values with . + + The coerce value and property changed callbacks are part of property metadata. Therefore, you can change the callbacks for a particular dependency property as it exists on a type that you derive from the type that owns the dependency property, by overriding the metadata for that property on your type. + + +## Advanced Coercion and Callback Scenarios + +### Constraints and Desired Values + The callbacks will be used by the property system to coerce a value in accordance to the logic you declare, but a coerced value of a locally set property will still retain a "desired value" internally. If the constraints are based on other property values that may change dynamically during the application lifetime, the coercion constraints are changed dynamically also, and the constrained property can change its value to get as close to the desired value as possible given the new constraints. The value will become the desired value if all constraints are lifted. You can potentially introduce some fairly complicated dependency scenarios if you have multiple properties that are dependent on one another in a circular manner. For instance, in the Min/Max/Current scenario, you could choose to have Minimum and Maximum be user settable. If so, you might need to coerce that Maximum is always greater than Minimum and vice versa. But if that coercion is active, and Maximum coerces to Minimum, it leaves Current in an unsettable state, because it is dependent on both and is constrained to the range between the values, which is zero. Then, if Maximum or Minimum are adjusted, Current will seem to "follow" one of the values, because the desired value of Current is still stored and is attempting to reach the desired value as the constraints are loosened. + + There is nothing technically wrong with complex dependencies, but they can be a slight performance detriment if they require large numbers of reevaluations, and can also be confusing to users if they affect the UI directly. Be careful with property changed and coerce value callbacks and make sure that the coercion being attempted can be treated as unambiguously as possible, and does not "overconstrain". + +### Using CoerceValue to Cancel Value Changes + The property system will treat any that returns the value as a special case. This special case means that the property change that resulted in the being called should be rejected by the property system, and that the property system should instead report whatever previous value the property had. This mechanism can be useful to check that changes to a property that were initiated asynchronously are still valid for the current object state, and suppress the changes if not. Another possible scenario is that you can selectively suppress a value depending on which component of property value determination is responsible for the value being reported. To do this, you can use the passed in the callback and the property identifier as input for , and then process the . + +## See also + +- [Dependency Properties Overview](dependency-properties-overview.md) +- [Dependency Property Metadata](dependency-property-metadata.md) +- [Custom Dependency Properties](custom-dependency-properties.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/dependency-property-metadata.md b/dotnet-desktop-guide/framework/wpf/advanced/dependency-property-metadata.md new file mode 100644 index 0000000000..82bbdcf636 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/dependency-property-metadata.md @@ -0,0 +1,93 @@ +--- +title: "Dependency Property Metadata" +ms.date: "03/30/2017" +helpviewer_keywords: + - "APIs [WPF], metadata" + - "dependency properties [WPF], metadata" + - "metadata [WPF], for dependency properties" + - "overriding metadata [WPF]" +ms.assetid: d01ed009-b722-41bf-b82f-fe1a8cdc50dd +--- +# Dependency Property Metadata +The [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] property system includes a metadata reporting system that goes beyond what can be reported about a property through reflection or general common language runtime (CLR) characteristics. Metadata for a dependency property can also be assigned uniquely by the class that defines a dependency property, can be changed when the dependency property is added to a different class, and can be specifically overridden by all derived classes that inherit the dependency property from the defining base class. + + +## Prerequisites + This topic assumes that you understand dependency properties from the perspective of a consumer of existing dependency properties on [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] classes, and have read the [Dependency Properties Overview](dependency-properties-overview.md). In order to follow the examples in this topic, you should also understand [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] and know how to write [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] applications. + + +## How Dependency Property Metadata is Used + Dependency property metadata exists as an object that can be queried to examine the characteristics of a dependency property. This metadata is also accessed frequently by the property system as it processes any given dependency property. The metadata object for a dependency property can contain the following types of information: + +- Default value for the dependency property, if no other value can be determined for the dependency property by local value, style, inheritance, etc. For a thorough discussion of how default values participate in the precedence used by the property system when assigning values for dependency properties, see [Dependency Property Value Precedence](dependency-property-value-precedence.md). + +- References to callback implementations that affect coercion or change-notification behaviors on a per-owner-type basis. Note that these callbacks are often defined with a nonpublic access level, so obtaining the actual references from metadata is generally not possible unless the references are within your permitted access scope. For more information on dependency property callbacks, see [Dependency Property Callbacks and Validation](dependency-property-callbacks-and-validation.md). + +- If the dependency property in question is considered to be a WPF framework-level property, the metadata might contain WPF framework-level dependency property characteristics, which report information and state for services such as the WPF framework-level layout engine and property inheritance logic. For more information on this aspect of dependency property metadata, see [Framework Property Metadata](framework-property-metadata.md). + + +## Metadata APIs + The type that reports most of the metadata information used by the property system is the class. Metadata instances are optionally specified when dependency properties are registered with the property system, and can be specified again for additional types that either add themselves as owners or override metadata they inherit from the base class dependency property definition. (For cases where a property registration does not specify metadata, a default is created with default values for that class.)The registered metadata is returned as when you call the various overloads that get metadata from a dependency property on a instance. + + The class is then derived from to provide more specific metadata for architectural divisions such as the WPF framework-level classes. adds animation reporting, and provides the WPF framework-level properties mentioned in the previous section. When dependency properties are registered, they can be registered with these derived classes. When the metadata is examined, the base type can potentially be cast to the derived classes so that you can examine the more specific properties. + +> [!NOTE] +> The property characteristics that can be specified in are sometimes referred to in this documentation as "flags". When you create new metadata instances for use in dependency property registrations or metadata overrides, you specify these values using the flagwise enumeration and then you supply possibly concatenated values of the enumeration to the constructor. However, once constructed, these option characteristics are exposed within a as a series of Boolean properties rather than the constructing enumeration value. The Boolean properties enable you to check each conditional, rather than requiring you to apply a mask to a flagwise enumeration value to get the information you are interested in. The constructor uses the concatenated in order to keep the length of the constructor signature reasonable, whereas the actual constructed metadata exposes the discrete properties to make querying the metadata more intuitive. + + +## When to Override Metadata, When to Derive a Class + The [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] property system has established capabilities for changing some characteristics of dependency properties without requiring them to be entirely re-implemented. This is accomplished by constructing a different instance of property metadata for the dependency property as it exists on a particular type. Note that most existing dependency properties are not virtual properties, so strictly speaking "re-implementing" them on inherited classes could only be accomplished by shadowing the existing member. + + If the scenario you are trying to enable for a dependency property on a type cannot be accomplished by modifying characteristics of existing dependency properties, it might then be necessary to create a derived class, and then to declare a custom dependency property on your derived class. A custom dependency property behaves identically to dependency properties defined by the [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] APIs. For more details about custom dependency properties, see [Custom Dependency Properties](custom-dependency-properties.md). + + One notable characteristic of a dependency property that you cannot override is its value type. If you are inheriting a dependency property that has the approximate behavior you require, but you require a different type for it, you will have to implement a custom dependency property and perhaps link the properties through type conversion or other implementation on your custom class. Also, you cannot replace an existing , because this callback exists in the registration field itself and not within its metadata. + + +## Scenarios for Changing Existing Metadata + If you are working with metadata of an existing dependency property, one common scenario for changing dependency property metadata is to change the default value. Changing or adding property system callbacks is a more advanced scenario. You might want to do this if your implementation of a derived class has different interrelationships between dependency properties. One of the conditionals of having a programming model that supports both code and declarative usage is that properties must enable being set in any order. Thus any dependent properties need to be set just-in-time without context and cannot rely on knowing a setting order such as might be found in a constructor. For more information on this aspect of the property system, see [Dependency Property Callbacks and Validation](dependency-property-callbacks-and-validation.md). Note that validation callbacks are not part of the metadata; they are part of the dependency property identifier. Therefore, validation callbacks cannot be changed by overriding the metadata. + + In some cases you might also want to alter the WPF framework-level property metadata options on existing dependency properties. These options communicate certain known conditionals about WPF framework-level properties to other WPF framework-level processes such as the layout system. Setting the options is generally done only when registering a new dependency property, but it is also possible to change the WPF framework-level property metadata as part of a or call. For the specific values to use and more information, see [Framework Property Metadata](framework-property-metadata.md). For more information that is pertinent to how these options should be set for a newly registered dependency property, see [Custom Dependency Properties](custom-dependency-properties.md). + + +### Overriding Metadata + The purpose of overriding metadata is primarily so that you have the opportunity to change the various metadata-derived behaviors that are applied to the dependency property as it exists on your type. The reasons for this are explained in more detail in the [Metadata](#dp_metadata_contents) section. For more information including some code examples, see [Override Metadata for a Dependency Property](how-to-override-metadata-for-a-dependency-property.md). + + Property metadata can be supplied for a dependency property during the registration call (). However, in many cases, you might want to provide type-specific metadata for your class when it inherits that dependency property. You can do this by calling the method. For an example from the [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] APIs, the class is the type that first registers the dependency property. But the class overrides metadata for the dependency property to provide its own initial default value, changing it from `false` to `true`, and otherwise re-uses the original implementation. + + When you override metadata, the different metadata characteristics are either merged or replaced. + +- is merged. If you add a new , that callback is stored in the metadata. If you do not specify a in the override, the value of is promoted as a reference from the nearest ancestor that specified it in metadata. + +- The actual property system behavior for is that implementations for all metadata owners in the hierarchy are retained and added to a table, with order of execution by the property system being that the most derived class's callbacks are invoked first. + +- is replaced. If you do not specify a in the override, the value of comes from the nearest ancestor that specified it in metadata. + +- implementations are replaced. If you add a new , that callback is stored in the metadata. If you do not specify a in the override, the value of is promoted as a reference from the nearest ancestor that specified it in metadata. + +- The property system behavior is that only the in the immediate metadata is invoked. No references to other implementations in the hierarchy are retained. + + This behavior is implemented by , and can be overridden on derived metadata classes. + +#### Overriding Attached Property Metadata + In [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)], attached properties are implemented as dependency properties. This means that they also have property metadata, which individual classes can override. The scoping considerations for an attached property in [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] are generally that any can have an attached property set on them. Therefore, any derived class can override the metadata for any attached property, as it might be set on an instance of the class. You can override default values, callbacks, or WPF framework-level characteristic-reporting properties. If the attached property is set on an instance of your class, those override property metadata characteristics apply. For instance, you can override the default value, such that your override value is reported as the value of the attached property on instances of your class, whenever the property is not otherwise set. + +> [!NOTE] +> The property is not relevant for attached properties. + + +### Adding a Class as an Owner of an Existing Dependency Property + A class can add itself as an owner of a dependency property that has already been registered, by using the method. This enables the class to use a dependency property that was originally registered for a different type. The adding class is typically not a derived class of the type that first registered that dependency property as owner. Effectively, this allows your class and its derived classes to "inherit" a dependency property implementation without the original owner class and the adding class being in the same true class hierarchy. In addition, the adding class (and all derived classes as well) can then provide type-specific metadata for the original dependency property. + + As well as adding itself as owner through the property system utility methods, the adding class should declare additional public members on itself in order to make the dependency property] a full participant in the property system with exposure to both code and markup. A class that adds an existing dependency property has the same responsibilities as far as exposing the object model for that dependency property as does a class that defines a new custom dependency property. The first such member to expose is a dependency property identifier field. This field should be a `public static readonly` field of type , which is assigned to the return value of the call. The second member to define is the common language runtime (CLR) "wrapper" property. The wrapper makes it much more convenient to manipulate your dependency property in code (you avoid calls to each time, and can make that call only once in the wrapper itself). The wrapper is implemented identically to how it would be implemented if you were registering a custom dependency property. For more information about implementing a dependency property, see [Custom Dependency Properties](custom-dependency-properties.md) and [Add an Owner Type for a Dependency Property](how-to-add-an-owner-type-for-a-dependency-property.md). + +#### AddOwner and Attached Properties + You can call for a dependency property that is defined as an attached property by the owner class. Generally the reason for doing this is to expose the previously attached property as a non-attached dependency property. You then will expose the return value as a `public static readonly` field for use as the dependency property identifier, and will define appropriate "wrapper" properties so that the property appears in the members table and supports a non-attached property usage in your class. + +## See also + +- +- +- +- +- [Dependency Properties Overview](dependency-properties-overview.md) +- [Framework Property Metadata](framework-property-metadata.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/dependency-property-security.md b/dotnet-desktop-guide/framework/wpf/advanced/dependency-property-security.md new file mode 100644 index 0000000000..2194c6768a --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/dependency-property-security.md @@ -0,0 +1,37 @@ +--- +title: "Dependency Property Security" +ms.date: "03/30/2017" +helpviewer_keywords: + - "wrappers [WPF], access" + - "wrappers [WPF], security" + - "dependency properties [WPF], security" + - "security [WPF], wrappers" + - "validation [WPF], dependency properties" + - "dependency properties [WPF], access" + - "security [WPF], dependency properties" +ms.assetid: d10150ec-90c5-4571-8d35-84bafa2429a4 +--- +# Dependency Property Security +Dependency properties should generally be considered to be public properties. The nature of the [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] property system prevents the ability to make security guarantees about a dependency property value. + + +## Access and Security of Wrappers and Dependency Properties + Typically, dependency properties are implemented along with "wrapper" common language runtime (CLR) properties that simplify getting or setting the property from an instance. But the wrappers are really just convenience methods that implement the underlying and static calls that are used when interacting with dependency properties. Thinking of it in another way, the properties are exposed as common language runtime (CLR) properties that happen to be backed by a dependency property rather than by a private field. Security mechanisms applied to the wrappers do not parallel the property system behavior and access of the underlying dependency property. Placing a security demand on the wrapper will only prevent the usage of the convenience method but will not prevent calls to or . Similarly, placing protected or private access level on the wrappers does not provide any effective security. + + If you are writing your own dependency properties, you should declare the wrappers and the identifier field as public members, so that callers do not get misleading information about the true access level of that property (because of its store being implemented as a dependency property). + + For a custom dependency property, you can register your property as a read-only dependency property, and this does provide an effective means of preventing a property being set by anyone that does not hold a reference to the for that property. For more information, see [Read-Only Dependency Properties](read-only-dependency-properties.md). + +> [!NOTE] +> Declaring a identifier field private is not forbidden, and it can conceivably be used to help reduce the immediately exposed namespace of a custom class, but such a property should not be considered "private" in the same sense as the common language runtime (CLR) language definitions define that access level, for reasons described in the next section. + + +## Property System Exposure of Dependency Properties + It is not generally useful, and it is potentially misleading, to declare a as any access level other than public. That access level setting only prevents someone from being able to get a reference to the instance from the declaring class. But there are several aspects of the property system that will return a as the means of identifying a particular property as it exists on an instance of a class or a derived class instance, and this identifier is still usable in a call even if the original static identifier is declared as nonpublic. Also, virtual methods receive information of any existing dependency property that changed value. In addition, the method returns identifiers for any property on instances with a locally set value. + +### Validation and Security + Applying a demand to a and expecting the validation failure on a demand failure to prevent a property from being set is not an adequate security mechanism. Set-value invalidation enforced through could also be suppressed by malicious callers, if those callers are operating within the application domain. + +## See also + +- [Custom Dependency Properties](custom-dependency-properties.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/dependency-property-value-precedence.md b/dotnet-desktop-guide/framework/wpf/advanced/dependency-property-value-precedence.md new file mode 100644 index 0000000000..99090d6490 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/dependency-property-value-precedence.md @@ -0,0 +1,128 @@ +--- +title: "Dependency Property Value Precedence" +ms.date: "03/30/2017" +helpviewer_keywords: + - "dependency properties [WPF], classes as owners" + - "dependency properties [WPF], metadata" + - "classes [WPF], owners of dependency properties" + - "metadata [WPF], dependency properties" +ms.assetid: 1fbada8e-4867-4ed1-8d97-62c07dad7ebc +--- +# Dependency Property Value Precedence + This topic explains how the workings of the [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] property system can affect the value of a dependency property, and describes the precedence by which aspects of the property system apply to the effective value of a property. + + +## Prerequisites + This topic assumes that you understand dependency properties from the perspective of a consumer of existing dependency properties on [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] classes, and have read [Dependency Properties Overview](dependency-properties-overview.md). To follow the examples in this topic, you should also understand [!INCLUDE[TLA#tla_xaml](../../../includes/tlasharptla-xaml-md.md)] and know how to write [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] applications. + + +## The WPF Property System + The [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] property system offers a powerful way to have the value of dependency properties be determined by a variety of factors, enabling features such as real-time property validation, late binding, and notifying related properties of changes to values for other properties. The exact order and logic that is used to determine dependency property values is reasonably complex. Knowing this order will help you avoid unnecessary property setting, and might also clear up confusion over exactly why some attempt to influence or anticipate a dependency property value did not end up resulting in the value you expected. + + +## Dependency Properties Might Be "Set" in Multiple Places + The following is example [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] where the same property () has three different "set" operations that might influence the value. + + [!code-xaml[PropertiesOvwSupport#DPPrecedence](~/samples/snippets/csharp/VS_Snippets_Wpf/PropertiesOvwSupport/CSharp/page4.xaml#dpprecedence)] + + Here, which color do you expect will apply—red, green, or blue? + + With the exception of animated values and coercion, local property sets are set at the highest precedence. If you set a value locally you can expect that the value will be honored, even above any styles or control templates. Here in the example, is set to Red locally. Therefore, the style defined in this scope, even though it is an implicit style that would otherwise apply to all elements of that type in that scope, is not the highest precedence for giving the property its value. If you removed the local value of Red from that Button instance, then the style would have precedence and the button would obtain the Background value from the style. Within the style, triggers take precedence, so the button will be blue if the mouse is over it, and green otherwise. + + +## Dependency Property Setting Precedence List + The following is the definitive order that the property system uses when assigning the run-time values of dependency properties. Highest precedence is listed first. This list expands on some of the generalizations made in the [Dependency Properties Overview](dependency-properties-overview.md). + +1. **Property system coercion.** For details on coercion, see [Coercion, Animation, and Base Value](#animations) later in this topic. + +2. **Active animations, or animations with a Hold behavior.** In order to have any practical effect, an animation of a property must be able to have precedence over the base (unanimated) value, even if that value was set locally. For details, see [Coercion, Animation, and Base Value](#animations) later in this topic. + +3. **Local value.** A local value might be set through the convenience of the "wrapper" property, which also equates to setting as an attribute or property element in [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)], or by a call to the API using a property of a specific instance. If you set a local value by using a binding or a resource, these each act in the precedence as if a direct value was set. + +4. **TemplatedParent template properties.** An element has a if it was created as part of a template (a or ). For details on when this applies, see [TemplatedParent](#templatedparent) later in this topic. Within the template, the following precedence applies: + + 1. Triggers from the template. + + 2. Property sets (typically through [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] attributes) in the template. + +5. **Implicit style.** Applies only to the `Style` property. The `Style` property is filled by any style resource with a key that matches the type of that element. That style resource must exist either in the page or the application; lookup for an implicit style resource does not proceed into the themes. + +6. **Style triggers.** The triggers within styles from page or application (these styles might be either explicit or implicit styles, but not from the default styles, which have lower precedence). + +7. **Template triggers.** Any trigger from a template within a style, or a directly applied template. + +8. **Style setters.** Values from a within styles from page or application. + +9. **Default (theme) style.** For details on when this applies, and how theme styles relate to the templates within theme styles, see [Default (Theme) Styles](#themestyles) later in this topic. Within a default style, the following order of precedence applies: + + 1. Active triggers in the theme style. + + 2. Setters in the theme style. + +10. **Inheritance.** A few dependency properties inherit their values from parent element to child elements, such that they need not be set specifically on each element throughout an application. For details see [Property Value Inheritance](property-value-inheritance.md). + +11. **Default value from dependency property metadata.** Any given dependency property may have a default value as established by the property system registration of that particular property. Also, derived classes that inherit a dependency property have the option to override that metadata (including the default value) on a per-type basis. See [Dependency Property Metadata](dependency-property-metadata.md) for more information. Because inheritance is checked before default value, for an inherited property, a parent element default value takes precedence over a child element. Consequently, if an inheritable property is not set anywhere, the default value as specified on the root or parent is used instead of the child element default value. + + +## TemplatedParent + TemplatedParent as a precedence item does not apply to any property of an element that you declare directly in standard application markup. The TemplatedParent concept exists only for child items within a visual tree that come into existence through the application of the template. When the property system searches the template for a value, it is searching the template that created that element. The property values from the template generally act as if they were set as a local value on the child element, but this lesser precedence versus the local value exists because the templates are potentially shared. For details, see . + + +## The Style Property + The order of lookup described earlier applies to all possible dependency properties except one: the property. The property is unique in that it cannot itself be styled, so the precedence items 5 through 8 do not apply. Also, either animating or coercing is not recommended (and animating would require a custom animation class). This leaves three ways that the property might be set: + +- **Explicit style.** The property is set directly. In most scenarios, the style is not defined inline, but instead is referenced as a resource, by explicit key. In this case the Style property itself acts as if it were a local value, precedence item 3. + +- **Implicit style.** The property is not set directly. However, the exists at some level in the resource lookup sequence (page, application) and is keyed using a resource key that matches the type the style is to be applied to. In this case, the property itself acts by a precedence identified in the sequence as item 5. This condition can be detected by using against the property and looking for in the results. + +- **Default style**, also known as **theme style.** The property is not set directly, and in fact will read as `null` up until run time. In this case, the style comes from the run-time theme evaluation that is part of the [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] presentation engine. + + For implicit styles not in themes, the type must match exactly - a `MyButton` `Button`-derived class will not implicitly use a style for `Button`. + + +## Default (Theme) Styles + Every control that ships with [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] has a default style. That default style potentially varies by theme, which is why this default style is sometimes referred to as a theme style. + + The most important information that is found within a default style for a control is its control template, which exists in the theme style as a setter for its property. If there were no template from default styles, a control without a custom template as part of a custom style would have no visual appearance at all. The template from the default style gives the visual appearance of each control a basic structure, and also defines the connections between properties defined in the visual tree of the template and the corresponding control class. Each control exposes a set of properties that can influence the visual appearance of the control without completely replacing the template. For example, consider the default visual appearance of a control, which is a component of a . + + A has certain customizable properties. The default template of a creates a basic structure / visual tree with several nested components to create a bevel look. If a property that is part of the template is intended to be exposed for customization by the class, then that property must be exposed by a [TemplateBinding](templatebinding-markup-extension.md), within the template. In the case of , various properties of these borders share a template binding to properties such as or . But certain other properties or visual arrangements are hard-coded into the control template or are bound to values that come directly from the theme, and cannot be changed short of replacing the entire template. Generally, if a property comes from a templated parent and is not exposed by a template binding, it cannot be adjusted by styles because there is no easy way to target it. But that property could still be influenced by property value inheritance in the applied template, or by default value. + + The theme styles use a type as the key in their definitions. However, when themes are applied to a given element instance, themes lookup for this type is performed by checking the property on a control. This is in contrast to using the literal Type, as implicit styles do. The value of would inherit to derived classes even if the implementer did not change it (the intended way of changing the property is not to override it at the property level, but to instead change its default value in property metadata). This indirection enables base classes to define the theme styles for derived elements that do not otherwise have a style (or more importantly, do not have a template within that style and would thus have no default visual appearance at all). Thus, you can derive `MyButton` from and will still get the default template. If you were the control author of `MyButton` and you wanted a different behavior, you could override the dependency property metadata for on `MyButton` to return a different key, and then define the relevant theme styles including template for `MyButton` that you must package with your `MyButton` control. For more details on themes, styles, and control authoring, see [Control Authoring Overview](../controls/control-authoring-overview.md). + + +## Dynamic Resource References and Binding + Dynamic resource references and binding operations respect the precedence of the location at which they are set. For example, a dynamic resource applied to a local value acts per precedence item 3, a binding for a property setter within a theme style applies at precedence item 9, and so on. Because dynamic resource references and binding must both be able to obtain values from the run time state of the application, this entails that the actual process of determining the property value precedence for any given property extends into the run time as well. + + Dynamic resource references are not strictly speaking part of the property system, but they do have a lookup order of their own which interacts with the sequence listed above. That precedence is documented more thoroughly in the [XAML Resources](/dotnet/desktop-wpf/fundamentals/xaml-resources-define). The basic summation of that precedence is: element to page root, application, theme, system. + + Dynamic resources and bindings have the precedence of where they were set, but the value is deferred. One consequence of this is that if you set a dynamic resource or binding to a local value, any change to the local value replaces the dynamic resource or binding entirely. Even if you call the method to clear the locally set value, the dynamic resource or binding will not be restored. In fact, if you call on a property that has a dynamic resource or binding in place (with no literal local value), they are cleared by the call too. + + +## SetCurrentValue + The method is another way to set a property, but it is not in the order of precedence. Instead, enables you to change the value of a property without overwriting the source of a previous value. You can use any time that you want to set a value without giving that value the precedence of a local value. For example, if a property is set by a trigger and then assigned another value via , the property system still respects the trigger and the property will change if the trigger’s action occurs. enables you to change the property’s value without giving it a source with a higher precedence. Likewise, you can use to change the value of a property without overwriting a binding. + + +## Coercion, Animations, and Base Value + Coercion and animation both act on a value that is termed as the "base value" throughout this SDK. The base value is thus whatever value is determined through evaluating upwards in the items until item 2 is reached. + + For an animation, the base value can have an effect on the animated value, if that animation does not specify both "From" and "To" for certain behaviors, or if the animation deliberately reverts to the base value when completed. To see this in practice, run the [From, To, and By Animation Target Values Sample](https://github.com/Microsoft/WPF-Samples/tree/master/Animation/TargetValues). Try setting the local values of the rectangle height in the example, such that the initial local value differs from any "From" in the animation. You will note that the animations start right away using the "From" values and replace the base value once started. The animation might specify to return to the value found before animation once it is completed by specifying the Stop . Afterwards, normal precedence is used for the base value determination. + + Multiple animations might be applied to a single property, with each of these animations possibly having been defined from different points in the value precedence. However, these animations will potentially composite their values, rather than just applying the animation from the higher precedence. This depends on exactly how the animations are defined, and the type of the value that is being animated. For more information about animating properties, see [Animation Overview](../graphics-multimedia/animation-overview.md). + + Coercion applies at the highest level of all. Even an already running animation is subject to value coercion. Certain existing dependency properties in [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] have built-in coercion. For a custom dependency property, you define the coercion behavior for a custom dependency property by writing a and passing the callback as part of metadata when you create the property. You can also override coercion behavior of existing properties by overriding the metadata on that property in a derived class. Coercion interacts with the base value in such a way that the constraints on coercion are applied as those constraints exist at the time, but the base value is still retained. Therefore, if constraints in coercion are later lifted, the coercion will return the closest value possible to that base value, and potentially the coercion influence on a property will cease as soon as all constraints are lifted. For more information about coercion behavior, see [Dependency Property Callbacks and Validation](dependency-property-callbacks-and-validation.md). + + +## Trigger Behaviors + Controls often define trigger behaviors as part of their default style in themes. Setting local properties on controls might prevent the triggers from being able to respond to user-driven events either visually or behaviorally. The most common use of a property trigger is for control or state properties such as . For example, by default when a is disabled (trigger for is `false`) then the value in the theme style is what causes the control to appear "grayed out". But if you have set a local value, that normal gray-out color will be overruled in precedence by your local property set, even in this property-triggered scenario. Be cautious of setting values for properties that have theme-level trigger behaviors and make sure you are not unduly interfering with the intended user experience for that control. + + +## ClearValue and Value Precedence + The method provides an expedient means to clear any locally applied value from a dependency property that is set on an element. However, calling is not a guarantee that the default as established in metadata during property registration is the new effective value. All of the other participants in value precedence are still active. Only the locally set value has been removed from the precedence sequence. For example, if you call on a property where that property is also set by a theme style, then the theme value is applied as the new value rather than the metadata-based default. If you want to take all property value participants out of the process and set the value to the registered metadata default, you can obtain that default value definitively by querying the dependency property metadata, and then you can use the default value to locally set the property with a call to . + +## See also + +- +- +- [Dependency Properties Overview](dependency-properties-overview.md) +- [Custom Dependency Properties](custom-dependency-properties.md) +- [Dependency Property Callbacks and Validation](dependency-property-callbacks-and-validation.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/digital-ink-how-to-topics.md b/dotnet-desktop-guide/framework/wpf/advanced/digital-ink-how-to-topics.md new file mode 100644 index 0000000000..b11e97bf55 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/digital-ink-how-to-topics.md @@ -0,0 +1,21 @@ +--- +title: "Digital Ink How-to Topics" +ms.date: "03/30/2017" +f1_keywords: + - "AutoGeneratedOrientationPage" +helpviewer_keywords: + - "ink [WPF], digital" + - "digital ink [WPF]" +ms.assetid: c29f8728-bfcb-4af7-9fbc-8169e180109f +--- +# Digital Ink How-to Topics +## In This Section + [Select Ink from a Custom Control](how-to-select-ink-from-a-custom-control.md) + [Add Custom Data to Ink Data](how-to-add-custom-data-to-ink-data.md) + [Erase Ink on a Custom Control](how-to-erase-ink-on-a-custom-control.md) + [Recognize Application Gestures](how-to-recognize-application-gestures.md) + [Drag and Drop Ink](how-to-drag-and-drop-ink.md) + [Data Bind to an InkCanvas](how-to-data-bind-to-an-inkcanvas.md) + [Analyze Ink with Analysis Hints](how-to-analyze-ink-with-analysis-hints.md) + [Rotate Ink](how-to-rotate-ink.md) + [Disable the RealTimeStylus for WPF Applications](disable-the-realtimestylus-for-wpf-applications.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/digital-ink-overviews.md b/dotnet-desktop-guide/framework/wpf/advanced/digital-ink-overviews.md new file mode 100644 index 0000000000..6e43d615e7 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/digital-ink-overviews.md @@ -0,0 +1,18 @@ +--- +title: "Digital Ink Overviews" +ms.date: "03/30/2017" +f1_keywords: + - "AutoGeneratedOrientationPage" +helpviewer_keywords: + - "ink [WPF], digital" + - "digital ink [WPF]" +ms.assetid: 5ddb23a6-7813-4058-b59d-29ff3341638c +--- +# Digital Ink Overviews +## In This Section + [Getting Started with Ink](getting-started-with-ink.md) + [Collecting Ink](collecting-ink.md) + [Handwriting Recognition](handwriting-recognition.md) + [Storing Ink](storing-ink.md) + [The Ink Object Model: Windows Forms and COM versus WPF](the-ink-object-model-windows-forms-and-com-versus-wpf.md) + [Advanced Ink Handling](advanced-ink-handling.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/digital-ink.md b/dotnet-desktop-guide/framework/wpf/advanced/digital-ink.md new file mode 100644 index 0000000000..f014b2cec2 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/digital-ink.md @@ -0,0 +1,19 @@ +--- +title: "Digital Ink" +ms.date: "03/30/2017" +f1_keywords: + - "AutoGeneratedOrientationPage" +helpviewer_keywords: + - "ink [WPF], digital" + - "digital ink [WPF]" +ms.assetid: d0d6df69-daf9-4cf3-b7f9-ffee588037a3 +--- +# Digital Ink +This section discusses the use of digital ink in the [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)]. Traditionally found only in the Tablet PC SDK, digital ink is now available in the core Windows Presentation Foundation. This means you can now develop full-fledged Tablet PC applications by using the power of Windows Presentation Foundation. + +## In This Section + [Overviews](digital-ink-overviews.md) + [How-to Topics](digital-ink-how-to-topics.md) + +## Related Sections + [Windows Presentation Foundation](../index.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/disable-the-realtimestylus-for-wpf-applications.md b/dotnet-desktop-guide/framework/wpf/advanced/disable-the-realtimestylus-for-wpf-applications.md new file mode 100644 index 0000000000..7fbee82f50 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/disable-the-realtimestylus-for-wpf-applications.md @@ -0,0 +1,52 @@ +--- +title: Disable the RealTimeStylus +ms.date: "03/30/2017" +ms.assetid: e0525309-5ede-4782-837d-dbf6e5554859 +--- +# Disable the RealTimeStylus for WPF Applications + +Windows Presentation Foundation (WPF) has built in support for processing Windows 7 touch input. The support comes through the tablet platform’s real-time stylus input as , , and events. Windows 7 also provides multi-touch input as Win32 WM_TOUCH window messages. These two APIs are mutually exclusive on the same HWND. Enabling touch input via the tablet platform (the default for WPF applications) disables WM_TOUCH messages. As a result, to use WM_TOUCH to receive touch messages from a WPF window, you must disable the built-in stylus support in WPF. This is applicable in a scenario such as a WPF window hosting a component that uses WM_TOUCH. + + To disable WPF listening to stylus input, remove any tablet support added by the WPF window. + +## Example + The following sample code shows how to remove the default tablet platform support by using reflection. + +```csharp +public static void DisableWPFTabletSupport() +{ + // Get a collection of the tablet devices for this window. + TabletDeviceCollection devices = System.Windows.Input.Tablet.TabletDevices; + + if (devices.Count > 0) + { + // Get the Type of InputManager. + Type inputManagerType = typeof(System.Windows.Input.InputManager); + + // Call the StylusLogic method on the InputManager.Current instance. + object stylusLogic = inputManagerType.InvokeMember("StylusLogic", + BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic, + null, InputManager.Current, null); + + if (stylusLogic != null) + { + // Get the type of the stylusLogic returned from the call to StylusLogic. + Type stylusLogicType = stylusLogic.GetType(); + + // Loop until there are no more devices to remove. + while (devices.Count > 0) + { + // Remove the first tablet device in the devices collection. + stylusLogicType.InvokeMember("OnTabletRemoved", + BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic, + null, stylusLogic, new object[] { (uint)0 }); + } + } + + } +} +``` + +## See also + +- [Intercepting Input from the Stylus](intercepting-input-from-the-stylus.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/document-serialization-and-storage.md b/dotnet-desktop-guide/framework/wpf/advanced/document-serialization-and-storage.md new file mode 100644 index 0000000000..68c49a67ab --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/document-serialization-and-storage.md @@ -0,0 +1,85 @@ +--- +title: "Document Serialization and Storage" +ms.date: "03/30/2017" +helpviewer_keywords: + - "serialization of documents [WPF], , " + - "documents [WPF], storage" + - "documents [WPF], serialization" +ms.assetid: 4839cd87-e206-4571-803f-0200098ad37b +--- +# Document Serialization and Storage + +Microsoft .NET Framework provides a powerful environment for creating and displaying high quality documents. Enhanced features that support both fixed-documents and flow-documents, advanced viewing controls, combined with powerful 2D and 3D graphic capabilities take .NET Framework applications to a new level of quality and user experience. Being able to flexibly manage an in-memory representation of a document is a key feature of .NET Framework, and being able to efficiently save and load documents from a data store is a need of almost every application. The process of converting a document from an internal in-memory representation to an external data store is termed serialization. The reverse process of reading a data store and recreating the original in-memory instance is termed deserialization. + + + +## About Document Serialization + +Ideally the process of serializing and deserializing a document from and then back into memory is transparent to the application. The application calls a serializer "write" method to save the document, while a deserializer "read" method accesses the data store and recreates the original instance in memory. The specific format that the data is stored in is generally not a concern of the application as long as the serialize and deserialize process recreates the document back to its original form. + +Applications often provide multiple serialization options which allow the user to save documents to different medium or to a different format. For example, an application might offer "Save As" options to store a document to a disk file, database, or web service. Similarly, different serializers could store the document in different formats such as in HTML, RTF, XML, XPS, or alternately to a third-party format. To the application, serialization defines an interface that isolates the details of the storage medium within the implementation of each specific serializer. In addition to the benefits of encapsulating storage details, the .NET Framework APIs provide several other important features. + +### Features of .NET Framework 3.0 Document Serializers + +- Direct access to the high-level document objects (logical tree and visuals) enable efficient storage of paginated content, 2D/3D elements, images, media, hyperlinks, annotations, and other support content. + +- Synchronous and asynchronous operation. + +- Support for plug-in serializers with enhanced capabilities: + + - System-wide access for use by all .NET Framework applications. + + - Simple application plug-in discoverability. + + - Simple deployment, installation, and update for custom third-party plug-ins. + + - User interface support for custom run-time settings and options. + +### XPS Print Path + +The Microsoft .NET Framework XPS print path also provides an extensible mechanism for writing documents through print output. XPS serves as both a document file format and is the native print spool format for Windows Vista. XPS documents can be sent directly to XPS-compatible printers without the need for conversion to an intermediate format. See the [Printing Overview](printing-overview.md) for additional information on print path output options and capabilities. + + + +## Plug-in Serializers + +The APIs provide support for both plug-in serializers and linked serializers that are installed separately from the application, bind at run time, and are accessed by using the discovery mechanism. Plug-in serializers offer enhanced benefits for ease of deployment and system-wide use. Linked serializers can also be implemented for partial trust environments such as XAML browser applications (XBAPs) where plug-in serializers are not accessible. Linked serializers, which are based on a derived implementation of the class, are compiled and linked directly into the application. Both plug-in serializers and linked serializers operate through identical public methods and events which make it easy to use either or both types of serializers in the same application. + +Plug-in serializers aid application developers by providing extensibility to new storage designs and file formats without having to code directly for every potential format at build time. Plug-in serializers also benefit third-party developers by providing a standardized means to deploy, install, and update system accessible plug-ins for custom or proprietary file formats. + +### Using a Plug-in Serializer + +Plug-in serializers are simple to use. The class enumerates a object for each plug-in installed on the system. The property filters the installed plug-ins based on the current configuration and verifies that the serializer can be loaded and used by the application. The also provides other properties, such as and , which the application can use to prompt the user in selecting a serializer for an available output format. A default plug-in serializer for XPS is provided with .NET Framework and is always enumerated. After the user selects an output format, the method is used to create a for the specific format. The method can then be called to output the document stream to the data store. + +The following example illustrates an application that uses the method in a "PlugInFileFilter" property. PlugInFileFilter enumerates the installed plug-ins and builds a filter string with the available file options for a . + +[!code-csharp[DocumentSerialize#DocSerializeFileFilter](~/samples/snippets/csharp/VS_Snippets_Wpf/DocumentSerialize/CSharp/ThumbViewer.cs#docserializefilefilter)] + +After an output file name has been selected by the user, the following example illustrates use of the method to store a given document in a specified format. + +[!code-csharp[DocumentSerialize#DocSerializePlugIn](~/samples/snippets/csharp/VS_Snippets_Wpf/DocumentSerialize/CSharp/ThumbViewer.cs#docserializeplugin)] + + + +### Installing Plug-in Serializers + +The class supplies the upper-level application interface for plug-in serializer discovery and access. locates and provides the application a list of the serializers that are installed and accessible on the system. The specifics of the installed serializers are defined through registry settings. Plug-in serializers can be added to the registry by using the method; or if .NET Framework is not yet installed, the plug-in installation script can directly set the registry values itself. The method can be used to remove a previously installed plug-in, or the registry settings can be reset similarly by an uninstall script. + +### Creating a Plug-in Serializer + +Both plug-in serializers and linked serializers use the same exposed public methods and events, and similarly can be designed to operate either synchronously or asynchronously. There are three basic steps normally followed to create a plug-in serializer: + +1. Implement and debug the serializer first as a linked serializer. Initially creating the serializer compiled and linked directly in a test application provides full access to breakpoints and other debug services helpful for testing. + +2. After the serializer is fully tested, an interface is added to create a plug-in. The interface permits full access to all .NET Framework objects which includes the logical tree, objects, , and elements. Additionally provides the same synchronous and asynchronous methods and events used by linked serializers. Since large documents can take time to output, asynchronous operations are recommended to maintain responsive user interaction and offer a "Cancel" option if some problem occurs with the data store. + +3. After the plug-in serializer is created, an installation script is implemented for distributing and installing (and uninstalling) the plug-in (see above, "[Installing Plug-in Serializers](#InstallingPluginSerializers)"). + +## See also + +- +- +- +- [Documents in WPF](documents-in-wpf.md) +- [Printing Overview](printing-overview.md) +- [XML Paper Specification](https://www.ecma-international.org/activities/XML%20Paper%20Specification/XPS%20Standard%20WD%201.6.pdf) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/documents-in-wpf.md b/dotnet-desktop-guide/framework/wpf/advanced/documents-in-wpf.md new file mode 100644 index 0000000000..be1c586d71 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/documents-in-wpf.md @@ -0,0 +1,144 @@ +--- +title: "Documents" +ms.date: "03/30/2017" +helpviewer_keywords: + - "documents [WPF], packaging" + - "documents [WPF], text layout" + - "documents [WPF], XPS" + - "XPS documents [WPF], , " + - "documents [WPF], controls" + - "documents [WPF], types of" + - "documents [WPF], browser-viewable" +ms.assetid: 6e8db7bc-050a-4070-aa72-bb8c46e87ff8 +--- +# Documents in WPF +[!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] offers a wide range of document features that enable the creation of high-fidelity content that is designed to be more easily accessed and read than in previous generations of Windows. In addition to enhanced capabilities and quality, [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] also provides integrated services for document display, packaging, and security. This topic provides an introduction to [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] document types and document packaging. + + +## Types of Documents + [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] divides documents into two broad categories based on their intended use; these document categories are termed "fixed documents" and "flow documents." + + Fixed documents are intended for applications that require a precise "what you see is what you get" (WYSIWYG) presentation, independent of the display or printer hardware used. Typical uses for fixed documents include desktop publishing, word processing, and form layout, where adherence to the original page design is critical. As part of its layout, a fixed document maintains the precise positional placement of content elements independent of the display or print device in use. For example, a fixed document page viewed on 96 dpi display will appear exactly the same when it is output to a 600 dpi laser printer as when it is output to a 4800 dpi phototypesetter. The page layout remains the same in all cases, while the document quality maximizes to the capabilities of each device. + + By comparison, flow documents are designed to optimize viewing and readability and are best utilized when ease of reading is the primary document consumption scenario. Rather than being set to one predefined layout, flow documents dynamically adjust and reflow their content based on run-time variables such as window size, device resolution, and optional user preferences. A Web page is a simple example of a flow document where the page content is dynamically formatted to fit the current window. Flow documents optimize the viewing and reading experience for the user, based on the runtime environment. For example, the same flow document will dynamically reformat for optimal readability on either high-resolution 19-inch display or a small 2x3-inch PDA screen. In addition, flow documents have a number of built in features including search, viewing modes that optimize readability, and the ability to change the size and appearance of fonts. See [Flow Document Overview](flow-document-overview.md) for illustrations, examples, and in-depth information on flow documents. + + +## Document Controls and Text Layout + The .NET Framework provides a set of pre-built controls that simplify using fixed documents, flow documents, and general text within your application. The display of fixed document content is supported using the control. Display of flow document content is supported by three different controls: , , and which map to different user scenarios (see sections below). Other [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] controls provide simplified layout to support general text uses (see [Text in the User Interface](#text_in_the_user_interface), below). + +### Fixed Document Control - DocumentViewer + The control is designed to display content. The control provides an intuitive user interface that provides built-in support for common operations including print output, copy to clipboard, zoom, and text search features. The control provides access to pages of content through a familiar scrolling mechanism. Like all [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] controls, supports complete or partial restyling, which enables the control to be visually integrated into virtually any application or environment. + + is designed to display content in a read-only manner; editing or modification of content is not available and is not supported. + + +### Flow Document Controls + +> [!NOTE] +> For more detailed information on flow document features and how to create them, see [Flow Document Overview](flow-document-overview.md). + + Display of flow document content is supported by three controls: , , and . + +#### FlowDocumentReader + includes features that enable the user to dynamically choose between various viewing modes, including a single-page (page-at-a-time) viewing mode, a two-page-at-a-time (book reading format) viewing mode, and a continuous scrolling (bottomless) viewing mode. For more information about these viewing modes, see . If you do not need the ability to dynamically switch between different viewing modes, and provide lighter-weight flow content viewers that are fixed in a particular viewing mode. + +#### FlowDocumentPageViewer and FlowDocumentScrollViewer + shows content in page-at-a-time viewing mode, while shows content in continuous scrolling mode. Both and are fixed to a particular viewing mode. Compare to , which includes features that enable the user to dynamically choose between various viewing modes (as provided by the enumeration), at the cost of being more resource intensive than or . + + By default, a vertical scrollbar is always shown, and a horizontal scrollbar becomes visible if needed. The default [!INCLUDE[TLA2#tla_ui](../../../includes/tla2sharptla-ui-md.md)] for does not include a toolbar; however, the property can be used to enable a built-in toolbar. + + +### Text in the User Interface + Besides adding text to documents, text can obviously be used in application UI such as forms. [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] includes multiple controls for drawing text to the screen. Each control is targeted to a different scenario and has its own list of features and limitations. In general, the element should be used when limited text support is required, such as a brief sentence in a [!INCLUDE[TLA#tla_ui](../../../includes/tlasharptla-ui-md.md)]. can be used when minimal text support is required. For more information, see [TextBlock Overview](../controls/textblock-overview.md). + + +## Document Packaging + The APIs provide an efficient means to organize application data, document content, and related resources in a single container that is simple to access, portable, and easy to distribute. A ZIP file is an example of a type capable of holding multiple objects as a single unit. The packaging APIs provide a default implementation designed using an Open Packaging Conventions standard with XML and ZIP file architecture. The [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] packaging APIs make it simple to create packages, and to store and access objects within them. An object stored in a is referred to as a ("part"). Packages can also include signed digital certificates that can be used to identify the originator of a part and to validate that the contents of a package have not been modified. Packages also include a feature that allows additional information to be added to a package or associated with specific parts without actually modifying the content of existing parts. Package services also support Microsoft Windows Rights Management (RM). + + The [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] Package architecture serves as the foundation for a number of key technologies: + +- XPS documents conforming to the XML Paper Specification (XPS). + +- Microsoft Office "12" open XML format documents (.docx). + +- Custom storage formats for your own application design. + + Based on the packaging APIs, an is specifically designed for storing [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] fixed content documents. An is a self-contained document that can be opened in a viewer, displayed in a control, routed to a print spool, or output directly to an XPS-compatible printer. + + The following sections provide additional information on the and APIs provided with [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)]. + + +### Package Components + The [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] packaging APIs allow application data and documents to be organized into a single portable unit. A ZIP file is one of the most common types of packages and is the default package type provided with [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)]. itself is an abstract class from which is implemented using an open standard XML and ZIP file architecture. The method uses to create and use ZIP files by default. A package can contain three basic types of items: + +||| +|-|-| +||Application content, data, documents, and resource files.| +||[X.509 Certificate] for identification, authentication and validation.| +||Added information related to the package or a specific part.| + + +#### PackageParts + A ("part") is an abstract class that refers to an object stored in a . In a ZIP file, the package parts correspond to the individual files stored within the ZIP file. provides the default implementation for serializable objects stored in a . Like a file system, parts contained in the package are stored in hierarchical directory or "folder-style" organization. Using the [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] packaging APIs, applications can write, store, and read multiple objects using a single ZIP file container. + + +#### PackageDigitalSignatures + For security, a ("digital signature") can be associated with parts within a package. A incorporates a [509] that provides two features: + +1. Identifies and authenticates the originator of the part. + +2. Validates that the part has not been modified. + + The digital signature does not preclude a part from being modified, but a validation check against the digital signature will fail if the part is altered in any way. The application can then take appropriate action—for example, block opening the part or notify the user that the part has been modified and is not secure. + + +#### PackageRelationships + A ("relationship") provides a mechanism for associating additional information with the package or a part within the package. A relationship is a package-level facility that can associate additional information with a part without modifying the actual part content. Inserting new data directly into the part content of is usually not practical in many cases: + +- The actual type of the part and its content schema is not known. + +- Even if known, the content schema might not provide a means for adding new information. + +- The part might be digitally signed or encrypted, precluding any modification. + + Package relationships provide a discoverable means for adding and associating additional information with individual parts or with the entire package. Package relationships are used for two primary functions: + +1. Defining dependency relationships from one part to another part. + +2. Defining information relationships that add notes or other data related to the part. + + A provides a quick, discoverable means to define dependencies and add other information associated with a part of the package or the package as a whole. + + +##### Dependency Relationships + Dependency relationships are used to describe dependencies that one part makes to other parts. For example, a package might contain an HTML part that includes one or more \ image tags. The image tags refer to images that are located either as other parts internal to the package or external to the package (such as accessible over the Internet). Creating a associated with HTML file makes discovering and accessing the dependent resources quick and easy. A browser or viewer application can directly access the part relationships and immediately begin assembling the dependent resources without knowing the schema or parsing the document. + + +##### Information Relationships + Similar to a note or annotation, a can also be used to store other types of information to be associated with a part without having to actually modify the part content itself. + + +## XPS Documents + XML Paper Specification (XPS) document is a package that contains one or more fixed-documents along with all the resources and information required for rendering. XPS is also the native Windows Vista print spool file format. An is stored in standard ZIP dataset, and can include a combination of XML and binary components, such as image and font files. [PackageRelationships](#PackageRelationships) are used to define the dependencies between the content and the resources required to fully render the document. The design provides a single, high-fidelity document solution that supports multiple uses: + +- Reading, writing, and storing fixed-document content and resources as a single, portable, and easy-to-distribute file. + +- Displaying documents with the XPS Viewer application. + +- Outputting documents in the native print spool output format of Windows Vista. + +- Routing documents directly to an XPS-compatible printer. + +## See also + +- +- +- +- +- +- +- +- [Text](optimizing-performance-text.md) +- [Flow Document Overview](flow-document-overview.md) +- [Printing Overview](printing-overview.md) +- [Document Serialization and Storage](document-serialization-and-storage.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/documents.md b/dotnet-desktop-guide/framework/wpf/advanced/documents.md new file mode 100644 index 0000000000..b9d534ec81 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/documents.md @@ -0,0 +1,26 @@ +--- +title: "Documents" +ms.date: "03/30/2017" +f1_keywords: + - "AutoGeneratedOrientationPage" +helpviewer_keywords: + - "documents [WPF], features for" +ms.assetid: 7bf37ccb-5d09-4eae-9661-929582aeb259 +--- +# Documents +[!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] provides a versatile set of components that enable developers to build applications with advanced document features and an improved reading experience. In addition to enhanced capabilities and quality, [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] also provides simplified management services for document packaging, security, and storage. + +## In This Section + [Documents in WPF](documents-in-wpf.md) + [Document Serialization and Storage](document-serialization-and-storage.md) + [Annotations](annotations.md) + [Flow Content](flow-content.md) + [Typography](typography.md) + [Printing and Print System Management](printing-and-print-system-management.md) + +## See also + +- +- +- +- [isXPS.exe (isXPS Conformance Tool)](https://docs.microsoft.com/previous-versions/dotnet/netframework-4.0/aa348104(v=vs.100)) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/drag-and-drop-how-to-topics.md b/dotnet-desktop-guide/framework/wpf/advanced/drag-and-drop-how-to-topics.md new file mode 100644 index 0000000000..c403531240 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/drag-and-drop-how-to-topics.md @@ -0,0 +1,23 @@ +--- +title: "Drag and Drop How-to Topics" +ms.date: "03/30/2017" +f1_keywords: + - "AutoGeneratedOrientationPage" +helpviewer_keywords: + - "drag-and-drop [WPF], how-to topics" +ms.assetid: 559c0804-c62a-4640-b6b9-cbd2aa9fb99c +--- +# Drag and Drop How-to Topics +The following examples demonstrate how to accomplish common tasks using the [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] drag-and-drop framework. + +## In This Section + [Open a File That is Dropped on a RichTextBox Control](how-to-open-a-file-that-is-dropped-on-a-richtextbox-control.md) + [Create a Data Object](how-to-create-a-data-object.md) + [Determine if a Data Format is Present in a Data Object](how-to-determine-if-a-data-format-is-present-in-a-data-object.md) + [List the Data Formats in a Data Object](how-to-list-the-data-formats-in-a-data-object.md) + [Retrieve Data in a Particular Data Format](how-to-retrieve-data-in-a-particular-data-format.md) + [Store Multiple Data Formats in a Data Object](how-to-store-multiple-data-formats-in-a-data-object.md) + +## See also + +- [Drag and Drop Overview](drag-and-drop-overview.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/drag-and-drop-overview.md b/dotnet-desktop-guide/framework/wpf/advanced/drag-and-drop-overview.md new file mode 100644 index 0000000000..858f927f8a --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/drag-and-drop-overview.md @@ -0,0 +1,218 @@ +--- +title: "Drag and Drop Overview" +description: Learn about drag-and-drop support in Windows Presentation Foundation applications, which lets users drag objects to a region in the user interface. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "drag-and-drop [WPF], implementing" + - "drag sources [WPF], drag-and-drop" + - "data transfer [WPF], drag-and-drop" + - "drag-and-drop [WPF], about" + - "drag-and-drop [WPF], events" + - "drop targets [WPF], drag-and-drop" +ms.assetid: 1a5b27b0-0ac5-4cdf-86c0-86ac0271fa64 +--- +# Drag and Drop Overview +This topic provides an overview of drag-and-drop support in [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] applications. Drag-and-drop commonly refers to a method of data transfer that involves using a mouse (or some other pointing device) to select one or more objects, dragging these objects over some desired drop target in the [!INCLUDE[TLA#tla_ui](../../../includes/tlasharptla-ui-md.md)], and dropping them. + + +## Drag-and-Drop Support in WPF + Drag-and-drop operations typically involve two parties: a drag source from which the dragged object originates and a drop target which receives the dropped object. The drag source and drop target may be UI elements in the same application or a different application. + + The type and number of objects that can be manipulated with drag-and-drop is completely arbitrary. For example, files, folders, and selections of content are some of the more common objects manipulated through drag-and-drop operations. + + The particular actions performed during a drag-and-drop operation are application specific, and often determined by context. For example, dragging a selection of files from one folder to another on the same storage device moves the files by default, whereas dragging files from a Universal Naming Convention (UNC) share to a local folder copies the files by default. + + The drag-and-drop facilities provided by [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] are designed to be highly flexible and customizable to support a wide variety of drag-and-drop scenarios. Drag-and-drop supports manipulating objects within a single application, or between different applications. Dragging-and-dropping between [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] applications and other Windows applications is also fully supported. + + In [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)], any or can participate in drag-and-drop. The events and methods required for drag-and-drop operations are defined in the class. The and classes contain aliases for the attached events so that the events appear in the class members list when a or is inherited as a base element. Event handlers that are attached to these events are attached to the underlying attached event and receive the same event data instance. For more information, see the event. + +> [!IMPORTANT] +> OLE drag-and-drop does not work while in the Internet zone. + + +## Data Transfer + Drag-and-drop is part of the more general area of data transfer. Data transfer includes drag-and-drop and copy-and-paste operations. A drag-and-drop operation is analogous to a copy-and-paste or cut-and-paste operation that is used to transfer data from one object or application to another by using the system clipboard. Both types of operations require: + +- A source object that provides the data. + +- A way to temporarily store the transferred data. + +- A target object that receives the data. + + In a copy-and-paste operation, the system clipboard is used to temporarily store the transferred data; in a drag-and-drop operation, a is used to store the data. Conceptually, a data object consists of one or more pairs of an that contains the actual data, and a corresponding data format identifier. + + The drag source initiates a drag-and-drop operation by calling the static method and passing the transferred data to it. The method will automatically wrap the data in a if necessary. For greater control over the data format, you can wrap the data in a before passing it to the method. The drop target is responsible for extracting the data from the . For more information about working with data objects, see [Data and Data Objects](data-and-data-objects.md). + + The source and target of a drag-and-drop operation are UI elements; however, the data that is actually being transferred typically does not have a visual representation. You can write code to provide a visual representation of the data that is dragged, such as occurs when dragging files in Windows Explorer. By default, feedback is provided to the user by changing the cursor to represent the effect that the drag-and-drop operation will have on the data, such as whether the data will be moved or copied. + +### Drag-and-Drop Effects + Drag-and-drop operations can have different effects on the transferred data. For example, you can copy the data or you can move the data. [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] defines a enumeration that you can use to specify the effect of a drag-and-drop operation. In the drag source, you can specify the effects that the source will allow in the method. In the drop target, you can specify the effect that the target intends in the property of the class. When the drop target specifies its intended effect in the event, that information is passed back to the drag source in the event. The drag source uses this information to inform the user what effect the drop target intends to have on the data. When the data is dropped, the drop target specifies its actual effect in the event. That information is passed back to the drag source as the return value of the method. If the drop target returns an effect that is not in the drag sources list of `allowedEffects`, the drag-and-drop operation is cancelled without any data transfer occurring. + + It is important to remember that in [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)], the values are only used to provide communication between the drag source and the drop target regarding the effects of the drag-and-drop operation. The actual effect of the drag-and-drop operation depends on you to write the appropriate code in your application. + + For example, the drop target might specify that the effect of dropping data on it is to move the data. However, to move the data, it must be both added to the target element and removed from the source element. The source element might indicate that it allows moving the data, but if you do not provide the code to remove the data from the source element, the end result will be that the data is copied, and not moved. + + +## Drag-and-Drop Events + Drag-and-drop operations support an event driven model. Both the drag source and the drop target use a standard set of events to handle drag-and-drop operations. The following tables summarize the standard drag-and-drop events. These are attached events on the class. For more information about attached events, see [Attached Events Overview](attached-events-overview.md). + +### Drag Source Events + +|Event|Summary| +|-----------|-------------| +||This event occurs continuously during a drag-and-drop operation, and enables the drop source to give feedback information to the user. This feedback is commonly given by changing the appearance of the mouse pointer to indicate the effects allowed by the drop target. This is a bubbling event.| +||This event occurs when there is a change in the keyboard or mouse button states during a drag-and-drop operation, and enables the drop source to cancel the drag-and-drop operation depending on the key/button states. This is a bubbling event.| +||Tunneling version of .| +||Tunneling version of .| + +### Drop Target Events + +|Event|Summary| +|-----------|-------------| +||This event occurs when an object is dragged into the drop target's boundary. This is a bubbling event.| +||This event occurs when an object is dragged out of the drop target's boundary. This is a bubbling event.| +||This event occurs continuously while an object is dragged (moved) within the drop target's boundary. This is a bubbling event.| +||This event occurs when an object is dropped on the drop target. This is a bubbling event.| +||Tunneling version of .| +||Tunneling version of .| +||Tunneling version of .| +||Tunneling version of .| + + To handle drag-and-drop events for instances of an object, add handlers for the events listed in the preceding tables. To handle drag-and-drop events at the class level, override the corresponding virtual On*Event and On\*PreviewEvent methods. For more information, see [Class Handling of Routed Events by Control Base Classes](marking-routed-events-as-handled-and-class-handling.md#Class_Handling_of_Routed_Events). + + +## Implementing Drag-and-Drop + A UI element can be a drag source, a drop target, or both. To implement basic drag-and-drop, you write code to initiate the drag-and-drop operation and to process the dropped data. You can enhance the drag-and-drop experience by handling optional drag-and-drop events. + + To implement basic drag-and-drop, you will complete the following tasks: + +- Identify the element that will be a drag source. A drag source can be a or a . + +- Create an event handler on the drag source that will initiate the drag-and-drop operation. The event is typically the event. + +- In the drag source event handler, call the method to initiate the drag-and-drop operation. In the call, specify the drag source, the data to be transferred, and the allowed effects. + +- Identify the element that will be a drop target. A drop target can be or a . + +- On the drop target, set the property to `true`. + +- In the drop target, create a event handler to process the dropped data. + +- In the event handler, extract the data from the by using the and methods. + +- In the event handler, use the data to perform the desired drag-and-drop operation. + + You can enhance your drag-and-drop implementation by creating a custom and by handling optional drag source and drop target events, as shown in the following tasks: + +- To transfer custom data or multiple data items, create a to pass to the method. + +- To perform additional actions during a drag, handle the , , and events on the drop target. + +- To change the appearance of the mouse pointer, handle the event on the drag source. + +- To change how the drag-and-drop operation is canceled, handle the event on the drag source. + + +## Drag-and-Drop Example + This section describes how to implement drag-and-drop for an element. The is both a drag source and a drop target. The transferred data is the string representation of the ellipse’s property. The following XAML shows the element and the drag-and-drop related events that it handles. For complete steps on how to implement drag-and-drop, see [Walkthrough: Enabling Drag and Drop on a User Control](walkthrough-enabling-drag-and-drop-on-a-user-control.md). + + [!code-xaml[DragDropSnippets#EllipseXaml](~/samples/snippets/csharp/VS_Snippets_Wpf/dragdropsnippets/cs/mainwindow.xaml#ellipsexaml)] + +### Enabling an Element to be a Drag Source + An object that is a drag source is responsible for: + +- Identifying when a drag occurs. + +- Initiating the drag-and-drop operation. + +- Identifying the data to be transferred. + +- Specifying the effects that the drag-and-drop operation is allowed to have on the transferred data. + + The drag source may also give feedback to the user regarding the allowed actions (move, copy, none), and can cancel the drag-and-drop operation based on additional user input, such as pressing the ESC key during the drag. + + It is the responsibility of your application to determine when a drag occurs, and then initiate the drag-and-drop operation by calling the method. Typically, this is when a event occurs over the element to be dragged while a mouse button is pressed. The following example shows how to initiate a drag-and-drop operation from the event handler of an element to make it a drag source. The transferred data is the string representation of the ellipse’s property. + + [!code-csharp[DragDropSnippets#DoDragDrop](~/samples/snippets/csharp/VS_Snippets_Wpf/dragdropsnippets/cs/mainwindow.xaml.cs#dodragdrop)] + [!code-vb[DragDropSnippets#DoDragDrop](~/samples/snippets/visualbasic/VS_Snippets_Wpf/dragdropsnippets/vb/mainwindow.xaml.vb#dodragdrop)] + + Inside of the event handler, call the method to initiate the drag-and-drop operation. The method takes three parameters: + +- `dragSource` – A reference to the dependency object that is the source of the transferred data; this is typically the source of the event. + +- `data` - An object that contains the transferred data, wrapped in a . + +- `allowedEffects` - One of the enumeration values that specifies the permitted effects of the drag-and-drop operation. + + Any serializable object can be passed in the `data` parameter. If the data is not already wrapped in a , it will automatically be wrapped in a new . To pass multiple data items, you must create the yourself, and pass it to the method. For more information, see [Data and Data Objects](data-and-data-objects.md). + + The `allowedEffects` parameter is used to specify what the drag source will allow the drop target to do with the transferred data. The common values for a drag source are , , and . + +> [!NOTE] +> The drop target is also able to specify what effects it intends in response to the dropped data. For example, if the drop target does not recognize the data type to be dropped, it can refuse the data by setting its allowed effects to . It typically does this in its event handler. + + A drag source can optionally handle the and events. These events have default handlers that are used unless you mark the events as handled. You will typically ignore these events unless you have a specific need to change their default behavior. + + The event is raised continuously while the drag source is being dragged. The default handler for this event checks whether the drag source is over a valid drop target. If it is, it checks the allowed effects of the drop target. It then gives feedback to the end user regarding the allowed drop effects. This is typically done by changing the mouse cursor to a no-drop, copy, or move cursor. You should only handle this event if you need to use custom cursors to provide feedback to the user. If you handle this event, be sure to mark it as handled so that the default handler does not override your handler. + + The event is raised continuously while the drag source is being dragged. You can handle this event to determine what action ends the drag-and-drop operation based on the state of the ESC, SHIFT, CTRL, and ALT keys, as well as the state of the mouse buttons. The default handler for this event cancels the drag-and-drop operation if the ESC key is pressed, and drops the data if the mouse button is released. + +> [!CAUTION] +> These events are raised continuously during the drag-and-drop operation. Therefore, you should avoid resource-intensive tasks in the event handlers. For example, use a cached cursor instead of creating a new cursor each time the event is raised. + +### Enabling an Element to be a Drop Target + An object that is a drop target is responsible for: + +- Specifying that it is a valid drop target. + +- Responding to the drag source when it drags over the target. + +- Checking that the transferred data is in a format that it can receive. + +- Processing the dropped data. + + To specify that an element is a drop target, you set its property to `true`. The drop target events will then be raised on the element so that you can handle them. During a drag-and-drop operation, the following sequence of events occurs on the drop target: + +1. + +2. + +3. or + + The event occurs when the data is dragged into the drop target's boundary. You typically handle this event to provide a preview of the effects of the drag-and-drop operation, if appropriate for your application. Do not set the property in the event, as it will be overwritten in the event. + + The following example shows the event handler for an element. This code previews the effects of the drag-and-drop operation by saving the current brush. It then uses the method to check whether the being dragged over the ellipse contains string data that can be converted to a . If so, the data is extracted using the method. It is then converted to a and applied to the ellipse. The change is reverted in the event handler. If the data cannot be converted to a , no action is performed. + + [!code-csharp[DragDropSnippets#DragEnter](~/samples/snippets/csharp/VS_Snippets_Wpf/dragdropsnippets/cs/mainwindow.xaml.cs#dragenter)] + [!code-vb[DragDropSnippets#DragEnter](~/samples/snippets/visualbasic/VS_Snippets_Wpf/dragdropsnippets/vb/mainwindow.xaml.vb#dragenter)] + + The event occurs continuously while the data is dragged over the drop target. This event is paired with the event on the drag source. In the event handler, you typically use the and methods to check whether the transferred data is in a format that the drop target can process. You can also check whether any modifier keys are pressed, which will typically indicate whether the user intends a move or copy action. After these checks are performed, you set the property to notify the drag source what effect dropping the data will have. The drag source receives this information in the event args, and can set an appropriate cursor to give feedback to the user. + + The following example shows the event handler for an element. This code checks to see if the being dragged over the ellipse contains string data that can be converted to a . If so, it sets the property to . This indicates to the drag source that the data can be copied to the ellipse. If the data cannot be converted to a , the property is set to . This indicates to the drag source that the ellipse is not a valid drop target for the data. + + [!code-csharp[DragDropSnippets#DragOver](~/samples/snippets/csharp/VS_Snippets_Wpf/dragdropsnippets/cs/mainwindow.xaml.cs#dragover)] + [!code-vb[DragDropSnippets#DragOver](~/samples/snippets/visualbasic/VS_Snippets_Wpf/dragdropsnippets/vb/mainwindow.xaml.vb#dragover)] + + The event occurs when the data is dragged out of the target's boundary without being dropped. You handle this event to undo anything that you did in the event handler. + + The following example shows the event handler for an element. This code undoes the preview performed in the event handler by applying the saved to the ellipse. + + [!code-csharp[DragDropSnippets#DragLeave](~/samples/snippets/csharp/VS_Snippets_Wpf/dragdropsnippets/cs/mainwindow.xaml.cs#dragleave)] + [!code-vb[DragDropSnippets#DragLeave](~/samples/snippets/visualbasic/VS_Snippets_Wpf/dragdropsnippets/vb/mainwindow.xaml.vb#dragleave)] + + The event occurs when the data is dropped over the drop target; by default, this happens when the mouse button is released. In the event handler, you use the method to extract the transferred data from the and perform any data processing that your application requires. The event ends the drag-and-drop operation. + + The following example shows the event handler for an element. This code applies the effects of the drag-and-drop operation, and is similar to the code in the event handler. It checks to see if the being dragged over the ellipse contains string data that can be converted to a . If so, the is applied to the ellipse. If the data cannot be converted to a , no action is performed. + + [!code-csharp[DragDropSnippets#Drop](~/samples/snippets/csharp/VS_Snippets_Wpf/dragdropsnippets/cs/mainwindow.xaml.cs#drop)] + [!code-vb[DragDropSnippets#Drop](~/samples/snippets/visualbasic/VS_Snippets_Wpf/dragdropsnippets/vb/mainwindow.xaml.vb#drop)] + +## See also + +- +- [Walkthrough: Enabling Drag and Drop on a User Control](walkthrough-enabling-drag-and-drop-on-a-user-control.md) +- [How-to Topics](drag-and-drop-how-to-topics.md) +- [Drag and Drop](drag-and-drop.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/drag-and-drop.md b/dotnet-desktop-guide/framework/wpf/advanced/drag-and-drop.md new file mode 100644 index 0000000000..4ba1d4440e --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/drag-and-drop.md @@ -0,0 +1,29 @@ +--- +title: "Drag and Drop" +ms.date: "03/30/2017" +f1_keywords: + - "AutoGeneratedOrientationPage" +helpviewer_keywords: + - "data [WPF], drag-and-drop" + - "drag and drop [WPF]" + - "drag-and-drop [WPF]" +ms.assetid: 77c48920-8c8b-41eb-8fe8-b411962c8623 +--- +# Drag and Drop +[!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] provides a highly flexible drag and drop infrastructure which supports dragging and dropping of data within both [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] applications as well as other Windows applications. + +## In This Section + [Drag and Drop Overview](drag-and-drop-overview.md) + [Data and Data Objects](data-and-data-objects.md) + [Walkthrough: Enabling Drag and Drop on a User Control](walkthrough-enabling-drag-and-drop-on-a-user-control.md) + [How-to Topics](drag-and-drop-how-to-topics.md) + +## Reference + + + + + + + +## Related Sections diff --git a/dotnet-desktop-guide/framework/wpf/advanced/draw-text-using-glyphs.md b/dotnet-desktop-guide/framework/wpf/advanced/draw-text-using-glyphs.md new file mode 100644 index 0000000000..54a663339a --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/draw-text-using-glyphs.md @@ -0,0 +1,24 @@ +--- +title: "Draw Text Using Glyphs" +ms.date: "03/30/2017" +helpviewer_keywords: + - "text [WPF], drawing with Glyphs objects" + - "Glyphs objects [WPF], drawing text" + - "typography [WPF], Glyphs objects" +ms.assetid: 587ab17e-a419-4ad5-b6da-8933a8e83d97 +--- +# Draw Text Using Glyphs +This topic explains how to use the low-level object to display text in [!INCLUDE[TLA#tla_xaml](../../../includes/tlasharptla-xaml-md.md)]. + +## Example + The following examples show how to define properties for a object in [!INCLUDE[TLA#tla_xaml](../../../includes/tlasharptla-xaml-md.md)]. The object represents the output of a in [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)]. The examples assume that the Arial, Courier New, and Times New Roman fonts are installed in the C:\WINDOWS\Fonts folder on the local computer. + + [!code-xaml[GlyphsOvwSample1#1](~/samples/snippets/csharp/VS_Snippets_Wpf/GlyphsOvwSample1/CS/default.xaml#1)] + + This example shows how to define other properties of objects in [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)]. + + [!code-xaml[GlyphsOvwSamp2#1](~/samples/snippets/csharp/VS_Snippets_Wpf/GlyphsOvwSamp2/CS/default.xaml#1)] + +## See also + +- [Typography in WPF](typography-in-wpf.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/drawing-formatted-text.md b/dotnet-desktop-guide/framework/wpf/advanced/drawing-formatted-text.md new file mode 100644 index 0000000000..e8ace9a04c --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/drawing-formatted-text.md @@ -0,0 +1,118 @@ +--- +title: "Drawing Formatted Text" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "text [WPF]" + - "typography [WPF], drawing formatted text" + - "formatted text [WPF]" + - "drawing [WPF], formatted text" +ms.assetid: b1d851c1-331c-4814-9964-6fe769db6f1f +--- +# Drawing Formatted Text +This topic provides an overview of the features of the object. This object provides low-level control for drawing text in [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] applications. + +## Technology Overview + The object allows you to draw multi-line text, in which each character in the text can be individually formatted. The following example shows text that has several formats applied to it. + + ![Text displayed using FormattedText object](./media/typography-in-wpf/text-formatted-linear-gradient.jpg) + +> [!NOTE] +> For those developers migrating from the Win32 API, the table in the [Win32 Migration](#win32_migration) section lists the Win32 DrawText flags and the approximate equivalent in [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)]. + +### Reasons for Using Formatted Text + [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] includes multiple controls for drawing text to the screen. Each control is targeted to a different scenario and has its own list of features and limitations. In general, the element should be used when limited text support is required, such as a brief sentence in a [!INCLUDE[TLA#tla_ui](../../../includes/tlasharptla-ui-md.md)]. can be used when minimal text support is required. For more information, see [Documents in WPF](documents-in-wpf.md). + + The object provides greater text formatting features than [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] text controls, and can be useful in cases where you want to use text as a decorative element. For more information, see the following section [Converting Formatted Text to a Geometry](#converting_formatted_text). + + In addition, the object is useful for creating text-oriented -derived objects. is a lightweight drawing class that is used to render shapes, images, or text. For more information, see [Hit Test Using DrawingVisuals Sample](https://github.com/Microsoft/WPF-Samples/tree/master/Visual%20Layer/DrawingVisual). + +## Using the FormattedText Object + To create formatted text, call the constructor to create a object. Once you have created the initial formatted text string, you can apply a range of formatting styles. + + Use the property to constrain the text to a specific width. The text will automatically wrap to avoid exceeding the specified width. Use the property to constrain the text to a specific height. The text will display an ellipsis, "…" for the text that exceeds the specified height. + + ![Text displayed with wordwrap and ellipsis.](./media/drawing-formatted-text/formatted-text-wordwrap-ellipsis.png) + + You can apply multiple formatting styles to one or more characters. For example, you could call both the and methods to change the formatting of the first five characters in the text. + + The following code example creates a object and then applies several formatting styles to the text. + + [!code-csharp[FormattedTextSnippets#FormattedTextSnippets1](~/samples/snippets/csharp/VS_Snippets_Wpf/FormattedTextSnippets/CSharp/Window1.xaml.cs#formattedtextsnippets1)] + [!code-vb[FormattedTextSnippets#FormattedTextSnippets1](~/samples/snippets/visualbasic/VS_Snippets_Wpf/FormattedTextSnippets/visualbasic/window1.xaml.vb#formattedtextsnippets1)] + +### Font Size Unit of Measure + As with other text objects in [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] applications, the object uses device-independent pixels as the unit of measure. However, most Win32 applications use points as the unit of measure. If you want to use display text in units of points in [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] applications, you need to convert device-independent units (1/96th inch per unit) to points. The following code example shows how to perform this conversion. + + [!code-csharp[FormattedTextSnippets#FormattedTextSnippets2](~/samples/snippets/csharp/VS_Snippets_Wpf/FormattedTextSnippets/CSharp/Window1.xaml.cs#formattedtextsnippets2)] + [!code-vb[FormattedTextSnippets#FormattedTextSnippets2](~/samples/snippets/visualbasic/VS_Snippets_Wpf/FormattedTextSnippets/visualbasic/window1.xaml.vb#formattedtextsnippets2)] + + +### Converting Formatted Text to a Geometry + You can convert formatted text into objects, allowing you to create other types of visually interesting text. For example, you could create a object based on the outline of a text string. + + ![Text outline using a linear gradient brush](./media/typography-in-wpf/text-outline-linear-gradient.jpg) + + The following examples illustrate several ways of creating interesting visual effects by modifying the stroke, fill, and highlight of converted text. + + ![Text with different colors for fill and stroke](./media/typography-in-wpf/fill-stroke-text-effect.jpg) + + ![Text with image brush applied to stroke](./media/typography-in-wpf/image-brush-application.jpg) + + ![Text with image brush applied to stroke and highlight](./media/typography-in-wpf/image-brush-text-application.jpg) + + When text is converted to a object, it is no longer a collection of characters—you cannot modify the characters in the text string. However, you can affect the appearance of the converted text by modifying its stroke and fill properties. The stroke refers to the outline of the converted text; the fill refers to the area inside the outline of the converted text. For more information, see [Create Outlined Text](how-to-create-outlined-text.md). + + You can also convert formatted text to a object, and use the object for highlighting the text. For example, you could apply an animation to the object so that the animation follows the outline of the formatted text. + + The following example shows formatted text that has been converted to a object. An animated ellipse follows the path of the strokes of the rendered text. + + ![Sphere following the path geometry of text](./media/drawing-formatted-text/sphere-following-geometry-path.gif) +Sphere following the path geometry of text + + For more information, see [How to: Create a PathGeometry Animation for Text](https://docs.microsoft.com/previous-versions/dotnet/netframework-4.0/ms743610(v=vs.100)). + + You can create other interesting uses for formatted text once it has been converted to a object. For example, you can clip video to display inside it. + + ![Video displaying in the path geometry of text](./media/drawing-formatted-text/video-displaying-text-path-geometry.png) + + +## Win32 Migration + The features of for drawing text are similar to the features of the Win32 DrawText function. For those developers migrating from the Win32 API, the following table lists the Win32 DrawText flags and the approximate equivalent in [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)]. + +|DrawText flag|WPF equivalent|Notes| +|-------------------|--------------------|-----------| +|DT_BOTTOM||Use the property to compute an appropriate Win32 DrawText 'y' position.| +|DT_CALCRECT|, |Use the and properties to calculate the output rectangle.| +|DT_CENTER||Use the property with the value set to .| +|DT_EDITCONTROL|None|Not required. Space width and last line rendering are the same as in the framework edit control.| +|DT_END_ELLIPSIS||Use the property with the value .

Use to get Win32 DT_END_ELLIPSIS with DT_WORD_ELIPSIS end ellipsis—in this case, character ellipsis only occurs on words that do not fit on a single line.| +|DT_EXPAND_TABS|None|Not required. Tabs are automatically expanded to stops every 4 ems, which is approximately the width of 8 language-independent characters.| +|DT_EXTERNALLEADING|None|Not required. External leading is always included in line spacing. Use the property to create user-defined line spacing.| +|DT_HIDEPREFIX|None|Not supported. Remove the '&' from the string before constructing the object.| +|DT_LEFT||This is the default text alignment. Use the property with the value set to . (WPF only)| +|DT_MODIFYSTRING|None|Not supported.| +|DT_NOCLIP||Clipping does not happen automatically. If you want to clip text, use the property.| +|DT_NOFULLWIDTHCHARBREAK|None|Not supported.| +|DT_NOPREFIX|None|Not required. The '&' character in strings is always treated as a normal character.| +|DT_PATHELLIPSIS|None|Use the property with the value .| +|DT_PREFIX|None|Not supported. If you want to use underscores for text, such as an accelerator key or link, use the method.| +|DT_PREFIXONLY|None|Not supported.| +|DT_RIGHT||Use the property with the value set to . (WPF only)| +|DT_RTLREADING||Set the property to .| +|DT_SINGLELINE|None|Not required. objects behave as a single line control, unless either the property is set or the text contains a carriage return/line feed (CR/LF).| +|DT_TABSTOP|None|No support for user-defined tab stop positions.| +|DT_TOP||Not required. Top justification is the default. Other vertical positioning values can be defined by using the property to compute an appropriate Win32 DrawText 'y' position.| +|DT_VCENTER||Use the property to compute an appropriate Win32 DrawText 'y' position.| +|DT_WORDBREAK|None|Not required. Word breaking happens automatically with objects. You cannot disable it.| +|DT_WORD_ELLIPSIS||Use the property with the value .| + +## See also + +- +- [Documents in WPF](documents-in-wpf.md) +- [Typography in WPF](typography-in-wpf.md) +- [Create Outlined Text](how-to-create-outlined-text.md) +- [How to: Create a PathGeometry Animation for Text](https://docs.microsoft.com/previous-versions/dotnet/netframework-4.0/ms743610(v=vs.100)) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/dynamicresource-markup-extension.md b/dotnet-desktop-guide/framework/wpf/advanced/dynamicresource-markup-extension.md new file mode 100644 index 0000000000..f3f155db26 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/dynamicresource-markup-extension.md @@ -0,0 +1,77 @@ +--- +title: "DynamicResource Markup Extension" +ms.date: "03/30/2017" +f1_keywords: + - "DynamicResource" + - "DynamicResourceExtension" +helpviewer_keywords: + - "XAML [WPF], DynamicResource markup extension" + - "DynamicResource markup extensions [WPF]" +ms.assetid: 7324f243-03af-4c2b-b0db-26ac6cdfcbe4 +--- +# DynamicResource Markup Extension +Provides a value for any [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] property attribute by deferring that value to be a reference to a defined resource. Lookup behavior for that resource is analogous to run-time lookup. + +## XAML Attribute Usage + +```xml + +``` + +## XAML Property Element Usage + +```xml + + + + + +``` + +## XAML Values + +||| +|-|-| +|`key`|The key for the requested resource. This key was initially assigned by the [x:Key Directive](/dotnet/desktop-wpf/xaml-services/xkey-directive) if a resource was created in markup, or was provided as the `key` parameter when calling if the resource was created in code.| + +## Remarks + A `DynamicResource` will create a temporary expression during the initial compilation and thus defer lookup for resources until the requested resource value is actually required in order to construct an object. This may potentially be after the [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] page is loaded. The resource value will be found based on key search against all active resource dictionaries starting from the current page scope, and is substituted for the placeholder expression from compilation. + +> [!IMPORTANT] +> In terms of dependency property precedence, a `DynamicResource` expression is equivalent to the position where the dynamic resource reference is applied. If you set a local value for a property that previously had a `DynamicResource` expression as the local value, the `DynamicResource` is completely removed. For details, see [Dependency Property Value Precedence](dependency-property-value-precedence.md). + + Certain resource access scenarios are particularly appropriate for `DynamicResource` as opposed to a [StaticResource Markup Extension](staticresource-markup-extension.md). See [XAML Resources](/dotnet/desktop-wpf/fundamentals/xaml-resources-define) for a discussion about the relative merits and performance implications of `DynamicResource` and `StaticResource`. + + The specified should correspond to an existing resource determined by [x:Key Directive](/dotnet/desktop-wpf/xaml-services/xkey-directive) at some level in your page, application, the available control themes and external resources, or system resources, and the resource lookup will happen in that order. For more information about resource lookup for static and dynamic resources, see [XAML Resources](/dotnet/desktop-wpf/fundamentals/xaml-resources-define). + + A resource key may be any string defined in the [XamlName Grammar](/dotnet/desktop-wpf/xaml-services/xamlname-grammar). A resource key may also be other object types, such as a . A key is fundamental to how controls can be styled by themes. For more information, see [Control Authoring Overview](../controls/control-authoring-overview.md). + + APIs for lookup of resource values, such as , follow the same resource lookup logic as used by `DynamicResource`. + + The alternative declarative means of referencing a resource is as a [StaticResource Markup Extension](staticresource-markup-extension.md). + + Attribute syntax is the most common syntax used with this markup extension. The string token provided after the `DynamicResource` identifier string is assigned as the value of the underlying extension class. + + `DynamicResource` can be used in object element syntax. In this case, specifying the value of the property is required. + + `DynamicResource` can also be used in a verbose attribute usage that specifies the property as a property=value pair: + +```xml + +``` + + The verbose usage is often useful for extensions that have more than one settable property, or if some properties are optional. Because `DynamicResource` has only one settable property, which is required, this verbose usage is not typical. + + In the [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] processor implementation, the handling for this markup extension is defined by the class. + + `DynamicResource` is a markup extension. Markup extensions are typically implemented when there is a requirement to escape attribute values to be other than literal values or handler names, and the requirement is more global than just putting type converters on certain types or properties. All markup extensions in [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] use the { and } characters in their attribute syntax, which is the convention by which a [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] processor recognizes that a markup extension must process the attribute. For more information, see [Markup Extensions and WPF XAML](markup-extensions-and-wpf-xaml.md). + +## See also + +- [XAML Resources](/dotnet/desktop-wpf/fundamentals/xaml-resources-define) +- [Resources and Code](resources-and-code.md) +- [x:Key Directive](/dotnet/desktop-wpf/xaml-services/xkey-directive) +- [XAML Overview (WPF)](/dotnet/desktop-wpf/fundamentals/xaml) +- [Markup Extensions and WPF XAML](markup-extensions-and-wpf-xaml.md) +- [StaticResource Markup Extension](staticresource-markup-extension.md) +- [Markup Extensions and WPF XAML](markup-extensions-and-wpf-xaml.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/element-tree-and-serialization-how-to-topics.md b/dotnet-desktop-guide/framework/wpf/advanced/element-tree-and-serialization-how-to-topics.md new file mode 100644 index 0000000000..c8dbef3cd2 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/element-tree-and-serialization-how-to-topics.md @@ -0,0 +1,25 @@ +--- +title: "Element Tree and Serialization How-to Topics" +ms.date: "03/30/2017" +f1_keywords: + - "AutoGeneratedOrientationPage" +helpviewer_keywords: + - "element tree [WPF]" + - "serialization [WPF]" +ms.assetid: 2d8ef436-d559-4c3e-86de-5a160d5f87d2 +--- +# Element Tree and Serialization How-to Topics +The topics in this section describe how to use the WPF element tree. + +## In This Section + [Find an Element by Its Name](how-to-find-an-element-by-its-name.md) + [Override the Logical Tree](how-to-override-the-logical-tree.md) + +## Reference + + + + + + +## Related Sections diff --git a/dotnet-desktop-guide/framework/wpf/advanced/element-tree-and-serialization.md b/dotnet-desktop-guide/framework/wpf/advanced/element-tree-and-serialization.md new file mode 100644 index 0000000000..5090f0410d --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/element-tree-and-serialization.md @@ -0,0 +1,37 @@ +--- +title: "Element Tree and Serialization" +ms.date: "03/30/2017" +f1_keywords: + - "AutoGeneratedOrientationPage" +helpviewer_keywords: + - "element tree [WPF]" + - "serialization [WPF]" + - "tree [WPF]" +ms.assetid: 8f57e879-180b-421f-b3d0-ac007ff2ce80 +--- +# Element Tree and Serialization +WPF programming elements often exist in some form of tree relationship to each other. For instance, an application UI created in XAML can be conceptualized as an object tree. The element tree can be further divided into two discrete yet sometimes parallel trees: the logical tree and the visual tree. Serialization in WPF involves saving the state of these two trees as well as application state and writing it to a file, potentially as XAML. + +## In This Section + [Trees in WPF](trees-in-wpf.md) + [Serialization Limitations of XamlWriter.Save](serialization-limitations-of-xamlwriter-save.md) + [Initialization for Object Elements Not in an Object Tree](initialization-for-object-elements-not-in-an-object-tree.md) + [How-to Topics](element-tree-and-serialization-how-to-topics.md) + +## Reference + + + + + + +## Related Sections + [WPF Architecture](wpf-architecture.md) + [XAML in WPF](xaml-in-wpf.md) + [Base Elements](base-elements.md) + [Properties](properties-wpf.md) + [Events](events-wpf.md) + [Input](input-wpf.md) + [Resources](resources-wpf.md) + [Styling and Templating](/dotnet/desktop-wpf/fundamentals/styles-templates-overview) + [Threading Model](threading-model.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/events-how-to-topics.md b/dotnet-desktop-guide/framework/wpf/advanced/events-how-to-topics.md new file mode 100644 index 0000000000..33d63cf404 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/events-how-to-topics.md @@ -0,0 +1,27 @@ +--- +title: "Events How-to Topics" +ms.date: "03/30/2017" +f1_keywords: + - "AutoGeneratedOrientationPage" +helpviewer_keywords: + - "events [WPF], how-to topics" +ms.assetid: 00463181-36eb-4be0-bfa2-452854cce642 +--- +# Events How-to Topics +The topics in this section describe how to use events in WPF. + +## In This Section + [Add an Event Handler Using Code](how-to-add-an-event-handler-using-code.md) + [Handle a Routed Event](how-to-handle-a-routed-event.md) + [Create a Custom Routed Event](how-to-create-a-custom-routed-event.md) + [Find the Source Element in an Event Handler](how-to-find-the-source-element-in-an-event-handler.md) + [Add Class Handling for a Routed Event](how-to-add-class-handling-for-a-routed-event.md) + +## Reference + + + + + + +## Related Sections diff --git a/dotnet-desktop-guide/framework/wpf/advanced/events-wpf.md b/dotnet-desktop-guide/framework/wpf/advanced/events-wpf.md new file mode 100644 index 0000000000..fbbec15d72 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/events-wpf.md @@ -0,0 +1,43 @@ +--- +title: "Events" +ms.date: "03/30/2017" +f1_keywords: + - "AutoGeneratedOrientationPage" +helpviewer_keywords: + - "Windows Presentation Foundation [WPF], events" + - "events [WPF], windows" + - "WPF [WPF], events" +ms.assetid: d3b93c6f-aa6b-486d-a010-d097ea8a516b +--- +# Events (WPF) +[!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] introduces routed events that can invoke handlers that exist on various listeners in the element tree of an application. + +## In This Section + [Routed Events Overview](routed-events-overview.md) + [Attached Events Overview](attached-events-overview.md) + [Object Lifetime Events](object-lifetime-events.md) + [Marking Routed Events as Handled, and Class Handling](marking-routed-events-as-handled-and-class-handling.md) + [Preview Events](preview-events.md) + [Property Change Events](property-change-events.md) + [Visual Basic and WPF Event Handling](visual-basic-and-wpf-event-handling.md) + [Weak Event Patterns](weak-event-patterns.md) + [How-to Topics](events-how-to-topics.md) + +## Reference + + + + + + +## Related Sections + [WPF Architecture](wpf-architecture.md) + [XAML in WPF](xaml-in-wpf.md) + [Base Elements](base-elements.md) + [Element Tree and Serialization](element-tree-and-serialization.md) + [Properties](properties-wpf.md) + [Input](input-wpf.md) + [Resources](resources-wpf.md) + [Styling and Templating](/dotnet/desktop-wpf/fundamentals/styles-templates-overview) + [WPF Content Model](../controls/wpf-content-model.md) + [Threading Model](threading-model.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/flow-content-elements-how-to-topics.md b/dotnet-desktop-guide/framework/wpf/advanced/flow-content-elements-how-to-topics.md new file mode 100644 index 0000000000..ccc0c2d444 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/flow-content-elements-how-to-topics.md @@ -0,0 +1,37 @@ +--- +title: "Flow Content Elements How-to Topics" +ms.date: "03/30/2017" +f1_keywords: + - "AutoGeneratedOrientationPage" +helpviewer_keywords: + - "flow content elements [WPF], how-to topics" + - "documents [WPF], flow content reference" +ms.assetid: ef5175df-6ab9-4096-be0c-804003b44c64 +--- +# Flow Content Elements How-to Topics +The topics in this section describe how to accomplish common tasks using various flow content elements and related features. + +## In This Section + [Adjust Spacing Between Paragraphs](how-to-adjust-spacing-between-paragraphs.md) + [Build a Table Programmatically](how-to-build-a-table-programmatically.md) + [Change the FlowDirection of Content Programmatically](how-to-change-the-flowdirection-of-content-programmatically.md) + [Change the TextWrapping Property Programmatically](how-to-change-the-textwrapping-property-programmatically.md) + [Define a Table with XAML](how-to-define-a-table-with-xaml.md) + [Alter the Typography of Text](how-to-alter-the-typography-of-text.md) + [Enable Text Trimming](how-to-enable-text-trimming.md) + [Insert an Element Into Text Programmatically](how-to-insert-an-element-into-text-programmatically.md) + [Manipulate Flow Content Elements through the Blocks Property](how-to-manipulate-flow-content-elements-through-the-blocks-property.md) + [Manipulate Flow Content Elements through the Inlines Property](how-to-manipulate-flow-content-elements-through-the-inlines-property.md) + [Manipulate a FlowDocument through the Blocks Property](how-to-manipulate-a-flowdocument-through-the-blocks-property.md) + [Manipulate a Table's Columns through the Columns Property](how-to-manipulate-table-columns-through-the-columns-property.md) + [Manipulate a Table's Row Groups through the RowGroups Property](how-to-manipulate-table-row-groups-through-the-rowgroups-property.md) + [Use Flow Content Elements](how-to-use-flow-content-elements.md) + [Use FlowDocument Column-Separating Attributes](how-to-use-flowdocument-column-separating-attributes.md) + +## Reference + + + + +## Related Sections + [Documents in WPF](documents-in-wpf.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/flow-content.md b/dotnet-desktop-guide/framework/wpf/advanced/flow-content.md new file mode 100644 index 0000000000..6e869036eb --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/flow-content.md @@ -0,0 +1,36 @@ +--- +title: "Flow Content" +ms.date: "03/30/2017" +f1_keywords: + - "AutoGeneratedOrientationPage" +helpviewer_keywords: + - "documents [WPF], flow content reference" + - "flow content reference [WPF]" +ms.assetid: d32501af-0bac-4b80-8a20-61a6996753fe +--- +# Flow Content +Flow content elements provide the building blocks for creating flow content suitable for hosting in a . + +## In This Section + [Flow Document Overview](flow-document-overview.md) + [TextElement Content Model Overview](textelement-content-model-overview.md) + [Table Overview](table-overview.md) + [How-to Topics](flow-content-elements-how-to-topics.md) + +## Reference + + + + + + + + + + + + + + +## Related Sections + [Documents in WPF](documents-in-wpf.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/flow-document-overview.md b/dotnet-desktop-guide/framework/wpf/advanced/flow-document-overview.md new file mode 100644 index 0000000000..ee7a895f53 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/flow-document-overview.md @@ -0,0 +1,374 @@ +--- +title: "Flow Document Overview" +description: Learn about flow documents in Windows Presentation Foundation, which dynamically adjust content based on window size, device resolution, and user preferences. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "documents [WPF], flow documents [WPF], , " + - ", " + - "flow documents [WPF]" +ms.assetid: ef236a50-d44f-43c8-ba7c-82b0c733c0b7 +--- +# Flow Document Overview + +Flow documents are designed to optimize viewing and readability. Rather than being set to one predefined layout, flow documents dynamically adjust and reflow their content based on run-time variables such as window size, device resolution, and optional user preferences. In addition, flow documents offer advanced document features, such as pagination and columns. This topic provides an overview of flow documents and how to create them. + + + +## What is a Flow Document + +A flow document is designed to "reflow content" depending on window size, device resolution, and other environment variables. In addition, flow documents have a number of built in features including search, viewing modes that optimize readability, and the ability to change the size and appearance of fonts. Flow Documents are best utilized when ease of reading is the primary document consumption scenario. In contrast, Fixed Documents are designed to have a static presentation. Fixed Documents are useful when fidelity of the source content is essential. See [Documents in WPF](documents-in-wpf.md) for more information on different types of documents. + +The following illustration shows a sample flow document viewed in several windows of different sizes. As the display area changes, the content reflows to make the best use of the available space. + +![Flow Document Content Reflow](./media/edocs-flowdocument.png "eDocs_FlowDocument") + +As seen in the image above, flow content can include many components including paragraphs, lists, images, and more. These components correspond to elements in markup and objects in procedural code. We will go over these classes in detail later in the [Flow Related Classes](#flow_related_classes) section of this overview. For now, here is a simple code example that creates a flow document consisting of a paragraph with some bold text and a list. + +[!code-xaml[FlowOvwSnippets_snip#SimpleFlowExampleWholePage](~/samples/snippets/csharp/VS_Snippets_Wpf/FlowOvwSnippets_snip/CS/SimpleFlowExample.xaml#simpleflowexamplewholepage)] + +[!code-csharp[FlowOvwSnippets_procedural_snip#SimpleFlowCodeOnlyExampleWholePage](~/samples/snippets/csharp/VS_Snippets_Wpf/FlowOvwSnippets_procedural_snip/CSharp/SimpleFlowExample.cs#simpleflowcodeonlyexamplewholepage)] +[!code-vb[FlowOvwSnippets_procedural_snip#SimpleFlowCodeOnlyExampleWholePage](~/samples/snippets/visualbasic/VS_Snippets_Wpf/FlowOvwSnippets_procedural_snip/VisualBasic/SimpleFlowExample.vb#simpleflowcodeonlyexamplewholepage)] + +The illustration below shows what this code snippet looks like. + +![Screenshot: Rendered FlowDocument example](./media/flow-ovw-first-example.png "Flow_Ovw_First_Example") + +In this example, the control is used to host the flow content. See [Flow Document Types](#flow_document_types) for more information on flow content hosting controls. , , , and elements are used to control content formatting, based on their order in markup. For example, the element spans across only part of the text in the paragraph; as a result, only that part of the text is bold. If you have used HTML, this will be familiar to you. + +As highlighted in the illustration above, there are several features built into Flow Documents: + +- Search: Allows the user to perform a full text search of an entire document. + +- Viewing Mode: The user can select their preferred viewing mode including a single-page (page-at-a-time) viewing mode, a two-page-at-a-time (book reading format) viewing mode, and a continuous scrolling (bottomless) viewing mode. For more information about these viewing modes, see . + +- Page Navigation Controls: If the viewing mode of the document uses pages, the page navigation controls include a button to jump to the next page (the down arrow) or previous page (the up arrow), as well as indicators for the current page number and total number of pages. Flipping through pages can also be accomplished using the keyboard arrow keys. + +- Zoom: The zoom controls enable the user to increase or decrease the zoom level by clicking the plus or minus buttons, respectively. The zoom controls also include a slider for adjusting the zoom level. For more information, see . + +These features can be modified based upon the control used to host the flow content. The next section describes the different controls. + + + +## Flow Document Types + +Display of flow document content and how it appears is dependent upon what object is used to host the flow content. There are four controls that support viewing of flow content: , , , and . These controls are briefly described below. + +> [!NOTE] +> is required to directly host flow content, so all of these viewing controls consume a to enable flow content hosting. + +### FlowDocumentReader + + includes features that enable the user to dynamically choose between various viewing modes, including a single-page (page-at-a-time) viewing mode, a two-page-at-a-time (book reading format) viewing mode, and a continuous scrolling (bottomless) viewing mode. For more information about these viewing modes, see . If you do not need the ability to dynamically switch between different viewing modes, and provide lighter-weight flow content viewers that are fixed in a particular viewing mode. + +### FlowDocumentPageViewer and FlowDocumentScrollViewer + + shows content in page-at-a-time viewing mode, while shows content in continuous scrolling mode. Both and are fixed to a particular viewing mode. Compare to , which includes features that enable the user to dynamically choose between various viewing modes (as provided by the enumeration), at the cost of being more resource intensive than or . + +By default, a vertical scrollbar is always shown, and a horizontal scrollbar becomes visible if needed. The default UI for does not include a toolbar; however, the property can be used to enable a built-in toolbar. + +### RichTextBox + +You use a when you want to allow the user to edit flow content. For example, if you wanted to create an editor that allowed a user to manipulate things like tables, italic and bold formatting, etc, you would use a . See [RichTextBox Overview](../controls/richtextbox-overview.md) for more information. + +> [!NOTE] +> Flow content inside a does not behave exactly like flow content contained in other controls. For example, there are no columns in a and hence no automatic resizing behavior. Also, the typically built in features of flow content like search, viewing mode, page navigation, and zoom are not available within a . + + + +## Creating Flow Content + +Flow content can be complex, consisting of various elements including text, images, tables, and even derived classes like controls. To understand how to create complex flow content, the following points are critical: + +- **Flow-related Classes**: Each class used in flow content has a specific purpose. In addition, the hierarchical relation between flow classes helps you understand how they are used. For example, classes derived from the class are used to contain other objects while classes derived from contain objects that are displayed. + +- **Content Schema**: A flow document can require a substantial number of nested elements. The content schema specifies possible parent/child relationships between elements. + +The following sections will go over each of these areas in more detail. + + + +## Flow Related Classes + +The diagram below shows the objects most typically used with flow content: + +![Diagram: Flow content element class hierarchy](./media/flow-class-hierarchy.png "Flow_Class_Hierarchy") + +For the purposes of flow content, there are two important categories: + +1. **Block-derived classes**: Also called "Block content elements" or just "Block Elements". Elements that inherit from can be used to group elements under a common parent or to apply common attributes to a group. + +2. **Inline-derived classes**: Also called "Inline content elements" or just "Inline Elements". Elements that inherit from are either contained within a Block Element or another Inline Element. Inline Elements are often used as the direct container of content that is rendered to the screen. For example, a (Block Element) can contain a (Inline Element) but the actually contains the text that is rendered on the screen. + +Each class in these two categories is briefly described below. + +### Block-derived Classes + +**Paragraph** + + is typically used to group content into a paragraph. The simplest and most common use of Paragraph is to create a paragraph of text. + +[!code-xaml[FlowOvwSnippets_snip#ParagraphExampleWholePage](~/samples/snippets/csharp/VS_Snippets_Wpf/FlowOvwSnippets_snip/CS/ParagraphExample.xaml#paragraphexamplewholepage)] + +[!code-csharp[FlowOvwSnippets_procedural_snip#ParagraphCodeOnlyExampleWholePage](~/samples/snippets/csharp/VS_Snippets_Wpf/FlowOvwSnippets_procedural_snip/CSharp/ParagraphExample.cs#paragraphcodeonlyexamplewholepage)] +[!code-vb[FlowOvwSnippets_procedural_snip#ParagraphCodeOnlyExampleWholePage](~/samples/snippets/visualbasic/VS_Snippets_Wpf/FlowOvwSnippets_procedural_snip/VisualBasic/ParagraphExample.vb#paragraphcodeonlyexamplewholepage)] + +However, you can also contain other inline-derived elements as you will see below. + +**Section** + + is used only to contain other -derived elements. It does not apply any default formatting to the elements it contains. However, any property values set on a applies to its child elements. A section also enables you to programmatically iterate through its child collection. is used in a similar manner to the \
tag in HTML. + +In the example below, three paragraphs are defined under one . The section has a property value of Red, therefore the background color of the paragraphs is also red. + +[!code-xaml[FlowOvwSnippets_snip#SectionExampleWholePage](~/samples/snippets/csharp/VS_Snippets_Wpf/FlowOvwSnippets_snip/CS/SectionExample.xaml#sectionexamplewholepage)] + +[!code-csharp[FlowOvwSnippets_procedural_snip#SectionCodeOnlyExampleWholePage](~/samples/snippets/csharp/VS_Snippets_Wpf/FlowOvwSnippets_procedural_snip/CSharp/SectionExample.cs#sectioncodeonlyexamplewholepage)] +[!code-vb[FlowOvwSnippets_procedural_snip#SectionCodeOnlyExampleWholePage](~/samples/snippets/visualbasic/VS_Snippets_Wpf/FlowOvwSnippets_procedural_snip/VisualBasic/SectionExample.vb#sectioncodeonlyexamplewholepage)] + +**BlockUIContainer** + + enables elements (i.e. a ) to be embedded in block-derived flow content. (see below) is used to embed elements in inline-derived flow content. and are important because there is no other way to use a in flow content unless it is contained within one of these two elements. + +The following example shows how to use the element to host objects within flow content. + +[!code-xaml[SpanSnippets#_BlockUIXAML](~/samples/snippets/csharp/VS_Snippets_Wpf/SpanSnippets/CSharp/Window1.xaml#_blockuixaml)] + +The following figure shows how this example renders: + +![Screenshot that shows a UIElement embedded in flow content.](./media/flow-document-overview/embedded-blockuicontainer.png) + +**List** + + is used to create a bulleted or numeric list. Set the property to a enumeration value to determine the style of the list. The example below shows how to create a simple list. + +[!code-xaml[FlowOvwSnippets_snip#ListExampleWholePage](~/samples/snippets/csharp/VS_Snippets_Wpf/FlowOvwSnippets_snip/CS/ListExample.xaml#listexamplewholepage)] + +[!code-csharp[FlowOvwSnippets_procedural_snip#ListCodeOnlyExampleWholePage](~/samples/snippets/csharp/VS_Snippets_Wpf/FlowOvwSnippets_procedural_snip/CSharp/ListExample.cs#listcodeonlyexamplewholepage)] +[!code-vb[FlowOvwSnippets_procedural_snip#ListCodeOnlyExampleWholePage](~/samples/snippets/visualbasic/VS_Snippets_Wpf/FlowOvwSnippets_procedural_snip/VisualBasic/ListExample.vb#listcodeonlyexamplewholepage)] + +> [!NOTE] +> is the only flow element that uses the to manage child elements. + +**Table** + + is used to create a table. is similar to the element but it has more capabilities and, therefore, requires greater resource overhead. Because is a , it cannot be used in flow content unless it is contained in a or . For more information on , see [Table Overview](table-overview.md). + +### Inline-derived Classes + +**Run** + + is used to contain unformatted text. You might expect objects to be used extensively in flow content. However, in markup, elements are not required to be used explicitly. is required to be used when creating or manipulating flow documents by using code. For example, in the markup below, the first specifies the element explicitly while the second does not. Both paragraphs generate identical output. + +[!code-xaml[FlowOvwSnippets_snip#RunExample1](~/samples/snippets/csharp/VS_Snippets_Wpf/FlowOvwSnippets_snip/CS/RunSnippetsExample.xaml#runexample1)] + +> [!NOTE] +> Starting in the .NET Framework 4, the property of the object is a dependency property. You can bind the property to a data source, such as a . The property fully supports one-way binding. The property also supports two-way binding, except for . For an example, see . + +**Span** + + groups other inline content elements together. No inherent rendering is applied to content within a element. However, elements that inherit from including , , and do apply formatting to text. + +Below is an example of a being used to contain inline content including text, a element, and a . + +[!code-xaml[FlowOvwSnippets_snip#SpanExampleWholePage](~/samples/snippets/csharp/VS_Snippets_Wpf/FlowOvwSnippets_snip/CS/SpanExample.xaml#spanexamplewholepage)] + +The following screenshot shows how this example renders. + +![Screenshot: Rendered Span example](./media/flow-spanexample.gif "Flow_SpanExample") + +**InlineUIContainer** + + enables elements (i.e. a control like ) to be embedded in an content element. This element is the inline equivalent to described above. Below is an example that uses to insert a inline in a . + +[!code-xaml[FlowOvwSnippets_snip#InlineUIContainerExampleWholePage](~/samples/snippets/csharp/VS_Snippets_Wpf/FlowOvwSnippets_snip/CS/InlineUIContainerExample.xaml#inlineuicontainerexamplewholepage)] + +[!code-csharp[FlowOvwSnippets_procedural_snip#InlineUIContainerCodeOnlyExampleWholePage](~/samples/snippets/csharp/VS_Snippets_Wpf/FlowOvwSnippets_procedural_snip/CSharp/InlineUIContainerExample.cs#inlineuicontainercodeonlyexamplewholepage)] +[!code-vb[FlowOvwSnippets_procedural_snip#InlineUIContainerCodeOnlyExampleWholePage](~/samples/snippets/visualbasic/VS_Snippets_Wpf/FlowOvwSnippets_procedural_snip/VisualBasic/InlineUIContainerExample.vb#inlineuicontainercodeonlyexamplewholepage)] + +> [!NOTE] +> does not need to be used explicitly in markup. If you omit it, an will be created anyway when the code is compiled. + +**Figure and Floater** + + and are used to embed content in Flow Documents with placement properties that can be customized independent of the primary content flow. or elements are often used to highlight or accentuate portions of content, to host supporting images or other content within the main content flow, or to inject loosely related content such as advertisements. + +The following example shows how to embed a into a paragraph of text. + +[!code-xaml[FlowOvwSnippets_snip#FigureExampleWholePage](~/samples/snippets/csharp/VS_Snippets_Wpf/FlowOvwSnippets_snip/CS/FigureExample.xaml#figureexamplewholepage)] + +[!code-csharp[FlowOvwSnippets_procedural_snip#FigureCodeOnlyExampleWholePage](~/samples/snippets/csharp/VS_Snippets_Wpf/FlowOvwSnippets_procedural_snip/CSharp/FigureExample.cs#figurecodeonlyexamplewholepage)] +[!code-vb[FlowOvwSnippets_procedural_snip#FigureCodeOnlyExampleWholePage](~/samples/snippets/visualbasic/VS_Snippets_Wpf/FlowOvwSnippets_procedural_snip/VisualBasic/FigureExample.vb#figurecodeonlyexamplewholepage)] + +The following illustration shows how this example renders. + +![Screenshot: Figure example](./media/flow-ovw-figure-example.png "Flow_Ovw_Figure_Example") + + and differ in several ways and are used for different scenarios. + +**Figure:** + +- Can be positioned: You can set its horizontal and vertical anchors to dock it relative to the page, content, column or paragraph. You can also use its and properties to specify arbitrary offsets. + +- Is sizable to more than one column: You can set height and width to multiples of page, content or column height or width. Note that in the case of page and content, multiples greater than 1 are not allowed. For example, you can set the width of a to be "0.5 page" or "0.25 content" or "2 Column". You can also set height and width to absolute pixel values. + +- Does not paginate: If the content inside a does not fit inside the , it will render whatever content does fit and the remaining content is lost + +**Floater:** + +- Cannot be positioned and will render wherever space can be made available for it. You cannot set the offset or anchor a . + +- Cannot be sized to more than one column: By default, sizes at one column. It has a property that can be set to an absolute pixel value, but if this value is greater than one column width it is ignored and the floater is sized at one column. You can size it to less than one column by setting the correct pixel width, but sizing is not column-relative, so "0.5Column" is not a valid expression for width. has no height property and it's height cannot be set, it’s height depends on the content + +- paginates: If its content at its specified width extends to more than 1 column height, floater breaks and paginates to the next column, the next page, etc. + + is a good place to put standalone content where you want to control the size and positioning, and are confident that the content will fit in the specified size. is a good place to put more free-flowing content that flows similar to the main page content, but is separated from it. + +**LineBreak** + + causes a line break to occur in flow content. The following example demonstrates the use of . + +[!code-xaml[FlowOvwSnippets_snip#LineBreakExampleWholePage](~/samples/snippets/csharp/VS_Snippets_Wpf/FlowOvwSnippets_snip/CS/LineBreakExample.xaml#linebreakexamplewholepage)] + +The following screenshot shows how this example renders. + +![Screenshot: LineBreak example](./media/flow-ovw-linebreakexample.png "Flow_Ovw_LineBreakExample") + +### Flow Collection Elements + +In many of the examples above, the and are used to construct flow content programmatically. For example, to add elements to a , you can use the syntax: + +```csharp +myParagraph.Inlines.Add(new Run("Some text")); +``` + +This adds a to the of the . This is the same as the implicit found inside a in markup: + +```xml + +Some Text + +``` + +As an example of using the , the following example creates a new and then uses the **Add** method to add a new to the contents. + +[!code-csharp[FlowDocumentSnippets#_SectionBlocksAdd](~/samples/snippets/csharp/VS_Snippets_Wpf/FlowDocumentSnippets/CSharp/Window1.xaml.cs#_sectionblocksadd)] +[!code-vb[FlowDocumentSnippets#_SectionBlocksAdd](~/samples/snippets/visualbasic/VS_Snippets_Wpf/FlowDocumentSnippets/visualbasic/window1.xaml.vb#_sectionblocksadd)] + +In addition to adding items to a flow collection, you can remove items as well. The following example deletes the last element in the . + +[!code-csharp[SpanSnippets#_SpanInlinesRemoveLast](~/samples/snippets/csharp/VS_Snippets_Wpf/SpanSnippets/CSharp/Window1.xaml.cs#_spaninlinesremovelast)] +[!code-vb[SpanSnippets#_SpanInlinesRemoveLast](~/samples/snippets/visualbasic/VS_Snippets_Wpf/SpanSnippets/visualbasic/window1.xaml.vb#_spaninlinesremovelast)] + +The following example clears all of the contents ( elements) from the . + +[!code-csharp[SpanSnippets#_SpanInlinesClear](~/samples/snippets/csharp/VS_Snippets_Wpf/SpanSnippets/CSharp/Window1.xaml.cs#_spaninlinesclear)] +[!code-vb[SpanSnippets#_SpanInlinesClear](~/samples/snippets/visualbasic/VS_Snippets_Wpf/SpanSnippets/visualbasic/window1.xaml.vb#_spaninlinesclear)] + +When working with flow content programmatically, you will likely make extensive use of these collections. + +Whether a flow element uses an (Inlines) or (Blocks) to contain its child elements depends on what type of child elements ( or ) can be contained by the parent. Containment rules for flow content elements are summarized in the content schema in the next section. + +> [!NOTE] +> There is a third type of collection used with flow content, the , but this collection is only used with a . In addition, there are several collections used with . See [Table Overview](table-overview.md) for more information. + + + +## Content Schema + +Given the number of different flow content elements, it can be overwhelming to keep track of what type of child elements an element can contain. The diagram below summarizes the containment rules for flow elements. The arrows represent the possible parent/child relationships. + +![Diagram: Flow content containment schema](./media/flow-content-schema.png "Flow_Content_Schema") + +As can be seen from the diagram above, the children allowed for an element are not necessarily determined by whether it is a element or an element. For example, a (an element) can only have child elements while a (also an element) can only have child elements. Therefore, a diagram is useful for quickly determining what element can be contained in another. As an example, let's use the diagram to determine how to construct the flow content of a . + +**1.** A must contain a which in turn must contain a -derived object. Below is the corresponding segment from the diagram above. + +![Diagram: RichTextBox containment rules](./media/flow-ovw-schemawalkthrough1.png "Flow_Ovw_SchemaWalkThrough1") + +Thus far, this is what the markup might look like. + +[!code-xaml[FlowOvwSnippets_snip#SchemaWalkThrough1](~/samples/snippets/csharp/VS_Snippets_Wpf/FlowOvwSnippets_snip/CS/MiscSnippets.xaml#schemawalkthrough1)] + +**2.** According to the diagram, there are several elements to choose from including , , , , and (see Block-derived classes above). Let's say we want a . According to the diagram above, a contains a containing elements, which contain elements which contain a -derived object. Below is the corresponding segment for taken from the diagram above. + +![Diagram: Parent/child schema for Table](./media/flow-ovw-schemawalkthrough2.png "Flow_Ovw_SchemaWalkThrough2") + +Below is the corresponding markup. + +[!code-xaml[FlowOvwSnippets_snip#SchemaWalkThrough2](~/samples/snippets/csharp/VS_Snippets_Wpf/FlowOvwSnippets_snip/CS/MiscSnippets.xaml#schemawalkthrough2)] + +**3.** Again, one or more elements are required underneath a . To make it simple, let's place some text inside the cell. We can do this using a with a element. Below is the corresponding segments from the diagram showing that a can take an element and that a (an element) can only take plain text. + +![Diagram: Parent/child schema for Paragraph](./media/flow-ovw-schemawalkthrough3.png "Flow_Ovw_SchemaWalkThrough3") + +![Diagram: Parent/Child schema for Run](./media/flow-ovw-schemawalkthrough4.png "Flow_Ovw_SchemaWalkThrough4") + +Below is the entire example in markup. + +[!code-xaml[FlowOvwSnippets_snip#SchemaExampleWholePage](~/samples/snippets/csharp/VS_Snippets_Wpf/FlowOvwSnippets_snip/CS/SchemaExample.xaml#schemaexamplewholepage)] + + + +## Customizing Text + +Usually text is the most prevalent type of content in a flow document. Although the objects introduced above can be used to control most aspects of how text is rendered, there are some other methods for customizing text that is covered in this section. + +### Text Decorations + +Text decorations allow you to apply the underline, overline, baseline, and strikethrough effects to text (see pictures below). These decorations are added using the property that is exposed by a number of objects including , , , and . + +The following example shows how to set the property of a . + +[!code-xaml[InlineSnippets#_Paragraph_TextDecXAML](~/samples/snippets/csharp/VS_Snippets_Wpf/InlineSnippets/CSharp/Window1.xaml#_paragraph_textdecxaml)] + +[!code-csharp[InlineSnippets#_Paragraph_TextDec](~/samples/snippets/csharp/VS_Snippets_Wpf/InlineSnippets/CSharp/Window1.xaml.cs#_paragraph_textdec)] +[!code-vb[InlineSnippets#_Paragraph_TextDec](~/samples/snippets/visualbasic/VS_Snippets_Wpf/InlineSnippets/visualbasic/window1.xaml.vb#_paragraph_textdec)] + +The following figure shows how this example renders. + +![Screenshot: Text with default strikethrough effect](./media/inline-textdec-strike.png "Inline_TextDec_Strike") + +The following figures show how the **Overline**, **Baseline**, and **Underline** decorations render, respectively. + +![Screenshot: Overline TextDecorator](./media/inline-textdec-over.png "Inline_TextDec_Over") + +![Screenshot: Default baseline effect on text](./media/inline-textdec-base.png "Inline_TextDec_Base") + +![Screenshot: Text with default underline effect](./media/inline-textdec-under.png "Inline_TextDec_Under") + +### Typography + +The property is exposed by most flow-related content including , , , and . This property is used to control typographical characteristics/variations of text (i.e. small or large caps, making superscripts and subscripts, etc). + +The following example shows how to set the attribute, using as the example element. + +[!code-xaml[TextElementSnippets#_TextElement_TypogXAML](~/samples/snippets/csharp/VS_Snippets_Wpf/TextElementSnippets/CSharp/Window1.xaml#_textelement_typogxaml)] + +The following figure shows how this example renders. + +![Screenshot: Text with altered typography](./media/textelement-typog.png "TextElement_Typog") + +In contrast, the following figure shows how a similar example with default typographic properties renders. + +![Screenshot: Text with altered typography](./media/textelement-typog-default.png "TextElement_Typog_Default") + +The following example shows how to set the property programmatically. + +[!code-csharp[TextElementSnippets#_TextElement_Typog](~/samples/snippets/csharp/VS_Snippets_Wpf/TextElementSnippets/CSharp/Window1.xaml.cs#_textelement_typog)] +[!code-vb[TextElementSnippets#_TextElement_Typog](~/samples/snippets/visualbasic/VS_Snippets_Wpf/TextElementSnippets/visualbasic/window1.xaml.vb#_textelement_typog)] + +See [Typography in WPF](typography-in-wpf.md) for more information on typography. + +## See also + +- [Text](optimizing-performance-text.md) +- [Typography in WPF](typography-in-wpf.md) +- [How-to Topics](flow-content-elements-how-to-topics.md) +- [TextElement Content Model Overview](textelement-content-model-overview.md) +- [RichTextBox Overview](../controls/richtextbox-overview.md) +- [Documents in WPF](documents-in-wpf.md) +- [Table Overview](table-overview.md) +- [Annotations Overview](annotations-overview.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/focus-overview.md b/dotnet-desktop-guide/framework/wpf/advanced/focus-overview.md new file mode 100644 index 0000000000..475aca7eda --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/focus-overview.md @@ -0,0 +1,119 @@ +--- +title: "Focus Overview" +description: "Learn about the two main concepts in Windows Presentation Foundation that pertain to focus: keyboard focus and logical focus." +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "applications [WPF], focus" + - "focus in applications [WPF]" +ms.assetid: 0230c4eb-0c8a-462b-ac4b-ae3e511659f4 +--- +# Focus Overview +In [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] there are two main concepts that pertain to focus: keyboard focus and logical focus. Keyboard focus refers to the element that receives keyboard input and logical focus refers to the element in a focus scope that has focus. These concepts are discussed in detail in this overview. Understanding the difference in these concepts is important for creating complex applications that have multiple regions where focus can be obtained. + + The major classes that participate in focus management are the class, the class, and the base element classes, such as and . For more information about the base elements, see the [Base Elements Overview](base-elements-overview.md). + + The class is concerned primarily with keyboard focus and the is concerned primarily with logical focus, but this is not an absolute distinction. An element that has keyboard focus will also have logical focus, but an element that has logical focus does not necessarily have keyboard focus. This is apparent when you use the class to set the element that has keyboard focus, for it also sets logical focus on the element. + + +## Keyboard Focus + Keyboard focus refers to the element that is currently receiving keyboard input. There can be only one element on the whole desktop that has keyboard focus. In [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)], the element that has keyboard focus will have set to `true`. The static property on the class gets the element that currently has keyboard focus. + + In order for an element to obtain keyboard focus, the and the properties on the base elements must be set to `true`. Some classes, such as the base class, have set to `false` by default; therefore, you must set to `true` if you want such an element to be able to obtain keyboard focus. + + Keyboard focus can be obtained through user interaction with the [!INCLUDE[TLA2#tla_ui](../../../includes/tla2sharptla-ui-md.md)], such as tabbing to an element or clicking the mouse on certain elements. Keyboard focus can also be obtained programmatically by using the method on the class. The method attempts to give the specified element keyboard focus. The returned element is the element that has keyboard focus, which might be a different element than requested if either the old or new focus object block the request. + + The following example uses the method to set keyboard focus on a . + + [!code-csharp[focussample#FocusSampleSetFocus](~/samples/snippets/csharp/VS_Snippets_Wpf/FocusSample/CSharp/Window1.xaml.cs#focussamplesetfocus)] + [!code-vb[focussample#FocusSampleSetFocus](~/samples/snippets/visualbasic/VS_Snippets_Wpf/FocusSample/visualbasic/window1.xaml.vb#focussamplesetfocus)] + + The property on the base element classes gets a value indicating whether the element has keyboard focus. The property on the base element classes gets a value indicating whether the element or any one of its visual child elements has keyboard focus. + + When setting initial focus at application startup, the element to receive focus must be in the visual tree of the initial window loaded by the application, and the element must have and set to `true`. The recommended place to set initial focus is in the event handler. A callback can also be used by calling or . + + +## Logical Focus + Logical focus refers to the in a focus scope. A focus scope is an element that keeps track of the within its scope. When keyboard focus leaves a focus scope, the focused element will lose keyboard focus but will retain logical focus. When keyboard focus returns to the focus scope, the focused element will obtain keyboard focus. This allows for keyboard focus to be changed between multiple focus scopes but ensures that the focused element in the focus scope regains keyboard focus when focus returns to the focus scope. + + There can be multiple elements that have logical focus in an application, but there may only be one element that has logical focus in a particular focus scope. + + An element that has keyboard focus has logical focus for the focus scope it belongs to. + + An element can be turned into a focus scope in [!INCLUDE[TLA#tla_xaml](../../../includes/tlasharptla-xaml-md.md)] by setting the attached property to `true`. In code, an element can be turned into a focus scope by calling . + + The following example makes a into a focus scope by setting the attached property. + + [!code-xaml[MarkupSnippets#MarkupIsFocusScopeXAML](~/samples/snippets/csharp/VS_Snippets_Wpf/MarkupSnippets/CSharp/Window1.xaml#markupisfocusscopexaml)] + + [!code-csharp[FocusSnippets#FocusSetIsFocusScope](~/samples/snippets/csharp/VS_Snippets_Wpf/FocusSnippets/CSharp/Window1.xaml.cs#focussetisfocusscope)] + [!code-vb[FocusSnippets#FocusSetIsFocusScope](~/samples/snippets/visualbasic/VS_Snippets_Wpf/FocusSnippets/visualbasic/window1.xaml.vb#focussetisfocusscope)] + + returns the focus scope for the specified element. + + Classes in [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] which are focus scopes by default are , , , and . + + gets the focused element for the specified focus scope. sets the focused element in the specified focus scope. is typically used to set the initial focused element. + + The following example sets the focused element on a focus scope and gets the focused element of a focus scope. + + [!code-csharp[FocusSnippets#FocusGetSetFocusedElement](~/samples/snippets/csharp/VS_Snippets_Wpf/FocusSnippets/CSharp/Window1.xaml.cs#focusgetsetfocusedelement)] + [!code-vb[FocusSnippets#FocusGetSetFocusedElement](~/samples/snippets/visualbasic/VS_Snippets_Wpf/FocusSnippets/visualbasic/window1.xaml.vb#focusgetsetfocusedelement)] + + +## Keyboard Navigation + The class is responsible for implementing default keyboard focus navigation when one of the navigation keys is pressed. The navigation keys are: TAB, SHIFT+TAB, CTRL+TAB, CTRL+SHIFT+TAB, UPARROW, DOWNARROW, LEFTARROW, and RIGHTARROW keys. + + The navigation behavior of a navigation container can be changed by setting the attached properties , , and . These properties are of type and the possible values are , , , , , and . The default value is , which means the element is not a navigation container. + + The following example creates a with a number of objects. The attached property is set to on the . When focus is changed using the tab key within the , focus will move from each element and when the last element is reached focus will return to the first element. + + [!code-xaml[MarkupSnippets#MarkupKeyboardNavigationTabNavigationXAML](~/samples/snippets/csharp/VS_Snippets_Wpf/MarkupSnippets/CSharp/Window1.xaml#markupkeyboardnavigationtabnavigationxaml)] + + [!code-csharp[MarkupSnippets#MarkupKeyboardNavigationTabNavigationCODE](~/samples/snippets/csharp/VS_Snippets_Wpf/MarkupSnippets/CSharp/Window1.xaml.cs#markupkeyboardnavigationtabnavigationcode)] + [!code-vb[MarkupSnippets#MarkupKeyboardNavigationTabNavigationCODE](~/samples/snippets/visualbasic/VS_Snippets_Wpf/MarkupSnippets/visualbasic/window1.xaml.vb#markupkeyboardnavigationtabnavigationcode)] + + +## Navigating Focus Programmatically + Additional API to work with focus are and . + + changes focus to the next element in the application. A is used to specify the direction. The passed to specifies the different directions focus can be moved, such as , , and . + + The following example uses to change the focused element. + + [!code-csharp[focussample#FocusSampleMoveFocus](~/samples/snippets/csharp/VS_Snippets_Wpf/FocusSample/CSharp/Window1.xaml.cs#focussamplemovefocus)] + [!code-vb[focussample#FocusSampleMoveFocus](~/samples/snippets/visualbasic/VS_Snippets_Wpf/FocusSample/visualbasic/window1.xaml.vb#focussamplemovefocus)] + + returns the object which would receive focus if focus were to be changed. Currently, only , , , and are supported by . + + +## Focus Events + The events related to keyboard focus are , and , . The events are defined as attached events on the class, but are more readily accessible as equivalent routed events on the base element classes. For more information about events, see the [Routed Events Overview](routed-events-overview.md). + + is raised when the element obtains keyboard focus. is raised when the element loses keyboard focus. If the event or the event is handled and is set to `true`, then focus will not change. + + The following example attaches and event handlers to a . + + [!code-xaml[keyboardsample#KeyboardSampleXAMLHandlerHookup](~/samples/snippets/csharp/VS_Snippets_Wpf/KeyboardSample/CSharp/Window1.xaml#keyboardsamplexamlhandlerhookup)] + + When the obtains keyboard focus, the property of the is changed to . + + [!code-csharp[keyboardsample#KeyboardSampleGotFocus](~/samples/snippets/csharp/VS_Snippets_Wpf/KeyboardSample/CSharp/Window1.xaml.cs#keyboardsamplegotfocus)] + [!code-vb[keyboardsample#KeyboardSampleGotFocus](~/samples/snippets/visualbasic/VS_Snippets_Wpf/KeyboardSample/visualbasic/window1.xaml.vb#keyboardsamplegotfocus)] + + When the loses keyboard focus, the property of the is changed back to white. + + [!code-csharp[keyboardsample#KeyboardSampleLostFocus](~/samples/snippets/csharp/VS_Snippets_Wpf/KeyboardSample/CSharp/Window1.xaml.cs#keyboardsamplelostfocus)] + [!code-vb[keyboardsample#KeyboardSampleLostFocus](~/samples/snippets/visualbasic/VS_Snippets_Wpf/KeyboardSample/visualbasic/window1.xaml.vb#keyboardsamplelostfocus)] + + The events related to logical focus are and . These events are defined on the as attached events, but the does not expose CLR event wrappers. and expose these events more conveniently. + +## See also + +- +- +- +- [Input Overview](input-overview.md) +- [Base Elements Overview](base-elements-overview.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/fonts-how-to-topics.md b/dotnet-desktop-guide/framework/wpf/advanced/fonts-how-to-topics.md new file mode 100644 index 0000000000..f20ca25ff7 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/fonts-how-to-topics.md @@ -0,0 +1,22 @@ +--- +title: "Fonts How-to Topics" +ms.date: "03/30/2017" +f1_keywords: + - "AutoGeneratedOrientationPage" +helpviewer_keywords: + - "fonts [WPF]" +ms.assetid: b4a97c97-7f88-4a89-b1d1-cf2c0d087955 +--- +# Fonts How-to Topics +The topics in this section demonstrate how to use the font features included with [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)]. + +## In This Section + [Enumerate System Fonts](how-to-enumerate-system-fonts.md) + [Use the FontSizeConverter Class](how-to-use-the-fontsizeconverter-class.md) + +## See also + +- +- +- [Documents in WPF](documents-in-wpf.md) +- [Typography in WPF](typography-in-wpf.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/fonts-wpf.md b/dotnet-desktop-guide/framework/wpf/advanced/fonts-wpf.md new file mode 100644 index 0000000000..0951a6510a --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/fonts-wpf.md @@ -0,0 +1,24 @@ +--- +title: "Fonts" +ms.date: "03/30/2017" +f1_keywords: + - "AutoGeneratedOrientationPage" +helpviewer_keywords: + - "fonts [WPF]" +ms.assetid: 6c766a95-ad03-475e-a36f-2243e9495941 +--- +# Fonts (WPF) +[!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] includes support for rich presentation of text using OpenType fonts. A sample pack of OpenType fonts is included with the Windows SDK. + +## In This Section + [OpenType Font Features](opentype-font-features.md) + [Packaging Fonts with Applications](packaging-fonts-with-applications.md) + [Sample OpenType Font Pack](sample-opentype-font-pack.md) + [How-to Topics](fonts-how-to-topics.md) + +## See also + +- +- +- [Documents in WPF](documents-in-wpf.md) +- [Typography in WPF](typography-in-wpf.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/forwardtranslateaccelerator-function-wpf-unmanaged-api-reference.md b/dotnet-desktop-guide/framework/wpf/advanced/forwardtranslateaccelerator-function-wpf-unmanaged-api-reference.md new file mode 100644 index 0000000000..455caff33a --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/forwardtranslateaccelerator-function-wpf-unmanaged-api-reference.md @@ -0,0 +1,47 @@ +--- +title: "ForwardTranslateAccelerator Function - WPF unmanaged API reference" +titleSuffix: "" +ms.date: "03/30/2017" +dev_langs: + - "cpp" +api_name: + - "ForwardTranslateAccelerator" +api_location: + - "PresentationHost_v0400.dll" +ms.assetid: fff47a86-9d9f-4176-9530-10e1876e393f +--- +# ForwardTranslateAccelerator Function (WPF Unmanaged API Reference) +This API supports the Windows Presentation Foundation (WPF) infrastructure and is not intended to be used directly from your code. + + Used by the Windows Presentation Foundation (WPF) infrastructure for windows management. + +## Syntax + +```cpp +HRESULT ForwardTranslateAccelerator( + MSG* pMsg, + VARIANT_BOOL appUnhandled +) +``` + +## Parameters + pMsg + A pointer to a message. + + appUnhandled + `true` when the app has already been given a chance to handle the input message, but has not handled it; otherwise, `false`. + +## Requirements + **Platforms:** See [.NET Framework System Requirements](/dotnet/framework/get-started/system-requirements). + + **DLL:** + + In the .NET Framework 3.0 and 3.5: PresentationHostDLL.dll + + In the .NET Framework 4 and later: PresentationHost_v0400.dll + + **.NET Framework Version:** [!INCLUDE[net_current_v30plus](../../../includes/net-current-v30plus-md.md)] + +## See also + +- [WPF Unmanaged API Reference](wpf-unmanaged-api-reference.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/framework-property-metadata.md b/dotnet-desktop-guide/framework/wpf/advanced/framework-property-metadata.md new file mode 100644 index 0000000000..ed674864f0 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/framework-property-metadata.md @@ -0,0 +1,72 @@ +--- +title: "Framework Property Metadata" +ms.date: "03/30/2017" +helpviewer_keywords: + - "metadata [WPF], framework properties" + - "framework property metadata [WPF]" +ms.assetid: 9962f380-b885-4b61-a62e-457397083fea +--- +# Framework Property Metadata +Framework property metadata options are reported for the properties of object elements considered to be at the WPF framework level in the [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] architecture. In general the WPF framework-level designation entails that features such as rendering, data binding, and property system refinements are handled by the [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] presentation APIs and executables. Framework property metadata is queried by these systems to determine feature-specific characteristics of particular element properties. + + +## Prerequisites + This topic assumes that you understand dependency properties from the perspective of a consumer of existing dependency properties on [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] classes, and have read the [Dependency Properties Overview](dependency-properties-overview.md). You should also have read [Dependency Property Metadata](dependency-property-metadata.md). + + +## What Is Communicated by Framework Property Metadata + Framework property metadata can be divided into the following categories: + +- Reporting layout properties that affect an element (, , ). You might set these flags in metadata if the property affects those respective aspects, and you are also implementing the / methods in your class to supply specific rendering behavior and information to the layout system. Typically, such an implementation would check for property invalidations in dependency properties where any of these layout properties were true in the property metadata, and only those invalidations would necessitate requesting a new layout pass. + +- Reporting layout properties that affect the parent element of an element (, ). Some examples where these flags are set by default are and . + +- . By default, dependency properties do not inherit values. allows the pathway of inheritance to also travel into a visual tree, which is necessary for some control compositing scenarios. + + > [!NOTE] + > The term "inherits" in the context of property values means something specific for dependency properties; it means that child elements can inherit the actual dependency property value from parent elements because of a WPF framework-level capability of the [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] property system. It has nothing to do directly with managed code type and members inheritance through derived types. For details, see [Property Value Inheritance](property-value-inheritance.md). + +- Reporting data binding characteristics (, ). By default, dependency properties in the framework support data binding, with a one-way binding behavior. You might disable data binding if there were no scenario for it whatsoever (because they are intended to be flexible and extensible, there aren't many examples of such properties in the default [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] APIs). You might set binding to have a two-way default for properties that tie together a control's behaviors amongst its component pieces ( is an example) or where two-way binding is the common and expected scenario for users ( is an example). Changing the data binding–related metadata only influences the default; on a per-binding basis that default can always be changed. For details on the binding modes and binding in general, see [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview). + +- Reporting whether properties should be journaled by applications or services that support journaling (). For general elements, journaling is not enabled by default, but it is selectively enabled for certain user input controls. This property is intended to be read by journaling services including the [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] implementation of journaling, and is typically set on user controls such as user selections within lists that should be persisted across navigation steps. For information about the journal, see [Navigation Overview](../app-development/navigation-overview.md). + + +## Reading FrameworkPropertyMetadata + Each of the properties linked above are the specific properties that the adds to its immediate base class . Each of these properties will be `false` by default. A metadata request for a property where knowing the value of these properties is important should attempt to cast the returned metadata to , and then check the values of the individual properties as needed. + + +## Specifying Metadata + When you create a new metadata instance for purposes of applying metadata to a new dependency property registration, you have the choice of which metadata class to use: the base or some derived class such as . In general, you should use , particularly if your property has any interaction with property system and [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] functions such as layout and data binding. Another option for more sophisticated scenarios is to derive from to create your own metadata reporting class with extra information carried in its members. Or you might use or to communicate the degree of support for features of your implementation. + + For existing properties ( or call), you should always override with the metadata type used by the original registration. + + If you are creating a instance, there are two ways to populate that metadata with values for the specific properties that communicate the framework property characteristics: + +1. Use the constructor signature that allows a `flags` parameter. This parameter should be filled with all desired combined values of the enumeration flags. + +2. Use one of the signatures without a `flags` parameter, and then set each reporting Boolean property on to `true` for each desired characteristic change. If you do this, you must set these properties before any elements with this dependency property are constructed; the Boolean properties are read-write in order to allow this behavior of avoiding the `flags` parameter and still populate the metadata, but the metadata must become effectively sealed before property use. Thus, attempting to set the properties after metadata is requested will be an invalid operation. + + +## Framework Property Metadata Merge Behavior + When you override framework property metadata, the different metadata characteristics are either merged or replaced. + +- is merged. If you add a new , that callback is stored in the metadata. If you do not specify a in the override, the value of is promoted as a reference from the nearest ancestor that specified it in metadata. + +- The actual property system behavior for is that implementations for all metadata owners in the hierarchy are retained and added to a table, with order of execution by the property system being that the callbacks of the most deeply derived class are invoked first. Inherited callbacks run only once, counting as being owned by the class that placed them in metadata. + +- is replaced. If you do not specify a in the override, the value of comes from the nearest ancestor that specified it in metadata. + +- implementations are replaced. If you add a new , that callback is stored in the metadata. If you do not specify a in the override, the value of is promoted as a reference from the nearest ancestor that specified it in metadata. + +- The property system behavior is that only the in the immediate metadata is invoked. No references to other implementations in the hierarchy are retained. + +- The flags of enumeration are combined as a bitwise OR operation. If you specify , the original options are not overwritten. To change an option, set the corresponding property on . For example, if the original object sets the flag, you can change that by setting to `false`. + + This behavior is implemented by , and can be overridden on derived metadata classes. + +## See also + +- +- [Dependency Property Metadata](dependency-property-metadata.md) +- [Dependency Properties Overview](dependency-properties-overview.md) +- [Custom Dependency Properties](custom-dependency-properties.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/freezable-objects-overview.md b/dotnet-desktop-guide/framework/wpf/advanced/freezable-objects-overview.md new file mode 100644 index 0000000000..d11e37b744 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/freezable-objects-overview.md @@ -0,0 +1,174 @@ +--- +title: "Freezable Objects Overview" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "Freezable objects [WPF], description" + - "unfreezing Freezable objects [WPF]" + - "classes [WPF], Freezable" +ms.assetid: 89c71692-4f43-4057-b611-67c6a8a863a2 +--- +# Freezable Objects Overview + +This topic describes how to effectively use and create objects, which provide special features that can help improve application performance. Examples of freezable objects include brushes, pens, transformations, geometries, and animations. + + + +## What Is a Freezable? + +A is a special type of object that has two states: unfrozen and frozen. When unfrozen, a appears to behave like any other object. When frozen, a can no longer be modified. + +A provides a event to notify observers of any modifications to the object. Freezing a can improve its performance, because it no longer needs to spend resources on change notifications. A frozen can also be shared across threads, while an unfrozen cannot. + +Although the class has many applications, most objects in [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] are related to the graphics sub-system. + +The class makes it easier to use certain graphics system objects and can help improve application performance. Examples of types that inherit from include the , , and classes. Because they contain unmanaged resources, the system must monitor these objects for modifications, and then update their corresponding unmanaged resources when there is a change to the original object. Even if you don't actually modify a graphics system object, the system must still spend some of its resources monitoring the object, in case you do change it. + +For example, suppose you create a brush and use it to paint the background of a button. + +[!code-csharp[freezablesample_procedural#FrozenExamplePart1](~/samples/snippets/csharp/VS_Snippets_Wpf/freezablesample_procedural/CSharp/freezablesample.cs#frozenexamplepart1)] +[!code-vb[freezablesample_procedural#FrozenExamplePart1](~/samples/snippets/visualbasic/VS_Snippets_Wpf/freezablesample_procedural/visualbasic/freezablesample.vb#frozenexamplepart1)] + +When the button is rendered, the [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] graphics sub-system uses the information you provided to paint a group of pixels to create the appearance of a button. Although you used a solid color brush to describe how the button should be painted, your solid color brush doesn't actually do the painting. The graphics system generates fast, low-level objects for the button and the brush, and it is those objects that actually appear on the screen. + +If you were to modify the brush, those low-level objects would have to be regenerated. The freezable class is what gives a brush the ability to find its corresponding generated, low-level objects and to update them when it changes. When this ability is enabled, the brush is said to be "unfrozen." + +A freezable's method enables you to disable this self-updating ability. You can use this method to make the brush become "frozen," or unmodifiable. + +> [!NOTE] +> Not every Freezable object can be frozen. To avoid throwing an , check the value of the Freezable object's property to determine whether it can be frozen before attempting to freeze it. + +[!code-csharp[freezablesample_procedural#FrozenExamplePart2](~/samples/snippets/csharp/VS_Snippets_Wpf/freezablesample_procedural/CSharp/freezablesample.cs#frozenexamplepart2)] +[!code-vb[freezablesample_procedural#FrozenExamplePart2](~/samples/snippets/visualbasic/VS_Snippets_Wpf/freezablesample_procedural/visualbasic/freezablesample.vb#frozenexamplepart2)] + +When you no longer need to modify a freezable, freezing it provides performance benefits. If you were to freeze the brush in this example, the graphics system would no longer need to monitor it for changes. The graphics system can also make other optimizations, because it knows the brush won't change. + +> [!NOTE] +> For convenience, freezable objects remain unfrozen unless you explicitly freeze them. + + + +## Using Freezables + +Using an unfrozen freezable is like using any other type of object. In the following example, the color of a is changed from yellow to red after it's used to paint the background of a button. The graphics system works behind the scenes to automatically change the button from yellow to red the next time the screen is refreshed. + +[!code-csharp[freezablesample_procedural#UnFrozenExampleShort](~/samples/snippets/csharp/VS_Snippets_Wpf/freezablesample_procedural/CSharp/freezablesample.cs#unfrozenexampleshort)] +[!code-vb[freezablesample_procedural#UnFrozenExampleShort](~/samples/snippets/visualbasic/VS_Snippets_Wpf/freezablesample_procedural/visualbasic/freezablesample.vb#unfrozenexampleshort)] + +### Freezing a Freezable + +To make a unmodifiable, you call its method. When you freeze an object that contains freezable objects, those objects are frozen as well. For example, if you freeze a , the figures and segments it contains would be frozen too. + +A Freezable **can't** be frozen if any of the following are true: + +- It has animated or data bound properties. + +- It has properties set by a dynamic resource. (See the [XAML Resources](/dotnet/desktop-wpf/fundamentals/xaml-resources-define) for more information about dynamic resources.) + +- It contains sub-objects that can't be frozen. + +If these conditions are false, and you don't intend to modify the , then you should freeze it to gain the performance benefits described earlier. + +Once you call a freezable's method, it can no longer be modified. Attempting to modify a frozen object causes an to be thrown. The following code throws an exception, because we attempt to modify the brush after it's been frozen. + +[!code-csharp[freezablesample_procedural#ExceptionExample](~/samples/snippets/csharp/VS_Snippets_Wpf/freezablesample_procedural/CSharp/freezablesample.cs#exceptionexample)] +[!code-vb[freezablesample_procedural#ExceptionExample](~/samples/snippets/visualbasic/VS_Snippets_Wpf/freezablesample_procedural/visualbasic/freezablesample.vb#exceptionexample)] + +To avoid throwing this exception, you can use the method to determine whether a is frozen. + +[!code-csharp[freezablesample_procedural#CheckIsFrozenExample](~/samples/snippets/csharp/VS_Snippets_Wpf/freezablesample_procedural/CSharp/freezablesample.cs#checkisfrozenexample)] +[!code-vb[freezablesample_procedural#CheckIsFrozenExample](~/samples/snippets/visualbasic/VS_Snippets_Wpf/freezablesample_procedural/visualbasic/freezablesample.vb#checkisfrozenexample)] + +In the preceding code example, a modifiable copy was made of a frozen object using the method. The next section discusses cloning in more detail. + +> [!NOTE] +> Because a frozen freezable cannot be animated, the animation system will automatically create modifiable clones of frozen objects when you try to animate them with a . To eliminate the performance overhead caused by cloning, leave an object unfrozen if you intend to animate it. For more information about animating with storyboards, see the [Storyboards Overview](../graphics-multimedia/storyboards-overview.md). + +### Freezing from Markup + +To freeze a object declared in markup, you use the `PresentationOptions:Freeze` attribute. In the following example, a is declared as a page resource and frozen. It is then used to set the background of a button. + +[!code-xaml[FreezableSample#FreezeFromMarkupWholePage](~/samples/snippets/csharp/VS_Snippets_Wpf/FreezableSample/CS/FreezeFromMarkupExample.xaml#freezefrommarkupwholepage)] + +To use the `Freeze` attribute, you must map to the presentation options namespace: `http://schemas.microsoft.com/winfx/2006/xaml/presentation/options`. `PresentationOptions` is the recommended prefix for mapping this namespace: + +```xaml +xmlns:PresentationOptions="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options" +``` + +Because not all XAML readers recognize this attribute, it's recommended that you use the [mc:Ignorable Attribute](mc-ignorable-attribute.md) to mark the `Presentation:Freeze` attribute as ignorable: + +```xaml +xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" +mc:Ignorable="PresentationOptions" +``` + +For more information, see the [mc:Ignorable Attribute](mc-ignorable-attribute.md) page. + +### "Unfreezing" a Freezable + +Once frozen, a can never be modified or unfrozen; however, you can create an unfrozen clone using the or method. + +In the following example, the button's background is set with a brush and that brush is then frozen. An unfrozen copy is made of the brush using the method. The clone is modified and used to change the button's background from yellow to red. + +[!code-csharp[freezablesample_procedural#CloneExample](~/samples/snippets/csharp/VS_Snippets_Wpf/freezablesample_procedural/CSharp/freezablesample.cs#cloneexample)] +[!code-vb[freezablesample_procedural#CloneExample](~/samples/snippets/visualbasic/VS_Snippets_Wpf/freezablesample_procedural/visualbasic/freezablesample.vb#cloneexample)] + +> [!NOTE] +> Regardless of which clone method you use, animations are never copied to the new . + +The and methods produce deep copies of the freezable. If the freezable contains other frozen freezable objects, they are also cloned and made modifiable. For example, if you clone a frozen to make it modifiable, the figures and segments it contains are also copied and made modifiable. + + + +## Creating Your Own Freezable Class + +A class that derives from gains the following features. + +- Special states: a read-only (frozen) and a writable state. + +- Thread safety: a frozen can be shared across threads. + +- Detailed change notification: Unlike other s, Freezable objects provide change notifications when sub-property values change. + +- Easy cloning: the Freezable class has already implemented several methods that produce deep clones. + +A is a type of , and therefore uses the dependency property system. Your class properties don't have to be dependency properties, but using dependency properties will reduce the amount of code you have to write, because the class was designed with dependency properties in mind. For more information about the dependency property system, see the [Dependency Properties Overview](dependency-properties-overview.md). + +Every subclass must override the method. If your class uses dependency properties for all its data, you're finished. + +If your class contains non-dependency property data members, you must also override the following methods: + +- + +- + +- + +- + +- + +You must also observe the following rules for accessing and writing to data members that are not dependency properties: + +- At the beginning of any API that reads non-dependency property data members, call the method. + +- At the beginning of any API that writes non-dependency property data members, call the method. (Once you've called in an API, you don't need to make an additional call to if you also read non-dependency property data members.) + +- Call the method before exiting methods that write to non-dependency property data members. + +If your class contains non-dependency-property data members that are objects, you must also call the method each time you change one of their values, even if you're setting the member to `null`. + +> [!NOTE] +> It's very important that you begin each method you override with a call to the base implementation. + +For an example of a custom class, see the [Custom Animation Sample](https://github.com/Microsoft/WPF-Samples/tree/master/Animation/CustomAnimation). + +## See also + +- +- [Custom Animation Sample](https://github.com/Microsoft/WPF-Samples/tree/master/Animation/CustomAnimation) +- [Dependency Properties Overview](dependency-properties-overview.md) +- [Custom Dependency Properties](custom-dependency-properties.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/getting-started-with-ink.md b/dotnet-desktop-guide/framework/wpf/advanced/getting-started-with-ink.md new file mode 100644 index 0000000000..32963183e0 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/getting-started-with-ink.md @@ -0,0 +1,110 @@ +--- +title: Create InkCanvas in Visual Studio +ms.date: 08/15/2018 +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "procedural code in lieu of XAML [WPF]" + - "XAML [WPF], procedural code in lieu of" + - "InkCanvas (WPF)" +ms.assetid: 760332dd-594a-475d-865b-01659db8cab7 +--- +# Get Started with Ink in WPF + +Windows Presentation Foundation (WPF) has an ink feature that makes it easy to incorporate digital ink into your app. + +## Prerequisites + +To use the following examples, first install [Visual Studio](https://visualstudio.microsoft.com/downloads/?utm_medium=microsoft&utm_source=docs.microsoft.com&utm_campaign=inline+link&utm_content=download+vs2019). It also helps to know how to write basic WPF apps. For help getting started with WPF, see [Walkthrough: My first WPF desktop application](../getting-started/walkthrough-my-first-wpf-desktop-application.md). + +## Quick Start + +This section helps you write a simple WPF application that collects ink. + +### Got Ink? + +To create a WPF app that supports ink: + +1. Open Visual Studio. + +2. Create a new **WPF App**. + + In the **New Project** dialog, expand the **Installed** > **Visual C#** or **Visual Basic** > **Windows Desktop** category. Then, select the **WPF App (.NET Framework)** app template. Enter a name, and then select **OK**. + + Visual Studio creates the project, and *MainWindow.xaml* opens in the designer. + +3. Type `` between the `` tags. + + ![XAML designer with InkCanvas tag](./media/getting-started-with-ink/inkcanvas-xaml.png) + +4. Press **F5** to launch your application in the debugger. + +5. Using a stylus or mouse, write **hello world** in the window. + +You've written the ink equivalent of a "hello world" application with only 12 keystrokes! + +### Spice Up Your App + +Let’s take advantage of some features of the WPF. Replace everything between the opening and closing \ tags with the following markup: + +```xaml + + + + + + + + + + + +``` + +This XAML creates a gradient brush background on your inking surface. + +![Gradient colors on inking surface in WPF app](./media/getting-started-with-ink/gradient-colors.png) + +### Add Some Code Behind the XAML + +While XAML makes it very easy to design the user interface, any real-world application needs to add code to handle events. Here is a simple example that zooms in on the ink in response to a right-click from a mouse. + +1. Set the `MouseRightButtonUp` handler in your XAML: + + [!code-xaml[DigitalInkTopics#3](~/samples/snippets/csharp/VS_Snippets_Wpf/DigitalInkTopics/CSharp/Window2.xaml#3)] + +1. In **Solution Explorer**, expand MainWindow.xaml and open the code-behind file (MainWindow.xaml.cs or MainWindow.xaml.vb). Add the following event handler code: + + [!code-csharp[DigitalInkTopics#4](~/samples/snippets/csharp/VS_Snippets_Wpf/DigitalInkTopics/CSharp/Window2.xaml.cs#4)] + [!code-vb[DigitalInkTopics#4](~/samples/snippets/visualbasic/VS_Snippets_Wpf/DigitalInkTopics/VisualBasic/Window2.xaml.vb#4)] + +1. Run the application. Add some ink, and then right-click with the mouse or perform a press-and-hold equivalent with a stylus. + + The display zooms in each time you click with the right mouse button. + +### Use Procedural Code Instead of XAML + +You can access all WPF features from procedural code. Follow these steps to create a "Hello Ink World" application for WPF that doesn’t use any XAML at all. + +1. Create a new console application project in Visual Studio. + + In the **New Project** dialog, expand the **Installed** > **Visual C#** or **Visual Basic** > **Windows Desktop** category. Then, select the **Console App (.NET Framework)** app template. Enter a name, and then select **OK**. + +1. Paste the following code into the Program.cs or Program.vb file: + + [!code-csharp[InkCanvasConsoleApp#1](~/samples/snippets/csharp/VS_Snippets_Wpf/InkCanvasConsoleApp/CSharp/Program.cs#1)] + [!code-vb[InkCanvasConsoleApp#1](~/samples/snippets/visualbasic/VS_Snippets_Wpf/InkCanvasConsoleApp/VisualBasic/Module1.vb#1)] + +1. Add references to the PresentationCore, PresentationFramework, and WindowsBase assemblies by right-clicking on **References** in **Solution Explorer** and choosing **Add Reference**. + + ![Reference Manager showing PresentationCore and PresentationFramework](./media/getting-started-with-ink/reference-manager-presentationcore-presentationframework.png) + +1. Build the application by pressing **F5**. + +## See also + +- [Digital Ink](digital-ink.md) +- [Collecting Ink](collecting-ink.md) +- [Handwriting Recognition](handwriting-recognition.md) +- [Storing Ink](storing-ink.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/globalization-and-localization.md b/dotnet-desktop-guide/framework/wpf/advanced/globalization-and-localization.md new file mode 100644 index 0000000000..265cf5d129 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/globalization-and-localization.md @@ -0,0 +1,35 @@ +--- +title: "Globalization and Localization" +ms.date: "03/30/2017" +f1_keywords: + - "AutoGeneratedOrientationPage" +helpviewer_keywords: + - "WPF [WPF], globalization" + - "Windows Presentation Foundation [WPF], globalization" + - "globalization [WPF]" + - "localization [WPF]" + - "WPF [WPF], localization" + - "Windows Presentation Foundation [WPF], localization" +ms.assetid: e96f9764-4e3f-4d1c-bf20-3fb890118aae +--- +# Globalization and Localization +[!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] provides extensive support for the development of world-ready applications. + +## In This Section + [WPF Globalization and Localization Overview](wpf-globalization-and-localization-overview.md) + [Globalization for WPF](globalization-for-wpf.md) + [Use Automatic Layout Overview](use-automatic-layout-overview.md) + [Localization Attributes and Comments](localization-attributes-and-comments.md) + [Bidirectional Features in WPF Overview](bidirectional-features-in-wpf-overview.md) + [How-to Topics](how-to-localize-an-application.md) + +## Reference + + + + + + + [xml:lang Handling in XAML](/dotnet/desktop-wpf/xaml-services/xml-language-handling) + +## Related Sections diff --git a/dotnet-desktop-guide/framework/wpf/advanced/globalization-for-wpf.md b/dotnet-desktop-guide/framework/wpf/advanced/globalization-for-wpf.md new file mode 100644 index 0000000000..f0362d202b --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/globalization-for-wpf.md @@ -0,0 +1,177 @@ +--- +title: Globalization +ms.date: "03/30/2017" +helpviewer_keywords: + - "XAML [WPF], international user interface" + - "XAML [WPF], globalization" + - "international user interface [WPF], XAML" + - "globalization [WPF]" +ms.assetid: 4571ccfe-8a60-4f06-9b37-7ac0b1c2d10f +--- +# Globalization for WPF +This topic introduces issues that you should be aware of when writing [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] applications for the global market. The globalization programming elements are defined in .NET in the namespace. + + +## XAML Globalization + Extensible Application Markup Language (XAML) is based on XML and takes advantage of the globalization support defined in the XML specification. The following sections describe some [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] features that you should be aware of. + + +### Character References +A character reference gives the UTF16 code unit of the particular Unicode character it represents, in either decimal or hexadecimal. The following example shows a decimal character reference for the COPTIC CAPITAL LETTER HORI, or 'Ϩ': + +```xaml +Ϩ +``` + +The following example shows a hexadecimal character reference. Notice that it has an **x** in front of the hexadecimal number. + +```xaml +Ϩ +``` + + +### Encoding + The encoding supported by [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] are ASCII, Unicode UTF-16, and UTF-8. The encoding statement is at the beginning of [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] document. If no encoding attribute exists and there is no byte-order, the parser defaults to UTF-8. UTF-8 and UTF-16 are the preferred encodings. UTF-7 is not supported. The following example demonstrates how to specify a UTF-8 encoding in a [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] file. + +```xaml +?xml encoding="UTF-8"? +``` + + +### Language Attribute + [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] uses [xml:lang](/dotnet/desktop-wpf/xaml-services/xml-language-handling) to represent the language attribute of an element. To take advantage of the class, the language attribute value needs to be one of the culture names predefined by . [xml:lang](/dotnet/desktop-wpf/xaml-services/xml-language-handling) is inheritable in the element tree (by XML rules, not necessarily because of dependency property inheritance) and its default value is an empty string if it is not assigned explicitly. + + The language attribute is very useful for specifying dialects. For example, French has different spelling, vocabulary, and pronunciation in France, Quebec, Belgium, and Switzerland. Also Chinese, Japanese, and Korean share code points in Unicode, but the ideographic shapes are different and they use totally different fonts. + + The following [!INCLUDE[TLA#tla_xaml](../../../includes/tlasharptla-xaml-md.md)] example uses the `fr-CA` language attribute to specify Canadian French. + +```xaml +Découvrir la France +``` + + +### Unicode + [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] supports all Unicode features including surrogates. As long as the character set can be mapped to Unicode, it is supported. For example, GB18030 introduces some characters that are mapped to the Chinese, Japanese, and Korean (CFK) extension A and B and surrogate pairs, therefore it is fully supported. A [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] application can use to manipulate strings without understanding whether they have surrogate pairs or combining characters. + + +## Designing an International User Interface with XAML + This section describes [!INCLUDE[TLA#tla_ui](../../../includes/tlasharptla-ui-md.md)] features that you should consider when writing an application. + + +### International Text + [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] includes built-in processing for all Microsoft .NET Framework supported writing systems. + + The following scripts are currently supported: + +- Arabic + +- Bengali + +- Devanagari + +- Cyrillic + +- Greek + +- Gujarati + +- Gurmukhi + +- Hebrew + +- Ideographic scripts + +- Kannada + +- Lao + +- Latin + +- Malayalam + +- Mongolian + +- Odia + +- Syriac + +- Tamil + +- Telugu + +- Thaana + +- Thai* + +- Tibetan + + *In this release the display and editing of Thai text is supported; word breaking is not. + + The following scripts are not currently supported: + +- Khmer + +- Korean Old Hangul + +- Myanmar + +- Sinhala + + All the writing system engines support OpenType fonts. OpenType fonts can include the OpenType layout tables that enable font creators to design better international and high-end typographic fonts. The OpenType font layout tables contain information about glyph substitutions, glyph positioning, justification, and baseline positioning, enabling text-processing applications to improve text layout. + + OpenType fonts allow the handling of large glyph sets using Unicode encoding. Such encoding enables broad international support as well as for typographic glyph variants. + + [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] text rendering is powered by Microsoft ClearType sub-pixel technology that supports resolution independence. This significantly improves legibility and provides the ability to support high quality magazine style documents for all scripts. + + +### International Layout + [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] provides a very convenient way to support horizontal, bidirectional, and vertical layouts. In presentation framework the property can be used to define layout. The flow direction patterns are: + +- *LeftToRight* - horizontal layout for Latin, East Asian and so forth. + +- *RightToLeft* - bidirectional for Arabic, Hebrew and so forth. + + +## Developing Localizable Applications + When you write an application for global consumption you should keep in mind that the application must be localizable. The following topics point out things to consider. + + +### Multilingual User Interface + Multilingual User Interfaces (MUI) is a Microsoft support for switching UIs from one language to another. A [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] application uses the assembly model to support MUI. One application contains language-neutral assemblies as well as language-dependent satellite resource assemblies. The entry point is a managed .EXE in the main assembly. [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] resource loader takes advantage of the Framework's resource manager to support resource lookup and fallback. Multiple language satellite assemblies work with the same main assembly. The resource assembly that is loaded depends on the of the current thread. + + +### Localizable User Interface + [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] applications use [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] to define their [!INCLUDE[TLA2#tla_ui](../../../includes/tla2sharptla-ui-md.md)]. [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] allows developers to specify a hierarchy of objects with a set of properties and logic. The primary use of [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] is to develop [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] applications but it can be used to specify a hierarchy of any common language runtime (CLR) objects. Most developers use [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] to specify their application's [!INCLUDE[TLA2#tla_ui](../../../includes/tla2sharptla-ui-md.md)] and use a programming language such as C# to react to user interaction. + + From a resource point of view, a [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] file designed to describe a language-dependent [!INCLUDE[TLA2#tla_ui](../../../includes/tla2sharptla-ui-md.md)] is a resource element and therefore its final distribution format must be localizable to support international languages. Because [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] cannot handle events many [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] applications contain blocks of code to do this. For more information, see [XAML Overview (WPF)](/dotnet/desktop-wpf/fundamentals/xaml). Code is stripped out and compiled into different binaries when a [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] file is tokenized into the BAML form of XAML. The BAML form of XAML files, images, and other types of managed resource objects are embedded in the satellite resource assembly, which can be localized into other languages, or the main assembly when localization is not required. + +> [!NOTE] +> [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] applications support all the FrameworkCLR resources including string tables, images, and so forth. + + +### Building Localizable Applications + Localization means to adapt a [!INCLUDE[TLA2#tla_ui](../../../includes/tla2sharptla-ui-md.md)] to different cultures. To make a [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] application localizable, developers need to build all the localizable resources into a resource assembly. The resource assembly is localized into different languages, and the code-behind uses resource management API to load. One of the files required for a [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] application is a project file (.proj). All resources that you use in your application should be included in the project file. The following example from a .csproj file shows how to do this. + +```xml + + +``` + + To use a resource in your application instantiate a and load the resource you want to use. The following example demonstrates how to do this. + + [!code-csharp[LocalizationResources#2](~/samples/snippets/csharp/VS_Snippets_Wpf/LocalizationResources/CSharp/page1.xaml.cs#2)] + + +## Using ClickOnce with Localized Applications + ClickOnce is a new Windows Forms deployment technology that will ship with Visual Studio 2005. It enables application installation and upgrading of Web applications. When an application that was deployed with ClickOnce is localized it can only be viewed on the localized culture. For example, if a deployed application is localized to Japanese it can only be viewed on Japanese Microsoft Windows not on English Windows. This presents a problem because it is a common scenario for Japanese users to run an English version of Windows. + + The solution to this problem is setting the neutral language fallback attribute. An application developer can optionally remove resources from the main assembly and specify that the resources can be found in a satellite assembly corresponding to a specific culture. To control this process use the . The constructor of the class has two signatures, one that takes an parameter to specify the location where the should extract the fallback resources: main assembly or satellite assembly. The following example shows how to use the attribute. For the ultimate fallback location, the code causes the to look for the resources in the "de" subdirectory of the directory of the currently executing assembly. + +```csharp +[assembly: NeutralResourcesLanguageAttribute( + "de" , UltimateResourceFallbackLocation.Satellite)] +``` + +## See also + +- [WPF Globalization and Localization Overview](wpf-globalization-and-localization-overview.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/glyphs.md b/dotnet-desktop-guide/framework/wpf/advanced/glyphs.md new file mode 100644 index 0000000000..fd5568030d --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/glyphs.md @@ -0,0 +1,27 @@ +--- +title: "Glyphs" +ms.date: "03/30/2017" +f1_keywords: + - "AutoGeneratedOrientationPage" +helpviewer_keywords: + - "Glyphs elements [WPF]" + - "GlyphRun object [WPF]" + - "text [WPF], glyphs" + - "GlyphRunDrawing objects [WPF]" + - "glyphs [WPF]" +ms.assetid: d5d9274c-23b3-4859-8869-6e64403c9ca7 +--- +# Glyphs +Glyphs are a low-level depiction of a character to be drawn on-screen. [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] provides direct access to glyphs for customers who want to intercept and persist text after formatting. + +## In This Section + [Introduction to the GlyphRun Object and Glyphs Element](introduction-to-the-glyphrun-object-and-glyphs-element.md) + [How to: Draw Text Using Glyphs](draw-text-using-glyphs.md) + +## See also + +- +- +- +- [Documents in WPF](documents-in-wpf.md) +- [Typography in WPF](typography-in-wpf.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/graphics-rendering-tiers.md b/dotnet-desktop-guide/framework/wpf/advanced/graphics-rendering-tiers.md new file mode 100644 index 0000000000..a9e1d95ff4 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/graphics-rendering-tiers.md @@ -0,0 +1,131 @@ +--- +title: "Graphics Rendering Tiers" +ms.date: "03/30/2017" +helpviewer_keywords: + - "graphics [WPF], performance" + - "rendering graphics [WPF]" + - "rendering tiers [WPF]" + - "graphics rendering tiers [WPF]" + - "graphics [WPF], rendering tiers" +ms.assetid: 08dd1606-02a2-4122-9351-c0afd2ec3a70 +--- +# Graphics Rendering Tiers +A rendering tier defines a level of graphics hardware capability and performance for a device that runs a [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] application. + + +## Graphics Hardware + The features of the graphics hardware that most impact the rendering tier levels are: + +- **Video RAM** The amount of video memory on the graphics hardware determines the size and number of buffers that can be used for compositing graphics. + +- **Pixel Shader** A pixel shader is a graphics processing function that calculates effects on a per-pixel basis. Depending on the resolution of the displayed graphics, there could be several million pixels that need to be processed for each display frame. + +- **Vertex Shader** A vertex shader is a graphics processing function that performs mathematical operations on the vertex data of the object. + +- **Multitexture Support** Multitexture support refers to the ability to apply two or more distinct textures during a blending operation on a 3D graphics object. The degree of multitexture support is determined by the number of multitexture units on the graphics hardware. + + +## Rendering Tier Definitions + The features of the graphics hardware determine the rendering capability of a [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] application. The [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] system defines three rendering tiers: + +- **Rendering Tier 0** No graphics hardware acceleration. All graphics features use software acceleration. The DirectX version level is less than version 9.0. + +- **Rendering Tier 1** Some graphics features use graphics hardware acceleration. The DirectX version level is greater than or equal to version 9.0. + +- **Rendering Tier 2** Most graphics features use graphics hardware acceleration. The DirectX version level is greater than or equal to version 9.0. + + The property allows you to retrieve the rendering tier at application run time. You use the rendering tier to determine whether the device supports certain hardware-accelerated graphics features. Your application can then take different code paths at run time depending on the rendering tier supported by the device. + +### Rendering Tier 0 + A rendering tier value of 0 means that there is no graphics hardware acceleration available for the application on the device. At this tier level, you should assume that all graphics will be rendered by software with no hardware acceleration. This tier's functionality corresponds to a DirectX version that is less than 9.0. + +### Rendering Tier 1 and Rendering Tier 2 + +> [!NOTE] +> Starting in the .NET Framework 4, rendering tier 1 has been redefined to only include graphics hardware that supports DirectX 9.0 or greater. Graphics hardware that supports DirectX 7 or 8 is now defined as rendering tier 0. + + A rendering tier value of 1 or 2 means that most of the graphics features of [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] will use hardware acceleration if the necessary system resources are available and have not been exhausted. This corresponds to a DirectX version that is greater than or equal to 9.0. + + The following table shows the differences in graphics hardware requirements for rendering tier 1 and rendering tier 2: + +|Feature|Tier 1|Tier 2| +|-------------|------------|------------| +|DirectX version|Must be greater than or equal to 9.0.|Must be greater than or equal to 9.0.| +|Video RAM|Must be greater than or equal to 60 MB.|Must be greater than or equal to 120 MB.| +|Pixel shader|Version level must greater than or equal to 2.0.|Version level must greater than or equal to 2.0.| +|Vertex shader|No requirement.|Version level must greater than or equal to 2.0.| +|Multitexture units|No requirement.|Number of units must greater than or equal to 4.| + + The following features and capabilities are hardware accelerated for rendering tier 1 and rendering tier 2: + +|Feature|Notes| +|-------------|-----------| +|2D rendering|Most 2D rendering is supported.| +|3D rasterization|Most 3D rasterization is supported.| +|3D anisotropic filtering|[!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] attempts to use anisotropic filtering when rendering 3D content. Anisotropic filtering refers to enhancing the image quality of textures on surfaces that are far away and steeply angled with respect to the camera.| +|3D MIP mapping|[!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] attempts to use MIP mapping when rendering 3D content. MIP mapping improves the quality of texture rendering when a texture occupies a smaller field of view in a .| +|Radial gradients|While supported, avoid the use of on large objects.| +|3D lighting calculations|[!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] performs per-vertex lighting, which means that a light intensity must be calculated at each vertex for each material applied to a mesh.| +|Text rendering|Subpixel font rendering uses available pixel shaders on the graphics hardware.| + + The following features and capabilities are hardware accelerated only for rendering tier 2: + +|Feature|Notes| +|-------------|-----------| +|3D anti-aliasing|3D anti-aliasing is supported only on operating systems that support Windows Display Driver Model (WDDM), such as Windows Vista and Windows 7.| + + The following features and capabilities are **not** hardware accelerated: + +|Feature|Notes| +|-------------|-----------| +|Printed content|All printed content is rendered using the [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] software pipeline.| +|Rasterized content that uses |Any content rendered by using the method of .| +|Tiled content that uses |Any tiled content in which the property of the is set to .| +|Surfaces that exceed the maximum texture size of the graphics hardware|For most graphics hardware, large surfaces are 2048x2048 or 4096x4096 pixels in size.| +|Any operation whose video RAM requirement exceeds the memory of the graphics hardware|You can monitor application video RAM usage by using the Perforator tool that is included in the [WPF Performance Suite](https://docs.microsoft.com/previous-versions/dotnet/netframework-4.0/aa969767(v=vs.100)) in the Windows SDK.| +|Layered windows|Layered windows allow [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] applications to render content to the screen in a non-rectangular window. On operating systems that support Windows Display Driver Model (WDDM), such as Windows Vista and Windows 7, layered windows are hardware accelerated. On other systems, such as Windows XP, layered windows are rendered by software with no hardware acceleration.

You can enable layered windows in [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] by setting the following properties:

- =
- = `true`
- = | + + +## Other Resources + The following resources can help you analyze the performance characteristics of your [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] application. + +### Graphics Rendering Registry Settings + [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] provides four registry settings for controlling [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] rendering: + +|Setting|Description| +|-------------|-----------------| +|**Disable Hardware Acceleration Option**|Specifies whether hardware acceleration should be enabled.| +|**Maximum Multisample Value**|Specifies the degree of multisampling for antialiasing 3D content.| +|**Required Video Driver Date Setting**|Specifies whether the system disables hardware acceleration for drivers released before November 2004.| +|**Use Reference Rasterizer Option**|Specifies whether [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] should use the reference rasterizer.| + + These settings can be accessed by any external configuration utility that knows how to reference the [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] registry settings. These settings can also be created or modified by accessing the values directly by using the Windows Registry Editor. For more information, see [Graphics Rendering Registry Settings](../graphics-multimedia/graphics-rendering-registry-settings.md). + +### WPF Performance Profiling Tools + [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] provides a suite of performance profiling tools that allow you to analyze the run-time behavior of your application and determine the types of performance optimizations you can apply. The following table lists the performance profiling tools that are included in the Windows SDK tool, WPF Performance Suite: + +|Tool|Description| +|----------|-----------------| +|Perforator|Use for analyzing rendering behavior.| +|Visual Profiler|Use for profiling the use of [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] services, such as layout and event handling, by elements in the visual tree.| + + The WPF Performance Suite provides a rich, graphical view of performance data. For more information about WPF performance tools, see [WPF Performance Suite](https://docs.microsoft.com/previous-versions/dotnet/netframework-4.0/aa969767(v=vs.100)). + +### DirectX Diagnostic Tool + The DirectX Diagnostic Tool, Dxdiag.exe, is designed to help you troubleshoot DirectX-related issues. The default installation folder for the DirectX Diagnostic Tool is: + + `~\Windows\System32` + + When you run the DirectX Diagnostic Tool, the main window contains a set of tabs that allow you to display and diagnose DirectX-related information. For example, the **System** tab provides system information about your computer and specifies the version of DirectX that is installed on your computer. + + ![Screenshot: DirectX Diagnostic Tool](./media/directxdiagnostictool-01.png "DirectXDiagnosticTool_01") +DirectX Diagnostic Tool main window + +## See also + +- +- +- [Optimizing WPF Application Performance](optimizing-wpf-application-performance.md) +- [WPF Performance Suite](https://docs.microsoft.com/previous-versions/dotnet/netframework-4.0/aa969767(v=vs.100)) +- [Graphics Rendering Registry Settings](../graphics-multimedia/graphics-rendering-registry-settings.md) +- [Animation Tips and Tricks](../graphics-multimedia/animation-tips-and-tricks.md) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/handwriting-recognition.md b/dotnet-desktop-guide/framework/wpf/advanced/handwriting-recognition.md new file mode 100644 index 0000000000..42df4d0dac --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/handwriting-recognition.md @@ -0,0 +1,32 @@ +--- +title: "Handwriting Recognition" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "handwriting recognition [WPF]" + - "recognition of handwriting [WPF]" +ms.assetid: f4e8576d-e731-4bac-9818-22e2ae636636 +--- +# Handwriting Recognition +This section discusses the fundamentals of recognition as it pertains to digital ink in the WPF platform. + +## Recognition Solutions + The following example shows how to recognize ink using the [Microsoft.Ink.InkCollector](https://docs.microsoft.com/previous-versions/dotnet/netframework-3.5/ms583683(v=vs.90)) class. + +> [!NOTE] +> This sample requires that handwriting recognizers be installed on the system. + + Create a new WPF application project in Visual Studio called **InkRecognition**. Replace the contents of the Window1.xaml file with the following XAML code. This code renders the application's user interface. + + [!code-xaml[InkRecognition#1](~/samples/snippets/csharp/VS_Snippets_Wpf/InkRecognition/CSharp/Window1.xaml#1)] + + Add a reference to the Microsoft Ink assembly, Microsoft.Ink.dll, which can be found in \Program Files\Common Files\Microsoft Shared\Ink. Replace the contents of the code behind file with the following code. + + [!code-csharp[InkRecognition#2](~/samples/snippets/csharp/VS_Snippets_Wpf/InkRecognition/CSharp/Window1.xaml.cs#2)] + [!code-vb[InkRecognition#2](~/samples/snippets/visualbasic/VS_Snippets_Wpf/InkRecognition/VisualBasic/Window1.xaml.vb#2)] + +## See also + +- [Microsoft.Ink.InkCollector](https://docs.microsoft.com/previous-versions/dotnet/netframework-3.5/ms583683(v=vs.90)) diff --git a/dotnet-desktop-guide/framework/wpf/advanced/hosting-win32-content-in-wpf.md b/dotnet-desktop-guide/framework/wpf/advanced/hosting-win32-content-in-wpf.md new file mode 100644 index 0000000000..07fd1a3047 --- /dev/null +++ b/dotnet-desktop-guide/framework/wpf/advanced/hosting-win32-content-in-wpf.md @@ -0,0 +1,369 @@ +--- +title: "Hosting Win32 Content" +ms.date: "03/30/2017" +helpviewer_keywords: + - "interoperability [WPF], tutorials" + - "Win32 code [WPF], WPF interoperation" + - "interoperability [WPF], Win32" +ms.assetid: 3cc8644a-34f3-4082-9ddc-77623e4df2d8 +--- + +# Hosting Win32 Content in WPF + +## Prerequisites + +See [WPF and Win32 Interoperation](wpf-and-win32-interoperation.md). + +## A Walkthrough of Win32 Inside Windows Presentation Framework (HwndHost) + +To reuse Win32 content inside [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] applications, use , which is a control that makes HWNDs look like [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] content. Like , is straightforward to use: derive from and implement `BuildWindowCore` and `DestroyWindowCore` methods, then instantiate your derived class and place it inside your [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] application. + +If your Win32 logic is already packaged as a control, then your `BuildWindowCore` implementation is little more than a call to `CreateWindow`. For example, to create a Win32 LISTBOX control in C++: + +```cpp +virtual HandleRef BuildWindowCore(HandleRef hwndParent) override { + HWND handle = CreateWindowEx(0, L"LISTBOX", + L"this is a Win32 listbox", + WS_CHILD | WS_VISIBLE | LBS_NOTIFY + | WS_VSCROLL | WS_BORDER, + 0, 0, // x, y + 30, 70, // height, width + (HWND) hwndParent.Handle.ToPointer(), // parent hwnd + 0, // hmenu + 0, // hinstance + 0); // lparam + + return HandleRef(this, IntPtr(handle)); +} + +virtual void DestroyWindowCore(HandleRef hwnd) override { + // HwndHost will dispose the hwnd for us +} +``` + +But suppose the Win32 code is not quite so self-contained? If so, you can create a Win32 dialog box and embed its contents into a larger [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] application. The sample shows this in Visual Studio and C++, although it is also possible to do this in a different language or at the command line. + +Start with a simple dialog, which is compiled into a C++ DLL project. + +Next, introduce the dialog into the larger [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] application: + +- Compile the DLL as managed (`/clr`) + +- Turn the dialog into a control + +- Define the derived class of with `BuildWindowCore` and `DestroyWindowCore` methods + +- Override `TranslateAccelerator` method to handle dialog keys + +- Override `TabInto` method to support tabbing + +- Override `OnMnemonic` method to support mnemonics + +- Instantiate the subclass and put it under the right [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] element + +### Turn the Dialog into a Control + +You can turn a dialog box into a child HWND using the WS_CHILD and DS_CONTROL styles. Go into the resource file (.rc) where the dialog is defined, and find the beginning of the definition of the dialog: + +```text +IDD_DIALOG1 DIALOGEX 0, 0, 303, 121 +STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU +``` + +Change the second line to: + +```text +STYLE DS_SETFONT | WS_CHILD | WS_BORDER | DS_CONTROL +``` + +This action does not fully package it into a self-contained control; you still need to call `IsDialogMessage()` so Win32 can process certain messages, but the control change does provide a straightforward way of putting those controls inside another HWND. + +## Subclass HwndHost + +Import the following namespaces: + +```cpp +namespace ManagedCpp +{ + using namespace System; + using namespace System::Windows; + using namespace System::Windows::Interop; + using namespace System::Windows::Input; + using namespace System::Windows::Media; + using namespace System::Runtime::InteropServices; +``` + +Then create a derived class of and override the `BuildWindowCore` and `DestroyWindowCore` methods: + +```cpp +public ref class MyHwndHost : public HwndHost, IKeyboardInputSink { + private: + HWND dialog; + + protected: + virtual HandleRef BuildWindowCore(HandleRef hwndParent) override { + InitializeGlobals(); + dialog = CreateDialog(hInstance, + MAKEINTRESOURCE(IDD_DIALOG1), + (HWND) hwndParent.Handle.ToPointer(), + (DLGPROC) About); + return HandleRef(this, IntPtr(dialog)); + } + + virtual void DestroyWindowCore(HandleRef hwnd) override { + // hwnd will be disposed for us + } +``` + +Here you use the `CreateDialog` to create the dialog box that is really a control. Since this is one of the first methods called inside the DLL, you should also do some standard Win32 initialization by calling a function you will define later, called `InitializeGlobals()`: + +```cpp +bool initialized = false; + void InitializeGlobals() { + if (initialized) return; + initialized = true; + + // TODO: Place code here. + MSG msg; + HACCEL hAccelTable; + + // Initialize global strings + LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); + LoadString(hInstance, IDC_TYPICALWIN32DIALOG, szWindowClass, MAX_LOADSTRING); + MyRegisterClass(hInstance); +``` + +### Override TranslateAccelerator Method to Handle Dialog Keys + +If you ran this sample now, you would get a dialog control that displays, but it would ignore all of the keyboard processing that makes a dialog box a functional dialog box. You should now override the `TranslateAccelerator` implementation (which comes from `IKeyboardInputSink`, an interface that implements). This method gets called when the application receives WM_KEYDOWN and WM_SYSKEYDOWN. + +```cpp +#undef TranslateAccelerator + virtual bool TranslateAccelerator(System::Windows::Interop::MSG% msg, + ModifierKeys modifiers) override + { + ::MSG m = ConvertMessage(msg); + + // Win32's IsDialogMessage() will handle most of our tabbing, but doesn't know + // what to do when it reaches the last tab stop + if (m.message == WM_KEYDOWN && m.wParam == VK_TAB) { + HWND firstTabStop = GetDlgItem(dialog, IDC_EDIT1); + HWND lastTabStop = GetDlgItem(dialog, IDCANCEL); + TraversalRequest^ request = nullptr; + + if (GetKeyState(VK_SHIFT) && GetFocus() == firstTabStop) { + // this code should work, but there’s a bug with interop shift-tab in current builds + request = gcnew TraversalRequest(FocusNavigationDirection::Last); + } + else if (!GetKeyState(VK_SHIFT) && GetFocus() == lastTabStop) { + request = gcnew TraversalRequest(FocusNavigationDirection::Next); + } + + if (request != nullptr) + return ((IKeyboardInputSink^) this)->KeyboardInputSite->OnNoMoreTabStops(request); + + } + + // Only call IsDialogMessage for keys it will do something with. + if (msg.message == WM_SYSKEYDOWN || msg.message == WM_KEYDOWN) { + switch (m.wParam) { + case VK_TAB: + case VK_LEFT: + case VK_UP: + case VK_RIGHT: + case VK_DOWN: + case VK_EXECUTE: + case VK_RETURN: + case VK_ESCAPE: + case VK_CANCEL: + IsDialogMessage(dialog, &m); + // IsDialogMessage should be called ProcessDialogMessage -- + // it processes messages without ever really telling you + // if it handled a specific message or not + return true; + } + } + + return false; // not a key we handled + } +``` + +This is a lot of code in one piece, so it could use some more detailed explanations. First, the code using C++ and C++ macros; you need to be aware that there is already a macro named `TranslateAccelerator`, which is defined in winuser.h: + +```cpp +#define TranslateAccelerator TranslateAcceleratorW +``` + +So make sure to define a `TranslateAccelerator` method and not a `TranslateAcceleratorW` method. + +Similarly, there is both the unmanaged winuser.h MSG and the managed `Microsoft::Win32::MSG` struct. You can disambiguate between the two using the C++ `::` operator. + +```cpp +virtual bool TranslateAccelerator(System::Windows::Interop::MSG% msg, + ModifierKeys modifiers) override +{ + ::MSG m = ConvertMessage(msg); +} +``` + +Both MSGs have the same data, but sometimes it is easier to work with the unmanaged definition, so in this sample you can define the obvious conversion routine: + +```cpp +::MSG ConvertMessage(System::Windows::Interop::MSG% msg) { + ::MSG m; + m.hwnd = (HWND) msg.hwnd.ToPointer(); + m.lParam = (LPARAM) msg.lParam.ToPointer(); + m.message = msg.message; + m.wParam = (WPARAM) msg.wParam.ToPointer(); + + m.time = msg.time; + + POINT pt; + pt.x = msg.pt_x; + pt.y = msg.pt_y; + m.pt = pt; + + return m; +} +``` + +Back to `TranslateAccelerator`. The basic principle is to call the Win32 function `IsDialogMessage` to do as much work as possible, but `IsDialogMessage` does not have access to anything outside the dialog. As a user tab around the dialog, when tabbing runs past the last control in our dialog, you need to set focus to the [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] portion by calling `IKeyboardInputSite::OnNoMoreStops`. + +```cpp +// Win32's IsDialogMessage() will handle most of the tabbing, but doesn't know +// what to do when it reaches the last tab stop +if (m.message == WM_KEYDOWN && m.wParam == VK_TAB) { + HWND firstTabStop = GetDlgItem(dialog, IDC_EDIT1); + HWND lastTabStop = GetDlgItem(dialog, IDCANCEL); + TraversalRequest^ request = nullptr; + + if (GetKeyState(VK_SHIFT) && GetFocus() == firstTabStop) { + request = gcnew TraversalRequest(FocusNavigationDirection::Last); + } + else if (!GetKeyState(VK_SHIFT) && GetFocus() == lastTabStop) { { + request = gcnew TraversalRequest(FocusNavigationDirection::Next); + } + + if (request != nullptr) + return ((IKeyboardInputSink^) this)->KeyboardInputSite->OnNoMoreTabStops(request); +} +``` + +Finally, call `IsDialogMessage`. But one of the responsibilities of a `TranslateAccelerator` method is telling [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] whether you handled the keystroke or not. If you did not handle it, the input event can tunnel and bubble through the rest of the application. Here, you will expose a quirk of keyboard messange handling and the nature of the input architecture in Win32. Unfortunately, `IsDialogMessage` does not return in any way whether it handles a particular keystroke. Even worse, it will call `DispatchMessage()` on keystrokes it should not handle! So you will have to reverse-engineer `IsDialogMessage`, and only call it for the keys you know it will handle: + +```cpp +// Only call IsDialogMessage for keys it will do something with. +if (msg.message == WM_SYSKEYDOWN || msg.message == WM_KEYDOWN) { + switch (m.wParam) { + case VK_TAB: + case VK_LEFT: + case VK_UP: + case VK_RIGHT: + case VK_DOWN: + case VK_EXECUTE: + case VK_RETURN: + case VK_ESCAPE: + case VK_CANCEL: + IsDialogMessage(dialog, &m); + // IsDialogMessage should be called ProcessDialogMessage -- + // it processes messages without ever really telling you + // if it handled a specific message or not + return true; + } +``` + +### Override TabInto Method to Support Tabbing + +Now that you have implemented `TranslateAccelerator`, a user can tab around inside the dialog box and tab out of it into the greater [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] application. But a user cannot tab back into the dialog box. To solve that, you override `TabInto`: + +```cpp +public: + virtual bool TabInto(TraversalRequest^ request) override { + if (request->FocusNavigationDirection == FocusNavigationDirection::Last) { + HWND lastTabStop = GetDlgItem(dialog, IDCANCEL); + SetFocus(lastTabStop); + } + else { + HWND firstTabStop = GetDlgItem(dialog, IDC_EDIT1); + SetFocus(firstTabStop); + } + return true; + } +``` + +The `TraversalRequest` parameter tells you whether the tab action is a tab or shift tab. + +### Override OnMnemonic Method to Support Mnemonics + +Keyboard handling is almost complete, but there is one thing missing – mnemonics do not work. If a user presses alt-F, focus doe not jump to the "First name:" edit box. So, you override the `OnMnemonic` method: + +```cpp +virtual bool OnMnemonic(System::Windows::Interop::MSG% msg, ModifierKeys modifiers) override { + ::MSG m = ConvertMessage(msg); + + // If it's one of our mnemonics, set focus to the appropriate hwnd + if (msg.message == WM_SYSCHAR && GetKeyState(VK_MENU /*alt*/)) { + int dialogitem = 9999; + switch (m.wParam) { + case 's': dialogitem = IDOK; break; + case 'c': dialogitem = IDCANCEL; break; + case 'f': dialogitem = IDC_EDIT1; break; + case 'l': dialogitem = IDC_EDIT2; break; + case 'p': dialogitem = IDC_EDIT3; break; + case 'a': dialogitem = IDC_EDIT4; break; + case 'i': dialogitem = IDC_EDIT5; break; + case 't': dialogitem = IDC_EDIT6; break; + case 'z': dialogitem = IDC_EDIT7; break; + } + if (dialogitem != 9999) { + HWND hwnd = GetDlgItem(dialog, dialogitem); + SetFocus(hwnd); + return true; + } + } + return false; // key unhandled +}; +``` + +Why not call `IsDialogMessage` here? You have the same issue as before--you need to be able to inform [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] code whether your code handled the keystroke or not, and `IsDialogMessage` cannot do that. There is also a second issue, because `IsDialogMessage` refuses to process the mnemonic if the focused HWND is not inside the dialog box. + +### Instantiate the HwndHost Derived Class + +Finally, now that all the key and tab support is in place, you can put your into the larger [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] application. If the main application is written in [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)], the easiest way to put it in the right place is to leave an empty element where you want to put the . Here you create a named `insertHwndHostHere`: + +```xaml + + +