Selecting items with windows

Выбор элементов из списка Selecting Items from a List Box

Используйте Windows PowerShell 3.0 и более поздние версии для создания диалогового окна, в котором пользователи могут выбирать элементы из списка. Use Windows PowerShell 3.0 and later releases to create a dialog box that lets users select items from a list box control.

Создание элемента управления «Список» и выбор элементов Create a list box control, and select items from it

Скопируйте и вставьте следующий код в интегрированную среду сценариев Windows PowerShell, а затем сохраните файл как сценарий Windows PowerShell (PS1-файл). Copy and then paste the following into Windows PowerShell ISE, and then save it as a Windows PowerShell script (.ps1).

Сценарий начинается с загрузки двух классов .NET Framework: System.Drawing и System.Windows.Forms. The script begins by loading two .NET Framework classes: System.Drawing and System.Windows.Forms. Затем вы запускаете новый экземпляр класса .NET Framework System.Windows.Forms.Form, предоставляющий пустую форму или окно, в которые можно добавить элементы управления. You then start a new instance of the .NET Framework class System.Windows.Forms.Form; that provides a blank form or window to which you can start adding controls.

После создания экземпляра класса «Форма» назначьте значения для трех свойств этого класса. After you create an instance of the Form class, assign values to three properties of this class.

Text. Text. Это будет заголовком окна. This becomes the title of the window.

Size. Size. Это размер формы в пикселях. This is the size of the form, in pixels. Предыдущий сценарий создает форму шириной 300 пикселей и высотой 200 пикселей. The preceding script creates a form that’s 300 pixels wide by 200 pixels tall.

StartingPosition. StartingPosition. Для этого дополнительного свойства задается значение CenterScreen в предыдущем сценарии. This optional property is set to CenterScreen in the preceding script. Если это свойство не добавлено, Windows выберет расположение после открытия формы. If you don’t add this property, Windows selects a location when the form is opened. Если для StartingPosition задать значение CenterScreen, форма будет автоматически отображаться в центре экрана при загрузке. By setting the StartingPosition to CenterScreen, you’re automatically displaying the form in the middle of the screen each time it loads.

Далее создайте кнопку для формы. Next, create an OK button for your form. Укажите размер и поведение кнопки ОК. Specify the size and behavior of the OK button. В этом примере кнопка расположена на 120 пикселей ниже верхней границы формы и на 75 пикселей правее левой границы. In this example, the button position is 120 pixels from the form’s top edge, and 75 pixels from the left edge. Высота кнопки — 23 пикселя, а длина — 75 пикселей. The button height is 23 pixels, while the button length is 75 pixels. Сценарий использует предопределенные типы Windows Forms для определения поведения кнопок. The script uses predefined Windows Forms types to determine the button behaviors.

Аналогичным образом создайте кнопку Отмена. Similarly, you create a Cancel button. Кнопка Отмена расположена на 120 пикселей ниже верхней границы и на 150 пикселей правее левой границы окна. The Cancel button is 120 pixels from the top, but 150 pixels from the left edge of the window.

Далее введите текст метки в окне, который должны получить пользователи. Next, provide label text on your window that describes the information you want users to provide. В данном случае пользователям необходимо выбрать компьютер. In this case, you want users to select a computer.

Читайте также:  Установка wine linux kali linux

Добавьте элемент управления (в данном случае список), который позволит пользователям указать сведения, описанные в тексте метки. Add the control (in this case, a list box) that lets users provide the information you’ve described in your label text. Помимо списка существует много других элементов управления, которые можно применить. Их описание см. в статье Пространство имен System.Windows.Forms. There are many other controls you can apply besides list boxes; for more controls, see System.Windows.Forms Namespace.

В следующем разделе необходимо указать значения списка, которые должны отображаться пользователям. In the next section, you specify the values you want the list box to display to users.

Список, созданный этим сценарием, позволяет выбрать только один вариант. The list box created by this script allows only one selection. Чтобы создать список, допускающий множественный выбор, укажите для свойства SelectionMode значение, аналогичное следующему: $listBox.SelectionMode = ‘MultiExtended’ . To create a list box control that allows multiple selections, specify a value for the SelectionMode property, similarly to the following: $listBox.SelectionMode = ‘MultiExtended’ . Дополнительные сведения см. в статье Списки с множественным выбором. For more information, see Multiple-selection List Boxes.

