How to udpate the ListView.SelectedItem
when a child control within the ListView
gets focus?
<ListView ItemsSource="{Binding Path=Records, Mode=TwoWay}" IsSynchronizedWithCurrentItem="True">
<ListView.SelectedItem>
<Binding Path="SelectedRecord" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged"/>
</ListView.SelectedItem>
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Style.Triggers>
<Trigger Property="IsKeyboardFocusWithin" Value="True">
<Setter Property="IsSelected" Value="True"/>
</Trigger>
</Style.Triggers>
</Style>
</ListView.ItemContainerStyle>
<ListView.Resources>
<DataTemplate DataType="x:Type ListViewItem">
<ListViewItem IsSelected="{Binding IsKeyboardFocusWithin"/>
</DataTemplate>
</ListView.Resources>
<ListView.View>
<GridView>
<GridViewColumn>
<TextBox ... Tag="{Binding}".../>
</GridViewColumn>
<GridViewColumn>
<TextBox ... Tag="{Binding}".../>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
The ListView
has rows of child controls within the GridView
columns. I want to update the bound property of the ListView.SelectedItem
when any of the child control in any row has the keyboard focus. It will be great if this could be entirely done within the .xaml
file without having to resort to the code-behind.
Change the SelectionMode of your
ListBox
toSingle
Your current code works if you don't set the default
SelectedItem
, however if you set the defaultSelectedItem
then it doesn't automatically unselect it when you click on a 2nd item, soSelectedItem
stays bound to the default selected item until you give that row focus and remove it again.You can also simplify your XAML a bit. You don't need the
DataTemplate
in yourListBoxItem.Resources
and you can set theSelectedItem
in your<ListBox>
tag directly