System windows controls itemscontrol

The ItemsControl

WPF has a wide range of controls for displaying a list of data. They come in several shapes and forms and vary in how complex they are and how much work they perform for you. The simplest variant is the ItemsControl, which is pretty much just a markup-based loop — you need to apply all the styling and templating, but in many cases, that’s just what you need.

A simple ItemsControl example

Let’s kick off with a very simple example, where we hand-feed the ItemsControl with a set of items. This should show you just how simple the ItemsControl is:

As you can see, there is nothing that shows that we’re using a control for repeating the items instead of just manually adding e.g. 5 TextBlock controls — the ItemsControl is completely lookless by default. If you click on one of the items, nothing happens, because there’s no concept of selected item(s) or anything like that.

ItemsControl with data binding

Of course the ItemsControl is not meant to be used with items defined in the markup, like we did in the first example. Like pretty much any other control in WPF, the ItemsControl is made for data binding, where we use a template to define how our code-behind classes should be presented to the user.

To demonstrate that, I’ve whipped up an example where we display a TODO list to the user, and to show you just how flexible everything gets once you define your own templates, I’ve used a ProgressBar control to show you the current completion percentage. First some code, then a screenshot and then an explanation of it all:

The most important part of this example is the template that we specify inside of the ItemsControl, using a DataTemplate tag inside of the ItemsControl.ItemTemplate. We add a Grid panel, to get two columns: In the first we have a TextBlock, which will show the title of the TODO item, and in the second column we have a ProgressBar control, which value we bind to the Completion property.

The template now represents a TodoItem, which we declare in the Code-behind file, where we also instantiate a number of them and add them to a list. In the end, this list is assigned to the ItemsSource property of our ItemsControl, which then does the rest of the job for us. Each item in the list is displayed by using our template, as you can see from the resulting screenshot.

The ItemsPanelTemplate property

In the above examples, all items are rendered from top to bottom, with each item taking up the full row. This happens because the ItemsControl throw all of our items into a vertically aligned StackPanel by default. It’s very easy to change though, since the ItemsControl allows you to change which panel type is used to hold all the items. Here’s an example:

We specify that the ItemsControl should use a WrapPanel as its template by declaring one in the ItemsPanelTemplate property and just for fun, we throw in an ItemTemplate that causes the strings to be rendered as buttons. You can use any of the WPF panels, but some are more useful than others.

Another good example is the UniformGrid panel, where we can define a number of columns and then have our items neatly shown in equally-wide columns:

ItemsControl with scrollbars

Once you start using the ItemsControl, you might run into a very common problem: By default, the ItemsControl doesn’t have any scrollbars, which means that if the content doesn’t fit, it’s just clipped. This can be seen by taking our first example from this article and resizing the window:

Читайте также:  Как проверить smart жесткого диска mac os

WPF makes this very easy to solve though. There are a number of possible solutions, for instance you can alter the template used by the ItemsControl to include a ScrollViewer control, but the easiest solution is to simply throw a ScrollViewer around the ItemsControl. Here’s an example:

I set the two visibility options to Auto, to make them only visible when needed. As you can see from the screenshot, you can now scroll through the list of items.

Items Control. Items Свойство

Определение

Возвращает коллекцию, используемую для создания содержимого ItemsControl. Gets the collection used to generate the content of the ItemsControl.

Значение свойства

Коллекция, которая используется для создания содержимого ItemsControl. The collection that is used to generate the content of the ItemsControl. По умолчанию является пустой коллекцией. The default is an empty collection.

Примеры

В следующих примерах демонстрируется привязка данных к ItemsControl . The following examples demonstrate binding data to an ItemsControl. В первом примере создается класс с именем MyData , который представляет собой простую коллекцию строк. The first example creates a class called MyData that is a simple string collection.

В следующем примере ItemsSource выполняется привязка объекта ItemsControl к MyData . The following example binds the ItemsSource object of an ItemsControl to MyData .

На следующем рисунке показан ListBox элемент управления, созданный в предыдущем примере. The following illustration shows the ListBox control created in the previous example.

В следующем примере показано, как заполнить ItemsControl с помощью Items Свойства. The following example demonstrates how to populate an ItemsControl by using the Items property. В примере добавляются следующие типы элементов в ListBox : The example adds the following different types of items to the ListBox:

Строка. A string.

PanelЭлемент управления, содержащий другие UIElement объекты. A Panel control that contains other UIElement objects.

На следующем рисунке показан ListBox пример, созданный в предыдущем примере. The following illustration shows the ListBox created in the previous example.

