Search code examples
wpfbindinglistboxitemtemplatecurrentitem

Wpf ItemTemplate CurrentItem


I have a simple ListBox.ItemTemplate containing a Label and a TextBox bound to a CSLA Bindable List. When I select the TextBox the CurrentItem does not change, it only changes if I select the Label. I have IsSynchronizedWithCurrentItem='True'.

<ListBox x:Name="ItemsDataGrid"
         ItemsSource="{Binding Source={StaticResource AuditItems},Path=Items}"
         IsSynchronizedWithCurrentItem="True">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="200"></ColumnDefinition>
                    <ColumnDefinition Width="100"></ColumnDefinition>
                </Grid.ColumnDefinitions>        
                <Label Grid.Column="0" 
                       Content="{Binding Path=TypeRef}" />                    
                        <TextBox x:Name="TextBoxQty" 
                                 Grid.Column="1" 
                                 Text="{Binding Path=TaliQty}"/>                         
            </Grid>
        </DataTemplate>                                
    </ListBox.ItemTemplate>                        
</ListBox>

Solution

  • Try adding this to your ListBox. It selects the item any time any contained element (like TextBox) gets keyboard focus. A similar method could also be used with just a simple setter in the Trigger but that tends to interfere with the CurrentItem setting on the ICollectionView:

             <ListBox.ItemContainerStyle>
                <Style TargetType="{x:Type ListBoxItem}">
                    <Style.Triggers>
                        <Trigger Property="IsKeyboardFocusWithin" Value="True">
                            <Trigger.EnterActions>
                                <BeginStoryboard x:Name="SetSelected">
                                    <Storyboard>
                                        <BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="IsSelected">
                                            <DiscreteBooleanKeyFrame KeyTime="0:00" Value="True" />
                                        </BooleanAnimationUsingKeyFrames>
                                    </Storyboard>
                                </BeginStoryboard>
                            </Trigger.EnterActions>
                            <Trigger.ExitActions>
                                <RemoveStoryboard BeginStoryboardName="SetSelected"/>
                            </Trigger.ExitActions>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </ListBox.ItemContainerStyle>