แก้ไข

แชร์ผ่าน


Selector.IsSelected Attached Property

Definition

Gets or sets a value that indicates whether an item is selected.

see GetIsSelected, and SetIsSelected
see GetIsSelected, and SetIsSelected
see GetIsSelected, and SetIsSelected

Examples

The follow example creates a ListBox that contains two CheckBox controls. The example does not explicitly create a ListBoxItem for either CheckBox, so it sets Selector.IsSelected directly on each CheckBox. To illustrate that Selector.IsSelected is not updated, the example binds the IsChecked property of the first checkbox to Selector.IsSelected. When the user unselects the item in the ListBox, the CheckBox remains checked. Likewise, checking or unchecking the CheckBox does not affect whether the CheckBox is selected in the ListBox. The example binds IsChecked of the second CheckBox to ListBoxItem.IsSelected. In this case, unselecting the item in the ListBox causes the checkbox to be unchecked, and unchecking the checkbox also unselects the item.

<ListBox Name="listBox1" SelectionMode="Multiple">
  <CheckBox Selector.IsSelected="True" 
            IsChecked="{Binding RelativeSource={RelativeSource Self}, 
                        Path=(Selector.IsSelected), Mode=TwoWay}">
    CheckBox.IsChecked is bound to Selector.IsChecked, which is set only
    once.
  </CheckBox>

  <CheckBox ListBox.IsSelected="True" 
            IsChecked="{Binding RelativeSource={RelativeSource 
                        AncestorType={x:Type ListBoxItem}}, 
                        Path=IsSelected, Mode=TwoWay}">
    CheckBox.IsChecked is bound to ListBoxItem.IsChecked, which is
    updated throughout the duration of the application.
  </CheckBox>
</ListBox>

Remarks

Use the IsSelected attached property to select an item in the Selector when you do not explicitly create the item container. An item container is a class that represents an item in the Selector. TabItem, ListBoxItem, and ComboBoxItem are item containers for the controls that inherit from Selector, and each defines an IsSelected property.

If you do not explicitly create an item container, Windows Presentation Foundation (WPF) implicitly creates one and sets the IsSelected property on the item container to the value of Selector.IsSelected. This is the only time Selector.IsSelected is read. Selector.IsSelected is not updated if the selection on the item changes.

If you explicitly create an item container, you should use the IsSelected property on that class.

Dependency Property Information

Identifier field IsSelectedProperty, registered as Attached
Metadata properties set to true BindsTwoWayByDefault

Applies to