Добавьте список в форму и настройте его так, чтобы он открывался в Windows поверх других диалоговых окон. Add the list box control to your form, and instruct Windows to open the form atop other windows and dialog boxes when it’s opened.

Добавьте следующую строку кода для отображения формы в Windows. Add the following line of code to display the form in Windows.

Наконец, код внутри блока If указывает Windows, что следует делать с формой после того, как пользователь выберет параметр из списка и нажмет кнопку ОК или клавишу ВВОД. Finally, the code inside the If block instructs Windows what to do with the form after users select an option from the list box, and then click the OK button or press the Enter key.

List Box. Selected Item Свойство

Определение

Получает или задает выбранный в настоящий момент элемент в поле со списком ListBox. Gets or sets the currently selected item in the ListBox.

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

Объект, представляющий текущую выбранную позицию в элементе управления. An object that represents the current selection in the control.

Примеры

В следующем примере кода показано, как использовать SelectedIndexChanged событие для поиска и выбора элемента в другом ListBox элементе управления. The following code example demonstrates how to use the SelectedIndexChanged event to search for and select an item in a different ListBox control. В примере с помощью SelectedIndexChanged события определяется, когда изменяется выбранный элемент в ListBox . The example uses the SelectedIndexChanged event to determine when the selected item in the ListBox is changed. Затем пример кода считывает текст элемента с помощью SelectedItem Свойства и вызывает FindString метод для другого, ListBox используя текст, возвращенный SelectedItem в первом ListBox . The example code then reads the text of the item using the SelectedItem property and calls the FindString method on a different ListBox using the text returned by SelectedItem in the first ListBox. Если элемент найден в другом элементе, он ListBox выбирается. If an item is found in the other ListBox, the item is selected. В этом примере необходимо, ListBox listBox1 чтобы в форму были добавлены два элемента управления с именами и listBox2 , а оба ListBox элемента управления содержат одинаковые элементы. This example requires that two ListBox controls, named listBox1 and listBox2 , have been added to a form and that both ListBox controls contain items that are identical. В этом примере также требуется, чтобы метод обработки событий, определенный в примере, был подключен к SelectedIndexChanged событию listBox1 . The example also requires that the event-handling method defined in the example is connected to the SelectedIndexChanged event of listBox1 .

Читайте также:  Windows 10 домашняя пароль домашней группы

Комментарии

Для стандартного ListBox можно использовать это свойство, чтобы определить, какой элемент выбран в ListBox . For a standard ListBox, you can use this property to determine which item is selected in the ListBox. Если SelectionMode свойство объекта ListBox установлено в значение SelectionMode.MultiSimple или SelectionMode.MultiExtended (которое указывает на множественный выбор ListBox ) и в списке выбрано несколько элементов, это свойство может возвращать любой выбранный элемент. If the SelectionMode property of the ListBox is set to either SelectionMode.MultiSimple or SelectionMode.MultiExtended (which indicates a multiple-selection ListBox) and multiple items are selected in the list, this property can return any selected item.

Чтобы получить коллекцию, содержащую все выбранные элементы множественного выбора ListBox , используйте SelectedItems свойство. To retrieve a collection containing all selected items in a multiple-selection ListBox, use the SelectedItems property. Если требуется получить позицию индекса текущего выбранного элемента в ListBox , используйте SelectedIndex свойство. If you want to obtain the index position of the currently selected item in the ListBox, use the SelectedIndex property. Кроме того, можно использовать SelectedIndices свойство для получения всех выбранных индексов в множественном выборе ListBox . In addition, you can use the SelectedIndices property to obtain all the selected indexes in a multiple-selection ListBox.

question

Selecting, deselecting ListView items by code. and manually

Working with a list of about 50,000 items, I must be able to select/deselect items code behind.

I first tried to achieve this through UI. For instance, to deselect a selection:

Since I was naturally using virtualization, I had to pass by the ItemContainerGenerator, so the code was more:

The problem is that when UI virtualization is enabled for the ListView, the ItemContainerGenerator methods will return null for items that are not currently visible. This happens because the corresponding ListViewItem has not yet been created.
(That said, I wonder how the Listview SelectAll() and UnselectAll() methods do! Because they do work perfectly with virtualization!!)

