Windows controls and facilities

How to Use Pager Controls

This section describes how to implement the pager control in your application.

What you need to know

Technologies

Prerequisites

  • C/C++
  • Windows User Interface Programming

Instructions

Initialize a Pager Control

To use the pager control, you must call the InitCommonControlsEx function with the ICC_PAGESCROLLER_CLASS flag set in the dwICC member of the INITCOMMONCONTROLSEX structure.

Create a Pager Control

Use the CreateWindow or the CreateWindowEx API to create a pager control. The class name for the control is WC_PAGESCROLLER, which is defined in Commctrl.h. The PGS_HORZ style is used to create a horizontal pager, and the PGS_VERT style is used to create a vertical pager. Because this is a child control, the WS_CHILD style should also be used.

After the pager control is created, you will most likely want to assign a contained window to it. If the contained window is a child window, you should make the child window a child of the pager control so that the size and position will be calculated correctly. You then assign the window to the pager control with the PGM_SETCHILD message. Be aware that this message does not actually change the parent window of the contained window; it simply assigns the contained window. If the contained window is one of the common controls, it must have the CCS_NORESIZE style to prevent the control from attempting to resize itself to the pager control’s size.

Process Pager Control Notifications

At a minimum, it is necessary to process the PGN_CALCSIZE notification. If you do not process this notification and enter a value for the width or height, the scroll arrows in the pager control will not be displayed. This is because the pager control uses the width or height supplied in the PGN_CALCSIZE notification to determine the «ideal» size of the contained window.

The following example demonstrates how to process the PGN_CALCSIZE notification case. In this example, the contained window is a toolbar control that contains an unknown number of buttons at an unknown size. The example shows how to use the TB_GETMAXSIZE message to determine the size of all of the items in the toolbar. The example then places the width of all of the items into the iWidth member of the NMPGCALCSIZE structure that is passed to the notification.

Item Collection Класс

Определение

Содержит список элементов, которые образуют содержимое ItemsControl. Holds the list of items that constitute the content of an ItemsControl.

Примеры

Если у вас есть ItemsControl , например, с ListBox содержимым, можно использовать Items свойство для доступа к элементу ItemCollection , который является представлением. If you have an ItemsControl, such as a ListBox that has content, you can use the Items property to access the ItemCollection, which is a view. Так как это представление, можно использовать функции, связанные с представлением, такие как сортировка, фильтрация и группирование. Because it is a view, you can then use the view-related functionalities such as sorting, filtering, and grouping. Обратите внимание, что при задании ItemsSource операции представления делегируют представление коллекции ItemsSource. Note that when ItemsSource is set, the view operations delegate to the view over the ItemsSource collection. Таким образом, ItemCollection поддерживает сортировку, фильтрацию и группирование, только если делегированное представление их поддерживает. Therefore, the ItemCollection supports sorting, filtering, and grouping only if the delegated view supported them.

В следующем примере показано, как сортировать содержимое ListBox с именем myListBox . The following example shows how to sort the content of a ListBox named myListBox . В этом примере Content — это имя свойства, по которому выполняется сортировка. In this example, Content is the name of the property to sort by.

При этом представление может быть или не быть представлением по умолчанию в зависимости от того, как данные настраиваются в ItemsControl . When you do this, the view might or might not be the default view, depending on how the data is set up on your ItemsControl. Например, если ItemsSource свойство привязано к CollectionViewSource , представление, полученное с помощью Items свойства, не является представлением по умолчанию. For example, when the ItemsSource property is bound to a CollectionViewSource, the view that you obtain using the Items property is not the default view.

Если ItemsControl используется привязка (вы используете ItemsSource свойство), то для получения представления по умолчанию можно выполнить следующие действия. If your ItemsControl is bound (you are using the ItemsSource property), then you can do the following to get the default view:

