I have as simple a user control as I can think of:
<UserControl x:Class="GsnEd2.View.TestControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:GsnEd2.View"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
Focusable="True"
IsTabStop="True">
<Grid GotFocus="Grid_GotFocus" MouseDown="Grid_MouseDown">
<Border BorderBrush="Black" BorderThickness="1"/>
</Grid>
and in the code behind:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
public partial class TestControl : UserControl
{
public TestControl()
{
InitializeComponent();
}
private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
{
MessageBox.Show("Mouse down");
Focus();
}
private void Grid_GotFocus(object sender, RoutedEventArgs e)
{
MessageBox.Show("Got focus");
}
}
(Yes, I know it would be better to respond to mouse up. Lets get it working first!)
My MainWindow constructor is:
public MainWindow()
{
InitializeComponent();
TestControl test = new()
{
Height = 200,
Width = 200
};
Canvas.SetLeft(test, 50);
Canvas.SetTop(test, 50);
DrawingCanvas.Children.Add(test);
}
The control appears just fine, but nothing I do seems to give it focus. I've tried setting the Border
's IsHitTestVisible
to false
in case that was catching mouse actions, but that didn't help. What am I missing?