Обратите внимание, что ItemCollection является представлением, поэтому можно использовать функции, связанные с представлением, такие как сортировка, фильтрация и группирование. Note that the ItemCollection is a view, so you can use the view-related functionalities such as sorting, filtering, and grouping.

Например, если у вас есть экземпляр ListBox , myListBox можно выполнить следующие действия, чтобы отсортировать содержимое ListBox . For example, if you have an instance of a ListBox, myListBox , you can do the following to sort the content of the ListBox. В этом примере Content — это имя свойства, по которому выполняется сортировка. In this example, Content is the name of the property to sort by.

Обратите внимание, что при этом, если элемент управления привязан к коллекции напрямую, используется представление коллекции по умолчанию, а критерии сортировки применяются ко всем остальным элементам управления, привязанным к той же коллекции напрямую. Note that when you do this, if the control is bound to a collection directly, the default collection view is used, and the sort criteria are applied to all other controls bound to the same collection directly. Представление не будет использоваться по умолчанию, если ItemsSource свойство привязано к CollectionViewSource . The view will not be the default view if the ItemsSource property is bound to a CollectionViewSource.

Если ItemsControl Привязка выполняется непосредственно к коллекции, можно выполнить следующие действия, чтобы получить представление по умолчанию: If your ItemsControl is bound directly to a collection, then you can do the following to get the default view:

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

Комментарии

Это свойство можно использовать для добавления элементов в ItemsControl . This property may be used to add items to an ItemsControl. Добавление дочернего ItemsControl объекта к объекту неявно добавляет его в объект ItemCollection для ItemsControl объекта. Adding a child to an ItemsControl object implicitly adds it to the ItemCollection for the ItemsControl object.

Это свойство можно задать только в XAML (XAML) с помощью показанного синтаксиса коллекции или путем доступа к объекту коллекции и использования его различных методов, таких как Add . This property can only be set in Extensible Application Markup Language (XAML) via the collection syntax shown, or by accessing the collection object and using its various methods such as Add . Свойство для доступа к объекту коллекции доступно только для чтения, а сама коллекция доступна для чтения и записи. The property to access the collection object itself is read-only, and the collection itself is read-write.

Читайте также:  Бэкап linux яндекс диск

Обратите внимание, что для Items ItemsSource указания коллекции, которая должна использоваться для создания содержимого, используется свойство или ItemsControl . Note that you use either the Items 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 is made read-only and fixed-size.

Если используется ItemsSource , задание ItemsSource свойства для null удаления коллекции и восстанавливает использование до Items , которое будет пустым ItemCollection . When ItemsSource is in use, setting the ItemsSource property to null removes the collection and restores usage to Items, which will be an empty ItemCollection.

Использование элемента свойства XAML XAML Property Element Usage

Значения XAML XAML Values

онеорморилементс OneOrMoreElements
Один или несколько UIElement объектов. One or more UIElement objects.

Items Control. Items Property

Definition

Gets the collection used to generate the content of the ItemsControl.

Property Value

The collection that is used to generate the content of the ItemsControl. The default is an empty collection.

Examples

The following examples demonstrate binding data to an ItemsControl. The first example creates a class called MyData that is a simple string collection.

The following example binds the ItemsSource object of an ItemsControl to MyData .

The following illustration shows the ListBox control created in the previous example.

The following example demonstrates how to populate an ItemsControl by using the Items property. The example adds the following different types of items to the ListBox:

A Panel control that contains other UIElement objects.

The following illustration shows the ListBox created in the previous example.

Note that the ItemCollection is a view, so you can use the view-related functionalities such as sorting, filtering, and grouping.

For example, if you have an instance of a ListBox, myListBox , you can do the following to sort the content of the ListBox. In this example, Content is the name of the property to sort by.

Note that when you do this, if the control is bound to a collection directly, the default collection view is used, and the sort criteria are applied to all other controls bound to the same collection directly. The view will not be the default view if the ItemsSource property is bound to a CollectionViewSource.

If your ItemsControl is bound directly to a collection, then you can do the following to get the default view:

Alternately, you can specify filtering, sorting, and grouping criteria in XAML or code by using a CollectionViewSource.

Remarks

This property may be used to add items to an ItemsControl. Adding a child to an ItemsControl object implicitly adds it to the ItemCollection for the ItemsControl object.

This property can only be set in Extensible Application Markup Language (XAML) via the collection syntax shown, or by accessing the collection object and using its various methods such as Add . The property to access the collection object itself is read-only, and the collection itself is read-write.

Note that you use either the Items or the ItemsSource property to specify the collection that should be used to generate the content of your ItemsControl. When the ItemsSource property is set, the Items collection is made read-only and fixed-size.

When ItemsSource is in use, setting the ItemsSource property to null removes the collection and restores usage to Items, which will be an empty ItemCollection.

