WrapPanel 从其 children 中获取焦点

WrapPanel grabs focus from its children

我在滚动查看器的包装面板中有一些(自制的)控件,我希望我的控件在我单击它们或通过 Tab 键切换时获得焦点。但是包装面板抓住了焦点并将其交给 Children[0].

<ScrollViewer IsTabStop="False" >
   <toolkit:WrapPanel>
        <!-- children, filled in from code. IsTabStop="True" -->       
   </toolkit:WrapPanel>
</ScrollViewer>

滚动查看器做了同样的事情,但它的 IsTabStop="False" 让它表现得很好。但是,WrapPanel 没有 IsTabStop 属性。那么我怎样才能让它停止从它的 children 中获取焦点?

我试图通过我控件中的鼠标单击事件处理程序使用 Focus() 设置焦点 'manually'。控件获得焦点,但 wrappanel 立即抓住它并最终在 Children[0],即使我试图阻止 mouseclick 事件冒泡(e.Handled = true)。

不知何故它对我来说工作得很好。分享我尝试过的代码片段。

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <Image Name="img" Height="100" Width="100"/>
        <TextBox Name="tb3" Text="text2" KeyDown="tb3_KeyDown"  Width="200"/>
    </Grid>
    <ScrollViewer Grid.Row="2">
    <toolkit:WrapPanel Orientation="Vertical" Name="wp">

    </toolkit:WrapPanel>
    </ScrollViewer>

从后面的代码添加文本框

TextBox tb2 = new TextBox();
    // Constructor
    public MainPage()
    {
        InitializeComponent();

        TextBox tb = new TextBox();
        tb.Text = "some text";
        tb.Width = 200;


        tb2.Text = "some text";
        tb2.Width = 200;

        wp.Children.Add(tb); 
        wp.Children.Add(tb2);

    }

将焦点从网格内的一个文本框更改为 WrapPanel 内的文本框

  private void tb3_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
    {
if(e.Key == System.Windows.Input.Key.Enter)
{
tb2.Focus();
}
}

我找到了解决方法。在清理 custom-made 用户控件并获得所有焦点要求(IsTabStop、`` 等)的控制权后,WrapPanel 仍然抓住焦点并将其交给它的 Children[0]在我明确地将焦点设置到另一个 children 之一之后。停止鼠标点击事件修复了它:

void UserControl_MouseLeftButtonDown(object sender, MouseButtonEventArgs a)
{
   try
   {
       this.Focus();
   }
   finally
   {
       a.Handled = true;
   }
}