Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

c# - Trigger SelectedIndex changed whilst clicking on any control within a ListBoxItem area

I've a data template for ListBoxItem which contains of few buttons, and few custom controls like Grid or Chart. Each button is bound to an appropriate command handler, SelectedIndex property of a ListView control is bound to ViewModel's propery as well.

The problem: in command handlers (which are bound to buttons) I can't resolve currently selected item/index because it is not changing whilst clicking on a button or an other control within a ListBox item, but when I clicking on ListBoxItem area itself - SelectedIndex is changing.

Question is how to trigger SelectedIndex to be changed whilst clicking on any control within ListBoxItem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Add this to your ListBox.Resources

<ListBox.Resources>
    <Style TargetType="{x:Type ListBoxItem}">
        <Style.Triggers>
            <Trigger Property="IsKeyboardFocusWithin" Value="True">
                <Setter Property="IsSelected" Value="True" />
            </Trigger>
        </Style.Triggers>
    </Style>
</ListBox.Resources>

EDIT

The previous method only makes the ListBoxItem selected for as long as it has keyboard focus. If you move focus out of the ListBoxItem, it becomes unselected again.

Here's another simple way to select a ListBox item when the keyboard focus moves within the item, and it stays selected when focus is moved out of the ListBoxItem

<Style TargetType="{x:Type ListBoxItem}">
    <EventSetter Event="PreviewGotKeyboardFocus" Handler="SelectCurrentItem"/>
</Style>

And in the Code Behind

protected void SelectCurrentItem(object sender, KeyboardFocusChangedEventArgs e)
{
    ListBoxItem item = (ListBoxItem)sender;
    item.IsSelected = true;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...