XAML Property Element Usage

XAML Values

OneOrMoreElements
One or more UIElement objects.

Items Control. Item Template Selector Свойство

Определение

Возвращает или задает пользовательскую логику для выбора шаблона, используемого для отображения каждого элемента. Gets or sets the custom logic for choosing a template used to display each item.

Читайте также:  Windows 10 2016 ltsb 2021

Значение свойства

Пользовательский объект DataTemplateSelector , который предоставляет логику и возвращает DataTemplate. A custom DataTemplateSelector object that provides logic and returns a DataTemplate. Значение по умолчанию — null . The default is null .

Примеры

В следующем примере auctionItemDataTemplateSelector имя ресурса (соответствующее AuctionItemDataTemplateSelector классу) назначается ItemTemplateSelector свойству объекта ItemsControl . In the following example, the auctionItemDataTemplateSelector resource name (corresponding to an AuctionItemDataTemplateSelector class) is assigned to the ItemTemplateSelector property of the ItemsControl.

В следующем примере показана реализация AuctionItemDataTemplateSelector класса с переопределением SelectTemplate метода: The following example shows the implementation of the AuctionItemDataTemplateSelector class with an override of the SelectTemplate method:

В этом случае в SelectTemplate методе класса есть логика для возврата соответствующего шаблона на основе значения SpecialFeatures свойства item переданного объекта. In this case, within the SelectTemplate method of the class, there is logic to return the appropriate template based on the value of the SpecialFeatures property of the item object passed. Возвращаемый шаблон находится в ресурсах Window элемента запечатывание. The template to return is found in the resources of the enveloping Window element.

При задании ItemTemplateSelector свойства ItemsControl направляется для автоматического вызова SelectTemplate метода AuctionItemDataTemplateSelector для каждого из элементов в коллекции, к которой ItemsControl привязан объект. When you set the ItemTemplateSelector property, the ItemsControl is directed to automatically call the SelectTemplate method of AuctionItemDataTemplateSelector for each of the items in the collection to which the ItemsControl is bound. Вызов передает элемент данных в виде объекта. The call passes the data item as an object. Объект DataTemplate , возвращаемый методом, используется для вывода этого элемента данных. The DataTemplate that is returned by the method is then used to display that data item.

Комментарии

Используйте ItemTemplate для указания визуализации объектов данных. You use the ItemTemplate to specify the visualization of the data objects. Если вы определили несколько шаблонов и хотите предоставить логику для возврата шаблона, используйте это свойство. If you have more than one template defined and want to supply logic to return a template to use, then you use this property. Обратите внимание, что это свойство игнорируется, если ItemTemplate задано значение. Note that this property is ignored if ItemTemplate is set.

ItemsControlПредоставляет большую гибкость для визуальной настройки и предоставляет множество свойств стилизации и шаблонов. The ItemsControl provides great flexibility for visual customization and provides many styling and templating properties. Используйте ItemContainerStyle свойство или свойство, ItemContainerStyleSelector чтобы задать стиль для изменения внешнего вида элементов, содержащих элементы данных. Use the ItemContainerStyle property or the ItemContainerStyleSelector property to set a style to affect the appearance of the elements that contain the data items. Например, для ListBox созданные контейнеры — это ListBoxItem элементы управления. для ComboBox , они являются ComboBoxItem элементами управления. For example, for ListBox, the generated containers are ListBoxItem controls; for ComboBox, they are ComboBoxItem controls. Чтобы изменить макет элементов, используйте ItemsPanel свойство. To affect the layout of the items, use the ItemsPanel property. Если вы используете группирование в элементе управления, можно использовать GroupStyle GroupStyleSelector свойство или. If you are using grouping on your control, you can use the GroupStyle or GroupStyleSelector property.

Дополнительные сведения см. в разделе Общие сведения о шаблонах данных. For more information, see Data Templating Overview.

Использование атрибута XAML XAML Attribute Usage

Значения XAML XAML Values

ресаурцеекстенсион ResourceExtension
Один из следующих элементов: StaticResource или DynamicResource . One of the following: StaticResource , or DynamicResource . Если сами стили не содержат ссылок на потенциальные ссылки времени выполнения, такие как системные ресурсы или пользовательские настройки, StaticResource для повышения производительности обычно рекомендуется использовать ссылку на стиль. Unless the styles themselves contain references to potential run-time references such as system resources or user preferences, StaticResource reference to a style is usually recommended for performance.

селекторресаурцекэй SelectorResourceKey
x:Key Строковое значение, ссылающееся на селектор, запрашиваемый в качестве ресурса. x:Key string value referring to the selector being requested as a resource.

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