Кроме того, можно указать критерии фильтрации, сортировки и группирования в XAML с помощью CollectionViewSource . Alternately, you can specify filtering, sorting, and grouping criteria in XAML using CollectionViewSource.

Комментарии

ItemCollection поддерживает коллекцию таких элементов, как строки, объекты, узлы XML, элементы и другие коллекции. ItemCollection maintains a collection of items such as strings, objects, XML nodes, elements, and other collections. ItemsControlКомпонент использует данные в ItemCollection для создания его содержимого. An ItemsControl uses the data in the ItemCollection to generate its content. Если требуется выполнить статистическую обработку более чем одной коллекции, присвойте CompositeCollection ItemsSource свойству значение ItemsControl . If you want to aggregate more than one collection, assign a CompositeCollection to the ItemsSource property of your ItemsControl.

Используйте Items свойство или ItemsSource свойство, чтобы указать коллекцию, которая должна использоваться для создания содержимого ItemsControl . Use either the Items property or the ItemsSource property to specify the collection that should be used to generate the content of your ItemsControl. Если ItemsSource свойство задано, Items коллекция будет доступна только для чтения и имеет фиксированный размер. When the ItemsSource property is set, the Items collection will be made read-only and fixed-size. Это означает, что при использовании ItemsSource свойства нельзя добавлять, удалять или изменять элементы ItemCollection напрямую. This means that if you are using the ItemsSource property, you cannot add, delete, or change items in the ItemCollection directly.

Читайте также:  Realtek high definition audio driver gigabyte windows 10

ItemCollection — Это CollectionView и, таким образом, обеспечивает функциональные возможности представления коллекции, такие как сортировка, группирование и фильтрация. ItemCollection is a CollectionView and therefore provides collection view functionalities, such as sorting, grouping, and filtering. Дополнительные сведения см. в разделах SortDescriptions, Filter и GroupDescriptions. For more information, see SortDescriptions, Filter, and GroupDescriptions.

Дополнительные сведения о представлениях коллекций см. в разделе Общие сведения о привязке данных. For more information about collection views, see Data Binding Overview.

Свойства

Получает значение, указывающее, может ли какой-либо поток, кроме создавшего CollectionView, изменить SourceCollection. Gets a value that indicates whether a thread other than the one that created the CollectionView can change the SourceCollection.

(Унаследовано от CollectionView) CanChangeLiveFiltering

Получает значение, указывающее, поддерживает ли представление коллекции включение или выключение фильтрации данных в режиме реального времени. Gets a value that indicates whether the collection view supports turning filtering data in real time on or off.

Получает значение, указывающее, поддерживает ли представление коллекции включение или выключение группирования данных в режиме реального времени. Gets a value that indicates whether the collection view supports turning grouping data in real time on or off.

Получает значение, указывающее, поддерживает ли представление коллекции включение или выключение сортировки данных в режиме реального времени. Gets a value that indicates whether the collection view supports turning sorting data in real time on or off.

Получает значение показывающее, поддерживает ли данное представление коллекции фильтрацию. Gets a value that indicates whether this collection view supports filtering.

Получает значение показывающее, поддерживает ли данное представление коллекции группировку. Gets a value that indicates whether this collection view supports grouping.

Получает значение показывающее, поддерживает ли данное представление коллекции сортировку. Gets a value that indicates whether this collection view supports sorting.

Возврат объекта, который можно использовать для сравнения элементов представления. Returns an object that you can use to compare items in the view.

(Унаследовано от CollectionView) Count

Получает количество записей в коллекции. Gets the number of records in the collection.

Возвращает или задает сведений о языке и региональных параметрах, используемых в ходе сортировки. Gets or sets the culture information to use during sorting.

(Унаследовано от CollectionView) CurrentItem

Возвращает текущий элемент в представлении. Gets the current item in the view.

Получает порядковую позицию текущего элемента в представлении. Gets the ordinal position of the current item within the view.

