4

我正在尝试将键盘焦点设置为堆栈面板中包含的文本框。当 IsEditMode 变为 true 时,我希望文本框默认成为焦点。

我试过这段代码:

<DataTemplate x:Key="LibraryItemTemplate">
<StackPanel Orientation="Vertical">
    <StackPanel.Style>
       <Style TargetType="StackPanel">
          <Style.Triggers>
               <DataTrigger Binding="{Binding IsEditMode}" Value="True">
                   <Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=TxtB}"/>
               </DataTrigger>
          </Style.Triggers>
       </Style>
    </StackPanel.Style>

    <TextBlock x:Name="TxtA" Text="A" />
    <TextBox x:Name="TxtB" Text="B" Visibility="{Binding IsEditMode, Converter={StaticResource BoolVisibilityCollapsed}}"/>
</StackPanel>
</DataTemplate>
....
<ListView x:Name="LibraryListView" SelectedItem="{Binding SelectedItem,   UpdateSourceTrigger=PropertyChanged}" >
<ListView.View>
    <GridView>
        <GridViewColumn CellTemplate="{StaticResource LibraryItemTemplate}"  Width="Auto"/>
    </GridView>
</ListView.View>

但问题是鼠标没有标记似乎键盘焦点不在文本框中,我必须再次用鼠标单击文本框才能在文本框中输入一些文本。

任何想法?

4

1 回答 1

3

After FocusManager is setting the focus you have to handle this event and in the event you have to add

<TextBox x:Name="TxtB" 
         Text="B" 
         GotFocus="TxtB_GotFocus"  
         Visibility="{Binding IsEditMode
             , Converter={StaticResource BoolVisibilityCollapsed}}"/>

....
private void TxtB_GotFocus(object sender, RoutedEventArgs e)
{
    this.Dispatcher.BeginInvoke((Action)delegate
    {
       Keyboard.Focus(TxtB);
    }, DispatcherPriority.Render);
}

Thanks a lot to Darlene

And I'm adding the answer by myself to meet Sheridan's suggestion Thanks a lot

于 2013-08-01T15:57:26.100 回答