The ScrollWindow function scrolls the contents of the specified window’s client area.
Syntax
Parameters
Handle to the window where the client area is to be scrolled.
Specifies the amount, in device units, of horizontal scrolling. If the window being scrolled has the CS_OWNDC or CS_CLASSDC style, then this parameter uses logical units rather than device units. This parameter must be a negative value to scroll the content of the window to the left.
Specifies the amount, in device units, of vertical scrolling. If the window being scrolled has the CS_OWNDC or CS_CLASSDC style, then this parameter uses logical units rather than device units. This parameter must be a negative value to scroll the content of the window up.
Pointer to the RECT structure specifying the portion of the client area to be scrolled. If this parameter is NULL, the entire client area is scrolled.
Pointer to the RECT structure containing the coordinates of the clipping rectangle. Only device bits within the clipping rectangle are affected. Bits scrolled from the outside of the rectangle to the inside are painted; bits scrolled from the inside of the rectangle to the outside are not painted.
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call GetLastError.
Remarks
If the caret is in the window being scrolled, ScrollWindow automatically hides the caret to prevent it from being erased and then restores the caret after the scrolling is finished. The caret position is adjusted accordingly.
The area uncovered by ScrollWindow is not repainted, but it is combined into the window’s update region. The application eventually receives a WM_PAINT message notifying it that the region must be repainted. To repaint the uncovered area at the same time the scrolling is in action, call the UpdateWindow function immediately after calling ScrollWindow.
If the lpRect parameter is NULL, the positions of any child windows in the window are offset by the amount specified by the XAmount and YAmount parameters; invalid (unpainted) areas in the window are also offset. ScrollWindow is faster when lpRect is NULL.
If lpRect is not NULL, the positions of child windows are not changed and invalid areas in the window are not offset. To prevent updating problems when lpRect is not NULL, call UpdateWindow to repaint the window before calling ScrollWindow.
Элементы управления «Средство прокрутки» Scroll viewer controls
При наличии большего содержимого пользовательского интерфейса, чем можно поместить в область, используйте средство прокрутки. When there is more UI content to show than you can fit in an area, use the scroll viewer control.
Средства прокрутки позволяют содержимому выходить за пределы окна просмотра (видимой области). Scroll viewers enable content to extend beyond the bounds of the viewport (visible area). Пользователи могут добраться до этого содержимого, манипулируя средством прокрутки с помощью сенсорного ввода, колесика мыши, клавиатуры или игрового планшета, курсора мыши либо пера для взаимодействия с полосой прокрутки средства прокрутки. Users reach this content by manipulating the scroll viewer surface through touch, mousewheel, keyboard, or a gamepad, or by using the mouse or pen cursor to interact with the scroll viewer’s scrollbar. На рисунке показано несколько примеров элементов управления средством прокрутки. This image shows several examples of scroll viewer controls.
В зависимости от ситуации, полоса прокрутки средства прокрутки использует две различные визуализации, показанные на следующем рисунке: индикатор сдвига (слева) и традиционную полосу прокрутки (справа). Depending on the situation, the scroll viewer’s scrollbar uses two different visualizations, shown in the following illustration: the panning indicator (left) and the traditional scrollbar (right).
Средство прокрутки знает о методе ввода пользователя и использует его, чтобы определить, какие визуализации отображать. The scroll viewer is conscious of the user’s input method and uses it to determine which visualization to display.
При прокрутке области без непосредственного управления полосой прокрутки, например, сенсорным вводом, появится индикатор сдвига, указывающий текущую позицию прокрутки. When the region is scrolled without manipulating the scrollbar directly, for example, by touch, the panning indicator appears, displaying the current scroll position.
При перемещении курсора мыши или пера через индикатор сдвига он преобразуется в традиционную полосу прокрутки. When the mouse or pen cursor moves over the panning indicator, it morphs into the traditional scrollbar. Перетаскиванием ползунка полосы прокрутки можно управлять областью прокрутки. Dragging the scrollbar thumb manipulates the scrolling region.
Когда полоса прокрутки отображается, она накладывается на 16 пикселей поверх содержимого внутри ScrollViewer. When the scrollbar is visible it is overlaid as 16px on top of the content inside your ScrollViewer. Чтобы обеспечить качественное проектирование взаимодействия с пользователем, необходимо убедиться, что интерактивное содержимое не замещается перекрытием. In order to ensure good UX design you will want to ensure that no interactive content is obscured by this overlay. Кроме того, если вы не хотите иметь перекрытие взаимодействия с пользователем, оставьте 16 пикселей заполнения границ окна просмотра, чтобы оставить место для полосы прокрутки. Additionally if you would prefer not to have UX overlap, leave 16px of padding on the edge of the viewport to allow for the scrollbar.
Примеры Examples
XAML Controls Gallery XAML Controls Gallery
Если у вас установлено приложение галереи элементов управления XAML, щелкните здесь, чтобы открыть приложение и увидеть ScrollViewer в действии. If you have the XAML Controls Gallery app installed, click here to open the app and see the ScrollViewer in action.
Создание средства прокрутки Create a scroll viewer
Для добавления на страницу вертикальной прокрутки создайте для содержимого страницы оболочку в средстве просмотра прокрутки. To add vertical scrolling to your page, wrap the page content in a scroll viewer.
В этом примере XAML показано, как размещать изображение в средстве прокрутки и включать масштабирование. This XAML shows how to enable horizontal scrolling, place an image in a scroll viewer and enable zooming.
ScrollViewer в шаблоне элемента управления ScrollViewer in a control template
Обычно элемент управления ScrollViewer является составной частью других элементов управления. It’s typical for a ScrollViewer control to exist as a composite part of other controls. Объект ScrollViewer с классом поддержки ScrollContentPresenter будет отображать окно просмотра вместе с полосами прокрутки только тогда, когда пространство макета основного элемента управления имеет меньший размер, чем размер развернутого содержимого. A ScrollViewer part, along with the ScrollContentPresenter class for support, will display a viewport along with scrollbars only when the host control’s layout space is being constrained smaller than the expanded content size. Такая ситуация часто возникает со списками, поэтому шаблоны ListView и GridView всегда содержат ScrollViewer. This is often the case for lists, so ListView and GridView templates always include a ScrollViewer. Шаблоны TextBox и RichEditBox также включают ScrollViewer. TextBox and RichEditBox also include a ScrollViewer in their templates.
Если в элементе управления имеется ScrollViewer, основной элемент управления зачастую имеет встроенную функцию обработки событий для определенных событий и манипуляций ввода, позволяющую прокручивать содержимое. When a ScrollViewer part exists in a control, the host control often has built-in event handling for certain input events and manipulations that enable the content to scroll. Например, GridView интерпретирует жест прокрутки, что приводит к горизонтальной прокрутке содержимого. For example, a GridView interprets a swipe gesture and this causes the content to scroll horizontally. События и необработанные манипуляции ввода, получаемые основным элементом управления, считаются обработанными элементом управления, а события более низкого уровня, такие как PointerPressed, не будут вызываться и не будут передаваться в какие-либо родительские контейнеры. The input events and raw manipulations that the host control receives are considered handled by the control, and lower-level events such as PointerPressed won’t be raised and won’t bubble to any parent containers either. Вы можете изменять некоторые параметры обработки встроенных элементов управления, переопределяя класс элементов управления и виртуальные методы OnEvent для событий или изменяя шаблон элемента управления. You can change some of the built-in control handling by overriding a control class and the OnEvent virtual methods for events, or by retemplating the control. Но в любом случае не рекомендуется просто воспроизводить исходное поведение по умолчанию, которое обычно там присутствует, чтобы элемент управления мог расширенно реагировать на события и на выполняемые пользователем действия и жесты ввода. But in either case it’s not trivial to reproduce the original default behavior, which is typically there so that the control reacts in expected ways to events and to a user’s input actions and gestures. Поэтому необходимо подумать о том, нужно ли вам на самом деле, чтобы это событие ввода срабатывало. So you should consider whether you really need that input event to fire. Вы можете проверить, имеются ли другие события ввода или жесты, которые не обрабатываются элементом управления, и использовать их в своем приложении или схеме взаимодействия элементов управления. You might want to investigate whether there are other input events or gestures that are not being handled by the control, and use those in your app or control interaction design.
Чтобы позволить элементам управления, имеющим в своем составе ScrollViewer, влиять на поведение и свойства, имеющие отношение к ScrollViewer, элемент ScrollViewer определяет несколько подключенных свойств XAML, которые можно настраивать в стилях и использовать в привязках шаблонов. To make it possible for controls that include a ScrollViewer to influence some of the behavior and properties that are from within the ScrollViewer part, ScrollViewer defines a number of XAML attached properties that can be set in styles and used in template bindings. Подробнее о подключенных свойствах см. в разделе Общие сведения о подключенных свойствах. For more info about attached properties, see Attached properties overview.
Подключенные свойства XAML для ScrollViewerScrollViewer XAML attached properties
ScrollViewer определяет следующие подключенные свойства XAML: ScrollViewer defines the following XAML attached properties:
Эти подключенные свойства XAML предназначены для случаев, когда применение ScrollViewer подразумевается, например когда ScrollViewer имеется в стандартном шаблоне для ListView или GridView, и вы хотите иметь возможность влиять на поведение элемента управления при прокрутке без осуществления доступа к частям шаблона. These XAML attached properties are intended for cases where the ScrollViewer is implicit, such as when the ScrollViewer exists in the default template for a ListView or GridView, and you want to be able to influence the scrolling behavior of the control without accessing template parts.
Например, вот как можно сделать вертикальные полосы прокрутки всегда видимыми во встроенном средстве прокрутки в ListView. For example, here’s how to make the vertical scrollbars always visible for a ListView’s built in scroll viewer.
В случаях, когда ScrollViewer подразумевается в вашем XAML, как показано в примере кода, вам не нужно использовать синтаксис подключенных свойств. For cases where a ScrollViewer is explicit in your XAML, as is shown in the example code, you don’t need to use attached property syntax. Просто используйте синтаксис атрибута, например . Just use attribute syntax, for example .
Что рекомендуется и что не рекомендуется делать Do’s and don’ts
По возможности используйте вертикальную, а не горизонтальную прокрутку. Whenever possible, design for vertical scrolling rather than horizontal.
Применяйте сдвиг вдоль одной оси для областей содержимого, выходящих за одну из границ окна просмотра (вертикальную или горизонтальную). Use one-axis panning for content regions that extend beyond one viewport boundary (vertical or horizontal). Применяйте сдвиг по двум осям для областей содержимого, которые выходят за обе границы окна просмотра (вертикальную и горизонтальную). Use two-axis panning for content regions that extend beyond both viewport boundaries (vertical and horizontal).
Используйте встроенную функцию прокрутки в представлении списка, представлении сетки, поле со списком, списке, поле текстового ввода и элементах управления «Главный раздел». Use the built-in scroll functionality in the list view, grid view, combo box, list box, text input box, and hub controls. Если элементов слишком много и невозможно отобразить их сразу, с помощью этих элементов управления пользователь может прокручивать список элементов по горизонтали или по вертикали. With those controls, if there are too many items to show all at once, the user is able to scroll either horizontally or vertically over the list of items.
Если вы хотите, чтобы пользователь мог применять сдвиг в обоих направлениях на довольно большой области и, возможно, также масштабирование, например если вы даете пользователю возможность сдвигать и масштабировать полноразмерное изображение (а не изображение по размеру экрана), то поместите это изображение в средство прокрутки. If you want the user to pan in both directions around a larger area, and possibly to zoom, too, for example, if you want to allow the user to pan and zoom over a full-sized image (rather than an image sized to fit the screen) then place the image inside a scroll viewer.
Если пользователь прокручивает большой объем текста, настройте средство прокрутки так, чтобы прокрутка осуществлялась только по вертикали. If the user will scroll through a long passage of text, configure the scroll viewer to scroll vertically only.
Средство прокрутки должно содержать только один объект. Use a scroll viewer to contain one object only. Имейте в виду, что один объект может являться панелью макета, в свою очередь содержащей любое количество собственных объектов. Note that the one object can be a layout panel, in turn containing any number of objects of its own.
Если нужно обрабатывать события указателя для UIElement в прокручиваемом представлении (например, ScrollViewer или ListView), необходимо явно отключить поддержку событий обработки для элемента в представлении, вызвав UIElement.CancelDirectmanipulation(). If you need to handle pointer events for a UIElement in a scrollable view (such as a ScrollViewer or ListView), you must explicitly disable support for manipulation events on the element in the view by calling UIElement.CancelDirectmanipulation(). Чтобы повторно включить события обработки в представлении, вызовите UIElement.TryStartDirectManipulation(). To re-enable manipulation events in the view, call UIElement.TryStartDirectManipulation().
Получение примера кода Get the sample code
Пример из коллекции элементов управления XAML — ознакомьтесь со всеми элементами управления XAML в интерактивном режиме. XAML Controls Gallery sample — See all the XAML controls in an interactive format.