Anyway! I then decided to rather handle the selection by adding a IsSelected property to my object. then bind the IsSelect from the ListViewItem to that property.
. and this just worked fine!

The problem:
The problem arises when I want to ‘mix’ code behind selection with ‘manual’ selection.
In the following clip, one can see how, after having done a selection code behind, then adding a selection manually (using the Ctrl/Shift combination from Windows) then attempting to invert the selection, the elements selected manually. stay selected!

Here I am..I can’t see what is to be done now. could you please help?
Here is the whole code used for this example

List Box. Selection Mode Свойство

Определение

Получает или задает метод выбора компонентов в элементе управления ListBox. Gets or sets the method in which items are selected in the ListBox.

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

Одно из значений перечисления SelectionMode. One of the SelectionMode values. Значение по умолчанию — SelectionMode.One . The default is SelectionMode.One .

Исключения

Присваиваемое значение не относится к значениям SelectionMode. The assigned value is not one of the SelectionMode values.

Примеры

В следующем примере кода показано, как с помощью GetSelected метода определить, какие элементы в ListBox выбраны, чтобы выбрать элементы, которые не выбраны, и отменить выбор выбранных элементов. The following code example demonstrates how to use the GetSelected method to determine which items in a ListBox are selected in order to select the items that are not selected and deselect the items that are selected. В этом примере также демонстрируется использование SelectionMode свойства для включения ListBox в для нескольких выбранных элементов и использования Sorted свойства для демонстрации автоматического упорядочения элементов ListBox . The example also demonstrates using the SelectionMode property to enable a ListBox to have more than one selected item and uses the Sorted property to demonstrate how to sort items in a ListBox automatically. В этом примере требуется ListBox , чтобы в listBox1 форму был добавлен объект с именем, а метод, InitializeMyListBox определенный в примере, вызывался из Load события формы. This example requires that a ListBox, named listBox1 , has been added to a form and that the InitializeMyListBox method defined in the example is called from the Load event of the form.

Читайте также:  Как определить подходящий windows

Selecting Items from a List Box

Use Windows PowerShell 3.0 and later releases to create a dialog box that lets users select items from a list box control.

Create a list box control, and select items from it

Copy and then paste the following into Windows PowerShell ISE, and then save it as a Windows PowerShell script (.ps1).

The script begins by loading two .NET Framework classes: System.Drawing and System.Windows.Forms. You then start a new instance of the .NET Framework class System.Windows.Forms.Form; that provides a blank form or window to which you can start adding controls.

After you create an instance of the Form class, assign values to three properties of this class.

Text. This becomes the title of the window.

Size. This is the size of the form, in pixels. The preceding script creates a form that’s 300 pixels wide by 200 pixels tall.

StartingPosition. This optional property is set to CenterScreen in the preceding script. If you don’t add this property, Windows selects a location when the form is opened. By setting the StartingPosition to CenterScreen, you’re automatically displaying the form in the middle of the screen each time it loads.

Next, create an OK button for your form. Specify the size and behavior of the OK button. In this example, the button position is 120 pixels from the form’s top edge, and 75 pixels from the left edge. The button height is 23 pixels, while the button length is 75 pixels. The script uses predefined Windows Forms types to determine the button behaviors.

Similarly, you create a Cancel button. The Cancel button is 120 pixels from the top, but 150 pixels from the left edge of the window.

Next, provide label text on your window that describes the information you want users to provide. In this case, you want users to select a computer.

Add the control (in this case, a list box) that lets users provide the information you’ve described in your label text. There are many other controls you can apply besides list boxes; for more controls, see System.Windows.Forms Namespace.

In the next section, you specify the values you want the list box to display to users.

The list box created by this script allows only one selection. To create a list box control that allows multiple selections, specify a value for the SelectionMode property, similarly to the following: $listBox.SelectionMode = ‘MultiExtended’ . For more information, see Multiple-selection List Boxes.

Add the list box control to your form, and instruct Windows to open the form atop other windows and dialog boxes when it’s opened.

Add the following line of code to display the form in Windows.

Finally, the code inside the If block instructs Windows what to do with the form after users select an option from the list box, and then click the OK button or press the Enter key.

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