mattisrowe
mattisrowe

Reputation: 149

Xaml Listbox item focus issue

I am using a xaml UserControl as part of a WPF application. i have created a list box which i have populated with data from a text search. this data appears on buttons which are used to select the users desired option from the search.

<ScrollViewer HorizontalScrollBarVisibility="Auto"
    VerticalScrollBarVisibility="Auto"
    Margin="2">

    <ListBox ItemsSource="{Binding Path=CrewOptions}"
        HorizontalContentAlignment="Stretch"
        BorderThickness="0"
        SelectionMode="Multiple"
        Name="CrewOptionsListBox">

        <ListBox.ItemTemplate>
            <DataTemplate>
                <Button x:Name="irrelevant"
                    Height="28px"
                    Background="#F4F3E9"
                    Margin="2,2,2,2"
                    Content="{Binding irrelevant1, TargetNullValue={x:Static sys:String.Empty}}"
                    Command="{Binding irrelevant2}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>

        <ListBox.ItemContainerStyle>
            <Style TargetType="{x:Type ListBoxItem}"
            </Style>
        </ListBox.ItemContainerStyle>
    </ListBox>
</ScrollViewer>

This works fine, however when i tab from the textbox into the list box and then use the arrow keys to select an option, the enter key press does not select the button. Instead, i have to tab once more to focus on the button before pressing enter to select it.

Is there any way to avoid having to hit the last tab key to focus on the button?

Open to both Xaml and C# solutions (preferably MVVM)

Upvotes: 0

Views: 974

Answers (2)

Mitan Shah
Mitan Shah

Reputation: 344

Hi you can add below code in ListBox this will resolve focus issue on ListBoxItem.

    <ListView.ItemContainerStyle>
        <Style TargetType="ContentControl">
            <Setter Property="Focusable" Value="False"/>
        </Style>
    </ListView.ItemContainerStyle>

Upvotes: 2

Jegan
Jegan

Reputation: 1237

The reason for this is that you have cascading controls. When you use the arrow keys the List box is the active control, therefore all events will be fired based on the list box, not the button.

One way forward is to assign a keypressed event on the selected item, then initiate the function that will be triggered by the button.

something like:

listBox_keyPressed()
{
   if(selecteditem)
   {
      DoSomethingFor(selectedItem);
   }
}

Upvotes: 0

Related Questions