Возвращает объект Dispatcher, с которым связан этот объект DispatcherObject. Gets the Dispatcher this DispatcherObject is associated with.

(Унаследовано от DispatcherObject) Filter

Возвращает или задает обратный вызов, используемый для определения, подходит ли элемент для включения в представление. Gets or sets a callback used to determine if an item is suitable for inclusion in the view.

Получает коллекцию объектов GroupDescription, определяющих, как группировать элементы. Gets a collection of GroupDescription objects that defines how to group the items.

Получает группы верхнего уровня, сконструированные в соответствии сGroupDescriptions. Gets the top-level groups that are constructed according to the GroupDescriptions.

Получает значение, которое показывает, находится ли текущий элемент за пределами окончания коллекции. Gets a value that indicates whether the current item of the view is beyond the end of the collection.

Получает значение, которое показывает, находится ли текущий элемент за пределами начала коллекции. Gets a value that indicates whether the current item of the view is beyond the beginning of the collection.

Получение значения, которое определяет, находится ли CurrentItem в CurrentPosition. Gets a value that indicates whether the CurrentItem is at the CurrentPosition.

(Унаследовано от CollectionView) IsDynamic

Получение значения, определяющего, предоставляет ли базовая коллекция уведомления об изменениях. Gets a value that indicates whether the underlying collection provides change notifications.

(Унаследовано от CollectionView) IsEmpty

Получение значения, которое определяет, является ли пустым полученное (отфильтрованное) представление. Gets a value that indicates whether the resulting (filtered) view is empty.

Получает значение, указывающее, подписывается ли какой-либо объект на события этого CollectionView. Gets a value that indicates whether any object is subscribing to the events of this CollectionView.

(Унаследовано от CollectionView) IsLiveFiltering

Получает или задает значение, указывающее, включена ли фильтрация данных в реальном времени. Gets or sets a value that indicates whether filtering data in real time is enabled.

Получает или задает значение, указывающее, включено ли группирование данных в реальном времени. Gets or sets a value that indicates whether grouping data in real time is enabled.

Получает или задает значение, указывающее, включена ли сортировка в реальном времени. Gets or sets a value that indicates whether sorting in real time is enabled.

Получает значение, которое указывает, используется ли метод DeferRefresh(). Gets a value that indicates whether there is an outstanding DeferRefresh() in use.

(Унаследовано от CollectionView) Item[Int32]

Возвращает или задает элемент в данном основанном на нуле индексе. Gets or sets the item at the given zero-based index.

Получает коллекцию строк, определяющих свойства, которые участвуют в фильтрации данных в режиме реального времени. Gets a collection of strings that specify the properties that participate in filtering data in real time.

Получает коллекцию строк, определяющих свойства, которые участвуют в группировании данных в режиме реального времени. Gets a collection of strings that specify the properties that participate in grouping data in real time.

Получает коллекцию строк, определяющих свойства, которые участвуют в сортировке данных в режиме реального времени. Gets a collection of strings that specify the properties that participate in sorting data in real time.

Читайте также:  Как запустить справочную систему windows

Получает значение, которое показывает, необходимо ли обновление коллекции. Gets a value that indicates whether the collection needs to be refreshed.

Возвращает коллекцию объектов SortDescription, которые описывают, как элементы в коллекции сортируются в представлении. Gets a collection of SortDescription objects that describe how the items in the collection are sorted in the view.

Получает неотсортированную и неотфильтрованную коллекцию, лежащую в основе данного представления коллекции. Gets the unsorted and unfiltered collection that underlies this collection view.

Возвращает значение, указывающее, требуется ли обновление журнала изменений, поскольку CollectionChanged уведомление было получено в другом потоке без предварительного входа в Диспетчер потоков пользовательского интерфейса. Gets a value that indicates whether it has been necessary to update the change log because a CollectionChanged notification has been received on a different thread without first entering the user interface (UI) thread dispatcher.

