- Практическое руководство. Поиск элемента TreeViewItem в TreeView How to: Find a TreeViewItem in a TreeView
- Пример Example
- Описание Description
- Код Code
- Обзор элемента управления «TreeView» TreeView Overview
- Что такое элемент управления TreeView? What Is a TreeView?
- Создание элемента управления TreeView Creating a TreeView
- Развертывание и свертывание элемента TreeViewItem Expanding and Collapsing a TreeViewItem
- Выбор элемента TreeViewItem TreeViewItem Selection
- Стиль элемента управления TreeView TreeView Style
- Добавление изображений и другого содержимого в элемент управления TreeView Adding Images and Other Content to TreeView Items
- TreeViewItem Class
- Inheritance Hierarchy
- Syntax
- XAML Values
- Constructors
- Properties
- Methods
- Events
- Fields
- Remarks
- Customizing the TreeViewItem Control
Практическое руководство. Поиск элемента TreeViewItem в TreeView How to: Find a TreeViewItem in a TreeView
TreeViewЭлемент управления предоставляет удобный способ для показа иерархических данных. The TreeView control provides a convenient way to display hierarchical data. Если TreeView Привязка привязана к источнику данных, это SelectedItem свойство предоставляет удобный способ быстрого извлечения выбранного объекта данных. If your TreeView is bound to a data source, the SelectedItem property provides a convenient way for you to quickly retrieve the selected data object. Обычно лучше работать с базовым объектом данных, но иногда может потребоваться программно манипулировать содержащимся в нем данным TreeViewItem . It is typically best to work with the underlying data object, but sometimes you may need to programmatically manipulate the data’s containing TreeViewItem. Например, может потребоваться программное расширение TreeViewItem или выбор другого элемента в TreeView . For example, you may need to programmatically expand the TreeViewItem, or select a different item in the TreeView.
Для поиска TreeViewItem объекта, содержащего конкретный объект данных, необходимо пройти по каждому уровню TreeView . To find a TreeViewItem that contains a specific data object, you must traverse each level of the TreeView. Элементы в TreeView можно также виртуализованы для повышения производительности. The items in a TreeView can also be virtualized to improve performance. В случае, когда элементы могут быть виртуализированы, необходимо также реализовать, TreeViewItem чтобы проверить, содержит ли он объект данных. In the case where items might be virtualized, you also must realize a TreeViewItem to check whether it contains the data object.
Пример Example
Описание Description
В следующем примере выполняется поиск TreeView определенного объекта и возвращается объект, содержащий TreeViewItem . The following example searches a TreeView for a specific object and returns the object’s containing TreeViewItem. В этом примере TreeViewItem создается экземпляр каждого экземпляра, чтобы можно было выполнять поиск его дочерних элементов. The example ensures that each TreeViewItem is instantiated so that its child items can be searched. Этот пример также работает, если не TreeView использует виртуализированные элементы. This example also works if the TreeView does not use virtualized items.
Следующий пример работает для любого TreeView , независимо от базовой модели данных, и ищет все TreeViewItem объекты до тех пор, пока объект не будет найден. The following example works for any TreeView, regardless of the underlying data model, and searches every TreeViewItem until the object is found. Другой способ, имеющий лучшую производительность, — поиск в модели данных указанного объекта, отслеживание его расположения в иерархии данных, а затем поиск соответствующего элемента TreeViewItem в TreeView . Another technique that has better performance is to search the data model for the specified object, keep track of its location within the data hierarchy, and then find the corresponding TreeViewItem in the TreeView. Однако метод, имеющий лучшую производительность, требует знания модели данных и не может быть обобщен для всех указанных TreeView . However, the technique that has better performance requires knowledge of the data model and cannot be generalized for any given TreeView.
Код Code
Предыдущий код полагается на пользовательский объект VirtualizingStackPanel , предоставляющий метод с именем BringIntoView . The previous code relies on a custom VirtualizingStackPanel that exposes a method named BringIntoView . Следующий код определяет пользовательский объект VirtualizingStackPanel . The following code defines the custom VirtualizingStackPanel.
В следующем коде XAML показано, как создать объект TreeView , использующий пользовательский VirtualizingStackPanel . The following XAML shows how to create a TreeView that uses the custom VirtualizingStackPanel.
Обзор элемента управления «TreeView» TreeView Overview
TreeViewЭлемент управления позволяет отображать сведения в иерархической структуре с помощью свертываемых узлов. The TreeView control provides a way to display information in a hierarchical structure by using collapsible nodes. В этом разделе описываются TreeView TreeViewItem элементы управления и, а также приводятся простые примеры их использования. This topic introduces the TreeView and TreeViewItem controls, and provides simple examples of their use.
Что такое элемент управления TreeView? What Is a TreeView?
TreeView — Это объект ItemsControl , который вкладывает элементы с помощью TreeViewItem элементов управления. TreeView is an ItemsControl that nests the items by using TreeViewItem controls. В следующем примере создается объект TreeView . The following example creates a TreeView.
Создание элемента управления TreeView Creating a TreeView
TreeViewЭлемент управления содержит иерархию TreeViewItem элементов управления. The TreeView control contains a hierarchy of TreeViewItem controls. TreeViewItemЭлемент управления — это объект HeaderedItemsControl , который содержит Header коллекцию и Items . A TreeViewItem control is a HeaderedItemsControl that has a Header and an Items collection.
При определении с помощью служб TreeView Язык XAML Extensible Application Markup Language (XAML) можно явно определить Header содержимое TreeViewItem элемента управления и элементы, составляющие его коллекцию. If you are defining a TreeView by using Язык XAML Extensible Application Markup Language (XAML) , you can explicitly define the Header content of a TreeViewItem control and the items that make up its collection. Этот способ был показан на предыдущем рисунке. The previous illustration demonstrates this method.
Можно также указать в ItemsSource качестве источника данных, а затем указать HeaderTemplate и ItemTemplate для определения TreeViewItem содержимого. You can also specify an ItemsSource as a data source and then specify a HeaderTemplate and ItemTemplate to define the TreeViewItem content.
Чтобы определить макет TreeViewItem элемента управления, можно также использовать HierarchicalDataTemplate объекты. To define the layout of a TreeViewItem control, you can also use HierarchicalDataTemplate objects. Дополнительные сведения и пример см. в разделе Использование свойств SelectedValue, SelectedValuePath и SelectedItem. For more information and an example, see Use SelectedValue, SelectedValuePath, and SelectedItem.
Если элемент не является TreeViewItem элементом управления, он автоматически заключается в TreeViewItem элемент управления при TreeView отображении элемента управления. If an item is not a TreeViewItem control, it is automatically enclosed by a TreeViewItem control when the TreeView control is displayed.
Развертывание и свертывание элемента TreeViewItem Expanding and Collapsing a TreeViewItem
Если пользователь расширяет TreeViewItem , свойство устанавливается в значение IsExpanded true . If the user expands a TreeViewItem, the IsExpanded property is set to true . Можно также развернуть или свернуть TreeViewItem без прямого вмешательства пользователя, задав IsExpanded для свойства значение true (развернуть) или false (свернуть). You can also expand or collapse a TreeViewItem without any direct user action by setting the IsExpanded property to true (expand) or false (collapse). При изменении этого свойства Expanded Collapsed возникает событие или. When this property changes, an Expanded or Collapsed event occurs.
При BringIntoView вызове метода для TreeViewItem элемента управления, TreeViewItem и его родительские TreeViewItem элементы управления расширяются. When the BringIntoView method is called on a TreeViewItem control, the TreeViewItem and its parent TreeViewItem controls expand. Если объект TreeViewItem не является видимым или частично видимым, элемент TreeView прокручивается, чтобы сделать его видимым. If a TreeViewItem is not visible or partially visible, the TreeView scrolls to make it visible.
Выбор элемента TreeViewItem TreeViewItem Selection
Когда пользователь щелкает TreeViewItem элемент управления для его выбора, Selected возникает событие, и его IsSelected свойство имеет значение true . When a user clicks a TreeViewItem control to select it, the Selected event occurs, and its IsSelected property is set to true . Объект TreeViewItem также превращается в SelectedItem TreeView элемент управления. The TreeViewItem also becomes the SelectedItem of the TreeView control. И наоборот, когда выбор изменяется из TreeViewItem элемента управления, Unselected происходит его событие, а его IsSelected свойство имеет значение false . Conversely, when the selection changes from a TreeViewItem control, its Unselected event occurs and its IsSelected property is set to false .
SelectedItemСвойство TreeView элемента управления является свойством только для чтения, поэтому его нельзя задать явным образом. The SelectedItem property on the TreeView control is a read-only property; hence, you cannot explicitly set it. SelectedItemСвойство задается, если пользователь щелкает TreeViewItem элемент управления или если IsSelected свойство имеет значение true в TreeViewItem элементе управления. The SelectedItem property is set if the user clicks on a TreeViewItem control or when the IsSelected property is set to true on the TreeViewItem control.
Можно зарегистрировать обработчик событий для SelectedItemChanged события, чтобы определить, когда выбрано TreeViewItem изменение. You can register an event handler on the SelectedItemChanged event in order to determine when a selected TreeViewItem changes. Объект, RoutedPropertyChangedEventArgs предоставляемый обработчику событий, задает объект OldValue , который является предыдущим выделением, и объект NewValue , который является текущим выделением. The RoutedPropertyChangedEventArgs that is provided to the event handler specifies the OldValue, which is the previous selection, and the NewValue, which is the current selection. Каждое из этих значений может быть равно null , если ни предыдущий, ни текущий выбор не были сделаны ни пользователем, ни в приложении. Either value can be null if the application or user has not made a previous or current selection.
Стиль элемента управления TreeView TreeView Style
Стиль по умолчанию для TreeView элемента управления помещает его внутрь StackPanel объекта, содержащего ScrollViewer элемент управления. The default style for a TreeView control places it inside a StackPanel object that contains a ScrollViewer control. При задании Width свойств и Height для TreeView , эти значения используются для изменения размера StackPanel объекта, который отображает TreeView . When you set the Width and Height properties for a TreeView, these values are used to size the StackPanel object that displays the TreeView. Если отображаемое содержимое больше, чем область отображения, ScrollViewer автоматически отображается, чтобы пользователь мог прокручивать TreeView содержимое. If the content to display is larger than the display area, a ScrollViewer automatically displays so that the user can scroll through the TreeView content.
Чтобы настроить внешний вид TreeViewItem элемента управления, присвойте Style свойству значение Custom Style . To customize the appearance of a TreeViewItem control, set the Style property to a custom Style.
В следующем примере показано, как задать Foreground FontSize значения свойств и для TreeViewItem элемента управления с помощью Style . The following example shows how to set the Foreground and FontSize property values for a TreeViewItem control by using a Style.
Добавление изображений и другого содержимого в элемент управления TreeView Adding Images and Other Content to TreeView Items
В содержимое можно включить более одного объекта Header TreeViewItem . You can include more than one object in the Header content of a TreeViewItem. Чтобы включить в содержимое несколько объектов Header , заключите эти объекты в элемент управления макет, например Panel или StackPanel . To include multiple objects in Header content, enclose the objects inside a layout control, such as a Panel or StackPanel.
В следующем примере показано, как определить объект Header TreeViewItem как CheckBox и TextBlock , заключенный в DockPanel элемент управления. The following example shows how to define the Header of a TreeViewItem as a CheckBox and TextBlock that are both enclosed in a DockPanel control.
В следующем примере показано, как определить объект DataTemplate , содержащий объект Image и TextBlock , который заключен в DockPanel элемент управления. The following example shows how to define a DataTemplate that contains an Image and a TextBlock that are enclosed in a DockPanel control. Можно использовать DataTemplate для задания HeaderTemplate или ItemTemplate для TreeViewItem . You can use a DataTemplate to set the HeaderTemplate or ItemTemplate for a TreeViewItem.
TreeViewItem Class
Microsoft Silverlight will reach end of support after October 2021. Learn more.
Provides a hierarchical selectable item for the TreeView control.
Inheritance Hierarchy
Namespace: В System.Windows.Controls
Assembly: В System.Windows.Controls (in System.Windows.Controls.dll)
Syntax
XAML Values
- content
A single object element that serves as content.
The TreeViewItem type exposes the following members.
Constructors
В | Name | Description |
---|---|---|
TreeViewItem | Initializes a new instance of the TreeViewItem class. |
Properties
В | Name | Description |
---|---|---|
ActualHeight | Gets the rendered height of a FrameworkElement. (Inherited from FrameworkElement.) | |
ActualWidth | Gets the rendered width of a FrameworkElement. (Inherited from FrameworkElement.) | |
AllowDrop | Gets or sets a value that determines whether this UIElement can be a drop target for purposes of Silverlight drag-and-drop operations. (Inherited from UIElement.) | |
Background | Gets or sets a brush that provides the background of the control. (Inherited from Control.) | |
BorderBrush | Gets or sets a brush that describes the border background of a control. (Inherited from Control.) | |
BorderThickness | Gets or sets the border thickness of a control. (Inherited from Control.) | |
CacheMode | Gets or sets a value that indicates that rendered content should be cached when possible. (Inherited from UIElement.) | |
CharacterSpacing | Gets or sets the distance between characters of text in the control measured in 1000ths of the font size. (Inherited from Control.) | |
Clip | Gets or sets the Geometry used to define the outline of the contents of a UIElement. (Inherited from UIElement.) | |
Cursor | Gets or sets the cursor image that displays while the mouse pointer is over a FrameworkElement. (Inherited from FrameworkElement.) | |
DataContext | Gets or sets the data context for a FrameworkElement when it participates in data binding. (Inherited from FrameworkElement.) | |
DefaultStyleKey | Gets or sets the key that references the default style for the control. (Inherited from Control.) | |
DesiredSize | Gets the size that this UIElement computed during the measure pass of the layout process. (Inherited from UIElement.) | |
Dispatcher | Gets the Dispatcher this object is associated with. (Inherited from DependencyObject.) | |
DisplayMemberPath | Gets or sets the name or path of the property that is displayed for each data item. (Inherited from ItemsControl.) | |
Effect | Gets or sets the pixel shader effect to use for rendering this UIElement. (Inherited from UIElement.) | |
FlowDirection | Gets or sets the direction that text and other user interface elements flow within any parent element that controls their layout. (Inherited from FrameworkElement.) | |
FontFamily | Gets or sets the font used to display text in the control. (Inherited from Control.) | |
FontSize | Gets or sets the size of the text in this control. (Inherited from Control.) | |
FontStretch | Gets or sets the degree to which a font is condensed or expanded on the screen. (Inherited from Control.) | |
FontStyle | Gets or sets the style in which the text is rendered. (Inherited from Control.) | |
FontWeight | Gets or sets the thickness of the specified font. (Inherited from Control.) | |
Foreground | Gets or sets a brush that describes the foreground color. (Inherited from Control.) | |
HasItems | Gets a value that indicates whether this TreeViewItem contains items. | |
Header | Gets or sets the item that labels the control. (Inherited from HeaderedItemsControl.) | |
HeaderTemplate | Gets or sets a data template that is used to display the contents of the control’s Header. (Inherited from HeaderedItemsControl.) | |
Height | Gets or sets the suggested height of a FrameworkElement. (Inherited from FrameworkElement.) | |
HorizontalAlignment | Gets or sets the horizontal alignment characteristics that are applied to a FrameworkElement when it is composed in a layout parent, such as a panel or items control. (Inherited from FrameworkElement.) | |
HorizontalContentAlignment | Gets or sets the horizontal alignment of the control’s content. (Inherited from Control.) | |
IsEnabled | Gets or sets a value indicating whether the user can interact with the control. (Inherited from Control.) | |
IsExpanded | Gets or sets a value that indicates whether the Items contained by this TreeViewItem are expanded or collapsed. | |
IsHitTestVisible | Gets or sets whether the contained area of this UIElement can return true values for hit testing. (Inherited from UIElement.) | |
IsSelected | Gets or sets a value that indicates whether this TreeViewItem is selected. | |
IsSelectionActive | Gets a value that indicates whether the TreeViewItem has focus. | |
IsTabStop | Gets or sets a value that indicates whether a control is included in tab navigation. (Inherited from Control.) | |
ItemContainerGenerator | Gets the ItemContainerGenerator associated with this ItemsControl. (Inherited from ItemsControl.) | |
ItemContainerStyle | Gets or sets the Style that is applied to the container element generated for each item. (Inherited from HeaderedItemsControl.) | |
Items | Gets the collection used to generate the content of the control. (Inherited from ItemsControl.) | |
ItemsPanel | Gets or sets the template that defines the panel that controls the layout of items. (Inherited from ItemsControl.) | |
ItemsSource | Gets or sets a collection used to generate the content of the ItemsControl. (Inherited from ItemsControl.) | |
ItemTemplate | Gets or sets the DataTemplate used to display each item. (Inherited from ItemsControl.) | |
Language | Gets or sets localization/globalization language information that applies to a FrameworkElement. (Inherited from FrameworkElement.) | |
Margin | Gets or sets the outer margin of a FrameworkElement. (Inherited from FrameworkElement.) | |
MaxHeight | Gets or sets the maximum height constraint of a FrameworkElement. (Inherited from FrameworkElement.) | |
MaxWidth | Gets or sets the maximum width constraint of a FrameworkElement. (Inherited from FrameworkElement.) | |
MinHeight | Gets or sets the minimum height constraint of a FrameworkElement. (Inherited from FrameworkElement.) | |
MinWidth | Gets or sets the minimum width constraint of a FrameworkElement. (Inherited from FrameworkElement.) | |
Name | Gets or sets the identifying name of the object. When a XAML processor creates the object tree from XAML markup, run-time code can refer to the XAML-declared object by this name. (Inherited from FrameworkElement.) | |
Opacity | Gets or sets the degree of the object’s opacity. (Inherited from UIElement.) | |
OpacityMask | Gets or sets the brush used to alter the opacity of regions of this object. (Inherited from UIElement.) | |
Padding | Gets or sets the padding inside a control. (Inherited from Control.) | |
Parent | Gets the parent object of this FrameworkElement in the object tree. (Inherited from FrameworkElement.) | |
Projection | Gets or sets the perspective projection (3-D effect) to apply when rendering this UIElement. (Inherited from UIElement.) | |
RenderSize | Gets the final render size of a UIElement. (Inherited from UIElement.) | |
RenderTransform | Gets or sets transform information that affects the rendering position of a UIElement. (Inherited from UIElement.) | |
RenderTransformOrigin | Gets or sets the origin point of any possible render transform declared by RenderTransform, relative to the bounds of the UIElement. (Inherited from UIElement.) | |
Resources | Gets the locally defined resource dictionary. In XAML, you can establish resource items as child object elements of a frameworkElement.Resources property element, through XAML implicit collection syntax. (Inherited from FrameworkElement.) | |
Style | Gets or sets an instance Style that is applied for this object during rendering. (Inherited from FrameworkElement.) | |
TabIndex | Gets or sets a value that determines the order in which elements receive focus when the user navigates through controls by using the TAB key. (Inherited from Control.) | |
TabNavigation | Gets or sets a value that modifies how tabbing and TabIndex work for this control. (Inherited from Control.) | |
Tag | Gets or sets an arbitrary object value that can be used to store custom information about this object. (Inherited from FrameworkElement.) | |
Template | Gets or sets a control template. (Inherited from Control.) | |
Triggers | Gets the collection of triggers for animations that are defined for a FrameworkElement. (Inherited from FrameworkElement.) | |
UseLayoutRounding | Gets or sets a value that determines whether rendering for the object and its visual subtree should use rounding behavior that aligns rendering to whole pixels. (Inherited from UIElement.) | |
VerticalAlignment | Gets or sets the vertical alignment characteristics that are applied to a FrameworkElement when it is composed in a parent object such as a panel or items control. (Inherited from FrameworkElement.) | |
VerticalContentAlignment | Gets or sets the vertical alignment of the control’s content. (Inherited from Control.) | |
Visibility | Gets or sets the visibility of a UIElement. A UIElement that is not visible does not render and does not communicate its desired size to layout. (Inherited from UIElement.) | |
Width | Gets or sets the width of a FrameworkElement. (Inherited from FrameworkElement.) |
Methods
В | Name | Description |
---|---|---|
AddHandler | Adds a routed event handler for a specified routed event, adding the handler to the handler collection on the current element. Specify handledEventsToo as true to have the provided handler be invoked for routed event that had already been marked as handled by another element along the event route. (Inherited from UIElement.) | |
ApplyTemplate | Loads the relevant control template so that its parts can be referenced. (Inherited from Control.) | |
Arrange | Positions child objects and determines a size for a UIElement. Parent objects that implement custom layout for their child elements should call this method from their layout override implementations to form a recursive layout update. (Inherited from UIElement.) | |
ArrangeOverride | Provides the behavior for the Arrange pass of Silverlight layout. Classes can override this method to define their own Arrange pass behavior. (Inherited from FrameworkElement.) | |
CaptureMouse | Sets mouse capture to a UIElement. (Inherited from UIElement.) | |
CheckAccess | Determines whether the calling thread has access to this object. (Inherited from DependencyObject.) | |
ClearContainerForItemOverride | Removes all templates, styles, and bindings for the object displayed as a TreeViewItem. (Overrides ItemsControl.ClearContainerForItemOverride(DependencyObject, Object).) | |
ClearValue | Clears the local value of a dependency property. (Inherited from DependencyObject.) | |
Equals(Object) | Determines whether the specified Object is equal to the current Object. (Inherited from Object.) | |
Finalize | Allows an object to try to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.) | |
FindName | Retrieves an object that has the specified identifier name. (Inherited from FrameworkElement.) | |
Focus | Attempts to set the focus on the control. (Inherited from Control.) | |
GetAnimationBaseValue | Returns any base value established for a Silverlight dependency property, which would apply in cases where an animation is not active. (Inherited from DependencyObject.) | |
GetBindingExpression | Retrieves the BindingExpression for a dependency property where a binding is established. (Inherited from FrameworkElement.) | |
GetContainerForItemOverride | Creates a TreeViewItem to display content. (Overrides ItemsControl.GetContainerForItemOverride().) | |
GetHashCode | Serves as a hash function for a particular type. (Inherited from Object.) | |
GetTemplateChild | Retrieves the named element in the instantiated ControlTemplate visual tree. (Inherited from Control.) | |
GetType | Gets the Type of the current instance. (Inherited from Object.) | |
GetValue | Returns the current effective value of a dependency property from a DependencyObject. (Inherited from DependencyObject.) | |
InvalidateArrange | Invalidates the arrange state (layout) for a UIElement. After the invalidation, the UIElement will have its layout updated, which will occur asynchronously. (Inherited from UIElement.) | |
InvalidateMeasure | Invalidates the measurement state (layout) for a UIElement. (Inherited from UIElement.) | |
IsItemItsOwnContainerOverride | Determines whether an object is a TreeViewItem. (Overrides ItemsControl.IsItemItsOwnContainerOverride(Object).) | |
Measure | Updates the DesiredSize of a UIElement. Typically, objects that implement custom layout for their layout children call this method from their own MeasureOverride implementations to form a recursive layout update. (Inherited from UIElement.) | |
MeasureOverride | Provides the behavior for the Measure pass of Silverlight layout. Classes can override this method to define their own Measure pass behavior. (Inherited from FrameworkElement.) | |
MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.) | |
OnApplyTemplate | Builds the visual tree for the TreeViewItem control when a new control template is applied. (Overrides HeaderedItemsControl.OnApplyTemplate().) | |
OnCollapsed | Raises a Collapsed event when the IsExpanded property changes from true to false. | |
OnCreateAutomationPeer | Returns a TreeViewItemAutomationPeer for use by the Silverlight automation infrastructure. (Overrides UIElement.OnCreateAutomationPeer().) | |
OnDragEnter | Called before the DragEnter event occurs. (Inherited from Control.) | |
OnDragLeave | Called before the DragLeave event occurs. (Inherited from Control.) | |
OnDragOver | Called before the DragOver event occurs. (Inherited from Control.) | |
OnDrop | Called before the Drop event occurs. (Inherited from Control.) | |
OnExpanded | Raises an Expanded event when the IsExpanded property changes from false to true. | |
OnGotFocus | Provides handling for the GotFocus event. (Overrides Control.OnGotFocus(RoutedEventArgs).) | |
OnHeaderChanged | Called when the value of the Header property changes. (Inherited from HeaderedItemsControl.) | |
OnHeaderTemplateChanged | Called when the value of the HeaderTemplate property changes. (Inherited from HeaderedItemsControl.) | |
OnItemsChanged | Makes adjustments to the TreeViewItem when the value of the Items property changes. (Overrides ItemsControl.OnItemsChanged(NotifyCollectionChangedEventArgs).) | |
OnKeyDown | Provides handling for the KeyDown event when the TreeViewItem has focus. (Overrides Control.OnKeyDown(KeyEventArgs).) | |
OnKeyUp | Provides handling for the KeyUp event. (Overrides Control.OnKeyUp(KeyEventArgs).) | |
OnLostFocus | Provides handling for the LostFocus event. (Overrides Control.OnLostFocus(RoutedEventArgs).) | |
OnLostMouseCapture | Called before the LostMouseCapture event occurs to provide handling for the event in a derived class without attaching a delegate. (Inherited from Control.) | |
OnMouseEnter | Provides handling for the MouseEnter event. (Overrides Control.OnMouseEnter(MouseEventArgs).) | |
OnMouseLeave | Provides handling for the MouseLeave event. (Overrides Control.OnMouseLeave(MouseEventArgs).) | |
OnMouseLeftButtonDown | Provides handling for the MouseLeftButtonDown event. (Overrides Control.OnMouseLeftButtonDown(MouseButtonEventArgs).) | |
OnMouseLeftButtonUp | Provides handling for the MouseLeftButtonUp event. (Overrides Control.OnMouseLeftButtonUp(MouseButtonEventArgs).) | |
OnMouseMove | Called before the MouseMove event occurs. (Inherited from Control.) | |
OnMouseRightButtonDown | Called before the MouseRightButtonDown event occurs. (Inherited from Control.) | |
OnMouseRightButtonUp | Called before the MouseRightButtonUp event occurs. (Inherited from Control.) | |
OnMouseWheel | Called before the MouseWheel event occurs to provide handling for the event in a derived class without attaching a delegate. (Inherited from Control.) | |
OnSelected | Raises the Selected event when the IsSelected property changes from false to true. | |
OnTextInput | Called before the TextInput event occurs. (Inherited from ItemsControl.) | |
OnTextInputStart | Called before the TextInputStart event occurs. (Inherited from Control.) | |
OnTextInputUpdate | Called before the TextInputUpdate event occurs. (Inherited from Control.) | |
OnUnselected | Raises the Unselected event when the IsSelected property changes from true to false. | |
PrepareContainerForItemOverride | Prepares the specified container element to display the specified item. (Overrides HeaderedItemsControl.PrepareContainerForItemOverride(DependencyObject, Object).) | |
ReadLocalValue | Returns the local value of a dependency property, if a local value is set. (Inherited from DependencyObject.) | |
ReleaseMouseCapture | Removes mouse capture from a UIElement. After this call, typically no object holds mouse capture. (Inherited from UIElement.) | |
RemoveHandler | Removes the specified routed event handler from this UIElement. (Inherited from UIElement.) | |
SetBinding | Attaches a binding to a FrameworkElement, using the provided binding object, and returns a BindingExpressionBase for possible later use. (Inherited from FrameworkElement.) | |
SetValue | Sets the local value of a dependency property on a DependencyObject. (Inherited from DependencyObject.) | |
ToString | Returns a string that represents the current object. (Inherited from Object.) | |
TransformToVisual | Returns a transform object that can be used to transform coordinates from the UIElement to the specified object. (Inherited from UIElement.) | |
UpdateLayout | Ensures that all positions of child objects of a UIElement are properly updated for layout. (Inherited from UIElement.) |
Events
В | Name | Description |
---|---|---|
BindingValidationError | Occurs when a data validation error is reported by a binding source. (Inherited from FrameworkElement.) | |
Collapsed | Occurs when the IsExpanded property changes from true to false. | |
DataContextChanged | Occurs when the data context for this element changes. (Inherited from FrameworkElement.) | |
DragEnter | Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement.) | |
DragLeave | Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement.) | |
DragOver | Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement.) | |
Drop | Occurs when the input system reports an underlying drop event with this element as the drop target. (Inherited from UIElement.) | |
Expanded | Occurs when the IsExpanded property changes from false to true. | |
GotFocus | Occurs when a UIElement receives focus. (Inherited from UIElement.) | |
IsEnabledChanged | Occurs when the IsEnabled property changes. (Inherited from Control.) | |
KeyDown | Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement.) | |
KeyUp | Occurs when a keyboard key is released while the UIElement has focus. (Inherited from UIElement.) | |
LayoutUpdated | Occurs when the layout of the Silverlight visual tree changes. (Inherited from FrameworkElement.) | |
Loaded | Occurs when a FrameworkElement has been constructed and added to the object tree. (Inherited from FrameworkElement.) | |
LostFocus | Occurs when a UIElement loses focus. (Inherited from UIElement.) | |
LostMouseCapture | Occurs when the UIElement loses mouse capture. (Inherited from UIElement.) | |
MediaCommand | Occurs when a button is pressed on a remote control. (Inherited from UIElement.) | |
MouseEnter | Occurs when the mouse (or a stylus) enters the bounding area of a UIElement. (Inherited from UIElement.) | |
MouseLeave | Occurs when the mouse (or the stylus) leaves the bounding area of a UIElement. (Inherited from UIElement.) | |
MouseLeftButtonDown | Occurs when the left mouse button is pressed (or when the tip of the stylus touches the tablet) while the mouse pointer is over a UIElement. (Inherited from UIElement.) | |
MouseLeftButtonUp | Occurs when the left mouse button is released (or the tip of the stylus is removed from the tablet) while the mouse (or the stylus) is over a UIElement (or while a UIElement holds mouse capture). (Inherited from UIElement.) | |
MouseMove | Occurs when the coordinate position of the mouse (or stylus) changes while over a UIElement (or while a UIElement holds mouse capture). (Inherited from UIElement.) | |
MouseRightButtonDown | Occurs when the right mouse button is pressed while the mouse pointer is over a UIElement. (Inherited from UIElement.) | |
MouseRightButtonUp | Occurs when the right mouse button is released while the mouse pointer is over a UIElement. However, this event will only be raised if a caller marks the preceding MouseRightButtonDown event as handled; see Remarks. (Inherited from UIElement.) | |
MouseWheel | Occurs when the user rotates the mouse wheel while the mouse pointer is over a UIElement, or the UIElement has focus. (Inherited from UIElement.) | |
Selected | Occurs when the IsSelected property of a TreeViewItem changes from false to true. | |
SizeChanged | Occurs when either the ActualHeight or the ActualWidth properties change value on a FrameworkElement. (Inherited from FrameworkElement.) | |
TextInput | Occurs when a UI element gets text in a device-independent manner. (Inherited from UIElement.) | |
TextInputStart | Occurs when a UI element initially gets text in a device-independent manner. (Inherited from UIElement.) | |
TextInputUpdate | Occurs when text continues to be composed via an input method editor (IME). (Inherited from UIElement.) | |
Unloaded | Occurs when this object is no longer connected to the main object tree. (Inherited from FrameworkElement.) | |
Unselected | Occurs when the IsSelected property of a TreeViewItem changes from true to false. |
Fields
В | Name | Description |
---|---|---|
HasItemsProperty | Identifies the HasItems dependency property. | |
IsExpandedProperty | Identifies the IsExpanded dependency property. | |
IsSelectedProperty | Identifies the IsSelected dependency property. | |
IsSelectionActiveProperty | Identifies the IsSelectionActive dependency property. |
Remarks
The TreeViewItem class provides a container for content items displayed in a TreeView control. You can populate the control by using the Items or ItemsSource property. For more information about controls and how they display content, see Control Content Models.
TreeViewItem is a HeaderedItemsControl. You can set a header for its contents by using the Header property.
If a TreeViewItem contains additional TreeViewItem objects, it can be expanded and collapsed by clicking the caret icon next to the control. You can programmatically expand the TreeViewItem by setting IsExpanded to true, or collapse the item by setting IsExpanded to false. To select an item, set the SelectedItem property to true.
Customizing the TreeViewItem Control
To apply the same property settings to multiple TreeViewItem controls, use the Style property. To change the visual structure and visual behavior of a TreeViewItem, copy and modify its default style and template. For more information, see Control Customization.
Dependency properties for this control might be set by the default style of the control. If a dependency property for a TreeViewItem is set by its default style, the property might change from its default value when the TreeViewItem appears in the application. For more information, see Dependency Property Value Precedence. You can get the default style and template for TreeViewItem from TreeView Styles and Templates.