1
說,我需要使用鍵盤在窗體中移動自定義(用戶)控件。保持焦點在WPF中的自定義(用戶)控件
行爲很簡單:用戶單擊控件,然後使用鍵盤(up/d/l/r)移動它。
在此示例中,而不是UserControl,我將使用Canvas。
的問題是,當我「合焦點」我的控制,或者我失去它的「階梯」對TextBox政變後,還是我不接受她在所有...
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」 S後執行日誌:
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 '
設置Handled to true help very well。謝謝! – serhio 2011-04-14 12:34:06