如何转换下面与Winforms
一起使用的代码以使其与WPF
一起使用:
textBox1.Text = (input);
KeyEventArgs ev = new KeyEventArgs(Keys.Enter);
textBox1_KeyDown(sender, ev);
我想用特定的键调用KeyDown
事件,以便将特定的值自动输入到textBox1
中。
答案 0 :(得分:1)
要使用WPF订阅KeyDown
的{{1}}事件,请在按下特定键时使用WPF输入一些随机文本,您可以使用以下方法之一:
方法1-使用XAML定义事件(您无需手动订阅事件):
XAML:
TextBox
C#代码:
<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>
方法2-定义事件并使用代码进行订阅:
XAML:
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!";
}
}
}
}
C#代码:
<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>
要使用特定键(此处为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
事件,您可以使用:
Key.Enter