(Унаследовано от CollectionView)

Методы

Добавляет элемент в коллекцию ItemCollection. Adds an item to the ItemCollection.

Определяет, имеет ли вызывающий поток доступ к этому DispatcherObject. Determines whether the calling thread has access to this DispatcherObject.

(Унаследовано от DispatcherObject) Clear()

Очищает коллекцию и освобождает ссылки на все элементы, входящие в данное время в коллекцию. Clears the collection and releases the references on all items currently in the collection.

Очищение ожидающих изменений из журнала изменений Clears any pending changes from the change log.

(Унаследовано от CollectionView) ClearPendingChanges()

Очищает необработанные изменения в коллекцию. Clears unprocessed changed to the collection.

(Унаследовано от CollectionView) Contains(Object)

Возвращает значение, которое показывает, находится ли указанный элемент в этом представлении. Returns a value that indicates whether the specified item is in this view.

Копирует элементы коллекции в массив начиная с определенного индекса в массиве. Copies the elements of the collection to an array, starting at a particular array index.

Вводит отложенный цикл, который можно использовать для слияния изменений с представлением и задержки автоматического обновления. Enters a defer cycle that you can use to merge changes to the view and delay automatic refresh.

Удаляет ссылку на базовую коллекцию из CollectionView. Removes the reference to the underlying collection from the CollectionView.

(Унаследовано от CollectionView) Equals(Object)

Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.

(Унаследовано от Object) GetEnumerator()

Возврат объекта, который можно использовать для перечисления элементов представления. Returns an object that you can use to enumerate the items in the view.

(Унаследовано от CollectionView) GetHashCode()

Служит хэш-функцией по умолчанию. Serves as the default hash function.

(Унаследовано от Object) GetItemAt(Int32)

Возвращает элемент в указанный основанный на нуле индекс в данном представлении. Returns the item at the specified zero-based index in this view.

Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.

(Унаследовано от Object) IndexOf(Object)

Возвращает индекс в данной коллекции, в которой расположен указанный элемент. Returns the index in this collection where the specified item is located.

Вставляет элемент в коллекцию по указанному индексу. Inserts an element into the collection at the specified index.

Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.

(Унаследовано от Object) MoveCurrentTo(Object)

Задает указанный элемент в коллекции как CurrentItem. Sets the specified item in the collection as the CurrentItem.

Задает первый элемент представления в качестве свойства CurrentItem. Sets the first item in the view as the CurrentItem.

Задает последний элемент представления в качестве свойства CurrentItem. Sets the last item in the view as the CurrentItem.

Задает элемент, следующий в представлении за свойством CurrentItem, в качестве свойства CurrentItem. Sets the item after the CurrentItem in the view as the CurrentItem.

Задает элемент по заданному индексу в качестве CurrentItem в представлении. Sets the item at the specified index to be the CurrentItem in the view.

Задает элемент в представлении перед CurrentItem как CurrentItem. Sets the item before the CurrentItem in the view as the CurrentItem.

Возвращение значения, которое определяет, может ли представление менять то, какой элемент является CurrentItem. Returns a value that indicates whether the view can change which item is the CurrentItem.

(Унаследовано от CollectionView) OnAllowsCrossThreadChangesChanged()

Происходит при изменении свойства AllowsCrossThreadChanges. Occurs when the AllowsCrossThreadChanges property changes.

(Унаследовано от CollectionView) OnBeginChangeLogging(NotifyCollectionChangedEventArgs)

Вызван базовым классом, чтобы уведомить производный класс, что событие CollectionChanged было отправлено в очередь сообщений. Called by the base class to notify the derived class that an CollectionChanged event has been posted to the message queue.

(Унаследовано от CollectionView) OnCollectionChanged(NotifyCollectionChangedEventArgs)

(Унаследовано от CollectionView) OnCollectionChanged(Object, NotifyCollectionChangedEventArgs)

