将焦点放在WPF中的自定义(用户)控件上
||
说,我需要使用键盘以表格的形式移动自定义(User)控件。
行为很简单:用户单击控件,然后可以使用键盘(up / d / l / r)移动它。
在此示例中,我将使用Canvas代替UserControl。
问题是当我“聚焦”控件时,或者在文本框发生“步骤”变通之后,我将其放开,或者根本不接收它...
XAML:
<Window x:Class=\"WpfApplication14.MainWindow\"
xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"
xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"
Title=\"MainWindow\" Height=\"350\" Width=\"525\"
PreviewKeyDown=\"Window_PreviewKeyDown\">
<Grid>
<TextBox Name=\"textBox1\"
Margin=\"91,66,292,223\" Width=\"120\"
Text=\"Good morning, miss Hilton!\"/>
<Canvas Name=\"canvas1\" Focusable=\"True\"
Margin=\"124,112,179,99\" Width=\"200\"
Background=\"AliceBlue\"
MouseDown=\"canvas1_MouseDown\"
PreviewKeyDown=\"canvas1_PreviewKeyDown\" />
</Grid>
</Window>
CS:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void canvas1_MouseDown(object sender, MouseButtonEventArgs e)
{
Console.WriteLine(\"canvas_MouseDown 0, canvas1.IsFocused? {0}\",
canvas1.IsFocused);
canvas1.Focus();
Console.WriteLine(\"canvas_MouseDown 1, canvas1.IsFocused? {0}\",
canvas1.IsFocused);
}
private void canvas1_PreviewKeyDown(object sender, KeyEventArgs e)
{
Console.WriteLine(\"canvas_PreviewKeyDown, canvas1.IsFocused? {0}\",
canvas1.IsFocused);
if (canvas1.IsFocused)
MoveCanvas(e.Key);
}
private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{
//Console.WriteLine(\"Window_PreviewKeyDown, canvas1.IsFocused? {0}\",
// canvas1.IsFocused);
//if (canvas1.IsFocused)
// MoveCanvas(e.Key);
}
void MoveCanvas(Key key)
{
int delta = 10;
switch (key)
{
case Key.Left: canvas1.Margin = new Thickness(
canvas1.Margin.Left - delta,
canvas1.Margin.Top,
canvas1.Margin.Right,
canvas1.Margin.Bottom);
break;
case Key.Up: canvas1.Margin = new Thickness(
canvas1.Margin.Left,
canvas1.Margin.Top - delta,
canvas1.Margin.Right,
canvas1.Margin.Bottom + delta);
break;
case Key.Right: canvas1.Margin = new Thickness(
canvas1.Margin.Left,
canvas1.Margin.Top,
canvas1.Margin.Right - delta,
canvas1.Margin.Bottom);
break;
case Key.Down: canvas1.Margin = new Thickness(
canvas1.Margin.Left,
canvas1.Margin.Top + delta,
canvas1.Margin.Right,
canvas1.Margin.Bottom - delta);
break;
default:
break;
}
}
}
鼠标按下控件和三个\“ keyUp \”后,下面是执行日志:
canvas_MouseDown 0, canvas1.IsFocused? False \' before click \'
canvas_MouseDown 1, canvas1.IsFocused? True \' after click \'
Window_PreviewKeyDown, canvas1.IsFocused? True \' up 1 \'
canvas_PreviewKeyDown, canvas1.IsFocused? True \' up 1 \'
Window_PreviewKeyDown, canvas1.IsFocused? False \' up 2 \'
Window_PreviewKeyDown, canvas1.IsFocused? False \' up 3 \'
没有找到相关结果
已邀请:
1 个回复
盛虱