【问题标题】:UWP control to keep focus after mouse click鼠标单击后保持焦点的 UWP 控件
【发布时间】:2020-04-11 00:10:32
【问题描述】:

我有一个画布(技术上是 SkiaSharp SKXamlCanvas),我需要将它托管在一个可以获得焦点的控件中(出于此处我不会介绍的原因)。我将画布作为子类添加到派生自ContentControl 的类(称为ControlHost),并将画布设置为ContentControlHost's GetFocus 在我打开应用程序时被调用,但是当我点击ControlHost(占据整个窗口)时,我在释放鼠标按钮后得到一个LostFocus

我知道TextBox 之类的东西在用鼠标单击它们后会保持焦点。我可以使用另一个控件来保持焦点并简单地充当画布的容器吗?我试过UserControlFramePage 等。或者我可以在ContentControl 上设置一些属性,让它保持焦点?

这可以通过制作一个空白的 UWP 应用并将以下控件作为子控件添加到MainPage 的网格中轻松重现。

public class ContentControlTest : ContentControl
{
    public ContentControlTest()
    {
        GotFocus += OnGotFocus;
        LostFocus += OnLostFocus;
    }

    private void OnLostFocus(object sender, RoutedEventArgs e)
    {
        Debug.WriteLine("OnLostFocus");
    }

    private void OnGotFocus(object sender, RoutedEventArgs e)
    {
        Debug.WriteLine("OnGotFocus");
    }
}

【问题讨论】:

    标签: c# uwp uwp-xaml


    【解决方案1】:

    鼠标点击后保持焦点的UWP控件

    按设计,ContentControlPointerReleased 时会失去焦点。 ContentControl 继承自 Control。所以它有Focus 方法,如果你想保持焦点,你可以尝试在OnLostFocus 中调用Focus 方法,如下所示。

    private void OnLostFocus(object sender, RoutedEventArgs e)
    {
        Debug.WriteLine("OnLostFocus");
        this.Focus(FocusState.Programmatic);
    }
    

    【讨论】:

    • 如果我在页面上有另一个控件,这将阻止该控件获得焦点。没有控件可以用作保持焦点的容器吗?
    • 是的,它始终保持焦点,这是设计使然。
    • 所以如果我不想这样做,并且我想让其他控件获得焦点,但又不想失去对鼠标向上的关注,那么没有其他选择吗?我可以从 TextBox 派生,但我必须弄清楚如何删除所有视觉样式以使其成为其他控件的简单容器。
    • 你可以获得默认的文本框样式here。您可以自定义样式并隐藏内容。
    • 好的。所以没有什么(没有属性应用于 TextBox)可以应用于 UserControl 或 ContentControl 以使它们能够像 TextBox 一样表现并在单击它们后保持焦点?
    【解决方案2】:

    其实你可以在点击一个ContentControl后保持焦点。

    默认情况下,ContentControl 的 PointerReleased 事件触发后,ContentControl 的 LostFocus 事件会被触发(一个控件在另一个控件获得焦点时失去焦点)。

    因此,您可以通过将自定义 PointerReleased 事件处理程序添加到 ContentControl 来修改默认行为。由于 PointerReleased 是路由事件,所以只需添加 e.Handled = true

    private void ControlHost_PointerReleased(object sender, Windows.UI.Xaml.Input.PointerRoutedEventArgs e)
    {
        // Prevent most handlers along the event route from handling the same event again.
        e.Handled = true;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-04-09
      • 2017-05-10
      • 1970-01-01
      • 2010-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-19
      相关资源
      最近更新 更多