(Унаследовано от CollectionView) OnCurrentChanged()

Вызывает событие CurrentChanged. Raises the CurrentChanged event.

(Унаследовано от CollectionView) OnCurrentChanging()

Порождение события CurrentChanging, которое не подлежит отмене. Raises a CurrentChanging event that is not cancelable.

(Унаследовано от CollectionView) OnCurrentChanging(CurrentChangingEventArgs)

Порождение события CurrentChanging посредством заданных аргументов. Raises the CurrentChanging event with the specified arguments.

(Унаследовано от CollectionView) OnPropertyChanged(PropertyChangedEventArgs)

Порождение события PropertyChanged с помощью заданных аргументов. Raises the PropertyChanged event using the specified arguments.

(Унаследовано от CollectionView) PassesFilter(Object)

Возвращает значение показывающее, принадлежит ли указанный элемент этому представлению. Returns a value that indicates whether the specified item belongs to this view.

При переопределении в производном классе обрабатывает одно изменение в потоке пользовательского интерфейса. When overridden in a derived class, processes a single change on the UI thread.

(Унаследовано от CollectionView) ProcessPendingChanges()

Гарантирует, что были зафиксированы все ожидающие изменения в коллекции. Ensures that all pending changes to the collection have been committed.

(Унаследовано от CollectionView) Refresh()

Повторное создание представления. Re-creates the view.

Читайте также:  Журнал обновлений windows 10 корпоративная

(Унаследовано от CollectionView) RefreshOrDefer()

Обновление представления или указание на необходимость обновления представления после завершения отложенного цикла. Refreshes the view or specifies that the view needs to be refreshed when the defer cycle completes.

(Унаследовано от CollectionView) RefreshOverride()

Повторное создание представления. Re-creates the view.

(Унаследовано от CollectionView) Remove(Object)

Удаляет ссылку указанного элемента из коллекции или ракурса. Removes the specified item reference from the collection or view.

Удаляет элемент в указанный индекс коллекции или представление. Removes the item at the specified index of the collection or view.

Установка заданного элемента и индекса в качестве значений свойств CurrentItem и CurrentPosition. Sets the specified item and index as the values of the CurrentItem and CurrentPosition properties.

(Унаследовано от CollectionView) SetCurrent(Object, Int32, Int32)

Установка заданного элемента и индекса в качестве значений свойств CurrentItem и CurrentPosition. Sets the specified item and index as the values of the CurrentItem and CurrentPosition properties. Данный метод можно вызвать из конструктора производного класса. This method can be called from a constructor of a derived class.

(Унаследовано от CollectionView) ToString()

Возвращает строку, представляющую текущий объект. Returns a string that represents the current object.

(Унаследовано от Object) VerifyAccess()

Обеспечивает наличие у вызывающего потока доступ к этому DispatcherObject. Enforces that the calling thread has access to this DispatcherObject.

(Унаследовано от DispatcherObject)

События

Возникает при изменении представления. Occurs when the view has changed.

(Унаследовано от CollectionView) CurrentChanged

Происходит после изменения CurrentItem. Occurs after the CurrentItem has changed.

(Унаследовано от CollectionView) CurrentChanging

Происходит, когда CurrentItem меняется. Occurs when the CurrentItem is changing.

(Унаследовано от CollectionView) PropertyChanged

Происходит при изменении значения свойства. Occurs when a property value has changed.

(Унаследовано от CollectionView)

Явные реализации интерфейса

Этот элемент поддерживает инфраструктуру Windows Presentation Foundation (WPF) и не предназначен для непосредственного использования из кода. This member supports the Windows Presentation Foundation (WPF) infrastructure and is not intended to be used directly from your code.

Этот элемент поддерживает инфраструктуру Windows Presentation Foundation (WPF) и не предназначен для непосредственного использования из кода. This member supports the Windows Presentation Foundation (WPF) infrastructure and is not intended to be used directly from your code.

