0

如何更新焦点ListView.SelectedItem内的子控件何时ListView获得焦点?

<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>

ListView中有子控件的GridView行。ListView.SelectedItem当任何行中的任何子控件具有键盘焦点时,我想更新绑定属性。如果这可以完全在.xaml文件中完成,而不必求助于代码隐藏,那就太好了。

4

1 回答 1

6

将您的SelectionMode更改ListBoxSingle

如果您没有设置默认值,您当前的代码可以工作SelectedItem,但是如果您设置默认值,SelectedItem那么当您单击第二个项目时它不会自动取消选择它,因此SelectedItem保持绑定到默认选定项目,直到您给予该行焦点和再次删除它。

您还可以稍微简化您的 XAML。你不需要DataTemplate你的ListBoxItem.Resources,你可以直接SelectedItem在你的<ListBox>标签中设置

<ListView ItemsSource="{Binding Path=Records}" IsSynchronizedWithCurrentItem="True"
          SelectedItem="{Binding SelectedRecord}" SelectionMode="Single">

     <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.View>
          <GridView>
              <GridViewColumn>
              <TextBox ... Tag="{Binding}".../>
              </GridViewColumn>
              <GridViewColumn>
              <TextBox ... Tag="{Binding}".../>
              </GridViewColumn>
          </GridView>
     </ListView.View>
</ListView>
于 2012-08-30T12:58:45.407 回答