如何转换以下适用的代码Winforms
以使其适用WPF
:
textBox1.Text = (input);
KeyEventArgs ev = new KeyEventArgs(Keys.Enter);
textBox1_KeyDown(sender, ev);
我想KeyDown
用特定的键调用事件,以便自动输入特定的值textBox1
。
如何转换以下适用的代码Winforms
以使其适用WPF
:
textBox1.Text = (input);
KeyEventArgs ev = new KeyEventArgs(Keys.Enter);
textBox1_KeyDown(sender, ev);
我想KeyDown
用特定的键调用事件,以便自动输入特定的值textBox1
。
要订阅使用 WPF 的KeyDown
-event 以TextBox
在按下特定键时向其输入一些随机文本,您可以使用以下方法之一:
方法 1 - 使用 XAML 定义事件(您不需要手动订阅事件):
XAML:
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<!-- define your TextBox and the KeyDown-event here -->
<TextBox x:Name="MyTextBox" Width="120" Height="30" KeyDown="MyTextBox_KeyDown"/>
</Grid>
</Window>
C#-代码:
using System.Windows;
using System.Windows.Input;
namespace WpfApp1
{
public partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
}
private void MyTextBox_KeyDown(object sender, KeyEventArgs e)
{
// if pressed key is "Enter", do something
if (e.Key == Key.Enter)
{
this.MyTextBox.Text = "Some Text!";
}
}
}
}
方法 2 - 定义事件并使用代码订阅它:
XAML:
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<!-- define your TextBox here -->
<TextBox x:Name="MyTextBox" Width="120" Height="30"/>
</Grid>
</Window>
C#-代码:
using System.Windows;
using System.Windows.Input;
namespace WpfApp1
{
public partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
this.MyTextBox.KeyDown += this.MyTextBox_KeyDown;
}
private void MyTextBox_KeyDown(object sender, KeyEventArgs e)
{
// if pressed key is "Enter", do something
if (e.Key == Key.Enter)
{
this.MyTextBox.Text = "Some Text!";
}
}
}
}
KeyDown
要使用特定键(此处:)调用-event,Key.Enter
您可以使用:
using System;
using System.Windows.Interop;
KeyEventArgs enterPressedArgs = new KeyEventArgs(Keyboard.PrimaryDevice, new HwndSource(0, 0, 0, 0, 0, "", IntPtr.Zero), 0, Key.Enter);
this.MyTextBox_KeyDown(null, enterPressedArgs);