Добавляет новый элемент в коллекцию. Adds a new item to the collection.

Возвращает значение, указывающее, можно ли добавить новый элемент в коллекцию. Gets a value that indicates whether a new item can be added to the collection.

Возвращает значение, указывающее, может ли представление коллекции отклонить отложенные изменения и восстановить исходные значения изменяемого объекта. Gets a value that indicates whether the collection view can discard pending changes and restore the original values of an edited object.

Завершает транзакцию изменения и, если это возможно, восстанавливает исходное значение для элемента. Ends the edit transaction and, if possible, restores the original value to the item.

Завершает транзакцию добавления и отменяет ожидающий новый элемент. Ends the add transaction and discards the pending new item.

Возвращает значение, указывающее, можно ли удалить элемент из коллекции. Gets a value that indicates whether an item can be removed from the collection.

Завершает транзакцию изменения и сохраняет отложенные изменения. Ends the edit transaction and saves the pending changes.

Завершает транзакцию добавления и сохраняет ожидаемый новый элемент. Ends the add transaction and saves the pending new item.

Возвращает элемент, добавляемый во время текущей транзакции добавления. Gets the item that is being added during the current add transaction.

Возвращает изменяемый элемент коллекции. Gets the item in the collection that is being edited.

Начинает транзакцию изменения заданного элемента. Begins an edit transaction of the specified item.

Возвращает значение, указывающее, выполняется ли в данный момент транзакция добавления. Gets a value that indicates whether an add transaction is in progress.

Возвращает значение, указывающее, выполняется ли в данный момент транзакция изменения. Gets a value that indicates whether an edit transaction is in progress.

Возвращает или задает положение местозаполнителя нового элемента в представлении коллекции. Gets or sets the position of the new item placeholder in the collection view.

Удаляет заданный элемент из коллекции. Removes the specified item from the collection.

Удаляет элемент в указанной позиции из коллекции. Removes the item at the specified position from the collection.

Добавляет указанный объект в коллекцию. Adds the specified object to the collection.

Получает значение, указывающее, можно ли добавить указанный объект в коллекцию. Gets a value that indicates whether a specified object can be added to the collection.

Возврат объекта IEnumerator, который можно использовать для перечисления элементов представления. Returns an IEnumerator object that you can use to enumerate the items in the view.

(Унаследовано от CollectionView) IItemProperties.ItemProperties

Получает коллекцию, которая содержит сведения о свойствах, доступных для элементов в коллекции. Gets a collection that contains information about the properties that are available on the items in a collection.

Этот элемент поддерживает инфраструктуру Windows Presentation Foundation (WPF) и не предназначен для непосредственного использования из кода. This member supports the Windows Presentation Foundation (WPF) infrastructure and is not intended to be used directly from your code.

Этот элемент поддерживает инфраструктуру Windows Presentation Foundation (WPF) и не предназначен для непосредственного использования из кода. This member supports the Windows Presentation Foundation (WPF) infrastructure and is not intended to be used directly from your code.

Возникает при изменении представления. Occurs when the view has changed.

(Унаследовано от CollectionView) INotifyPropertyChanged.PropertyChanged

Возникает при смене значения свойства. Occurs when a property value changes.

(Унаследовано от CollectionView) IWeakEventListener.ReceiveWeakEvent(Type, Object, EventArgs)

Получает события от централизованного диспетчера событий. Receives events from the centralized event manager.

Методы расширения

Приводит элементы объекта IEnumerable к заданному типу. Casts the elements of an IEnumerable to the specified type.

Выполняет фильтрацию элементов объекта IEnumerable по заданному типу. Filters the elements of an IEnumerable based on a specified type.

Позволяет осуществлять параллельный запрос. Enables parallelization of a query.

Преобразовывает коллекцию IEnumerable в объект IQueryable. Converts an IEnumerable to an IQueryable.

Оцените статью