WPF では、TextBox 要素は、プロパティ AcceptsReturn="True" を設定しない限り、KeyUp イベントを作成するために「Enter」ボタンを使用する機会を得られません。
ただし、TextBox 要素での KeyUp イベントの処理の問題は解決しません。「ENTER」を押すと、TextBox に新しいテキスト行が表示されます。
Bubbleイベント戦略を使用して、TextBox要素のKeyUpイベントを使用する問題を解決しました。短くて簡単です。一部の(任意の)親要素に KeyUp イベント ハンドラをアタッチする必要があります。
XAML:
<Window x:Class="TextBox_EnterButtomEvent.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:TextBox_EnterButtomEvent"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid KeyUp="Grid_KeyUp">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height ="0.3*"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="1" Grid.Column="1" Padding="0" TextWrapping="WrapWithOverflow">
Input text end press ENTER:
</TextBlock>
<TextBox Grid.Row="2" Grid.Column="1" HorizontalAlignment="Stretch"/>
<TextBlock Grid.Row="4" Grid.Column="1" Padding="0" TextWrapping="WrapWithOverflow">
You have entered:
</TextBlock>
<TextBlock Name="txtBlock" Grid.Row="5" Grid.Column="1" HorizontalAlignment="Stretch"/>
</Grid>
</Window>
C# 論理部分 (KeyUp イベント ハンドラーはグリッド要素にアタッチされています):
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Grid_KeyUp(object sender, KeyEventArgs e)
{
if(e.Key == Key.Enter)
{
TextBox txtBox = e.Source as TextBox;
if(txtBox != null)
{
this.txtBlock.Text = txtBox.Text;
this.txtBlock.Background = new SolidColorBrush(Colors.LightGray);
}
}
}
}
結果:
結果が表示されたアプリケーションのメイン ウィンドウ