Search code examples
wpflistviewdatatemplateselectionchangedselecteditemchanged

ListView SelectionChanged won't update when enclosed TextBox clicked


I have a list view with a gridview. The gridview second column contains textboxes (and in case this is relevant to this particular problem, the textboxes are rendered by a datatemplate).

I want the listview SelectedItem to update when the user clicks in the textbox to type and reflect the row (or listview item) containing the textbox. Right now listview SelectedItem will update only if the user's click on a row is just outside the textbox. If I click the textbox or type in it, the highlighted row stays the same and no SelectionChanged occurs for the listview.

How can I get the listview's selecteditem to update? Can I maybe force a change in its selecteditem or enable the listview to see the textbox click as its own somehow?

Thanks in advance.

P.s. Solution located here:

https://drive.google.com/file/d/0B89vOvsI7UbdTmN5RVdLVTFGeXM/view?usp=sharing

ListView xaml:

  <ListView x:Name="CombinedlistView" Grid.Column="0"                                  
     DataContext="{Binding ElementName=mainWindow}"
     SelectedIndex="{Binding Path=SelectedIndex, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
       IsSynchronizedWithCurrentItem="True">
          <ListView.View>
              <GridView >
                  <GridViewColumn CellTemplate="{StaticResource labelTemplate}" />
                  <GridViewColumn CellTemplateSelector="{StaticResource fieldValueTemplateSelector}" />
              </GridView>
          </ListView.View>                
   </ListView>

TemplateSelector:

     <loc:FieldValueTemplateSelector x:Key="fieldValueTemplateSelector" 
                        StringTemplate="{StaticResource stringTemplate}"
                        DateTimeTemplate="{StaticResource dateTimeTemplate}"/>

DataTemplate where textbox is located:

 <DataTemplate x:Key="stringTemplate" DataType="{x:Type System:String}">
  <StackPanel Style="{StaticResource dataTemplateStackPanelStyle}" Name="stringTemplStack">            
      <TextBox Name="searchValText"  Width="120"
        Text="{Binding Path=TextVal, Mode=OneWayToSource}"
        DataContext="{Binding ElementName=mainWindow}"/>
  </StackPanel>
 </DataTemplate>

Solution

  • try wiring up this event to your PreviewGotKeyboardFocus event on your listviewitem:

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