Wpf 如何制作文本块';s能见度';可见';在文本框中输入文本并按下Enter键时?
当用户在“WhatsYourname文本框”中输入他/她的名字并按Enter键时,我希望隐藏的文本块(“DoyouwanPlayTextBlock”)变得可见。这是我目前在XAML中得到的:Wpf 如何制作文本块';s能见度';可见';在文本框中输入文本并按下Enter键时?,wpf,visibility,keyup,Wpf,Visibility,Keyup,当用户在“WhatsYourname文本框”中输入他/她的名字并按Enter键时,我希望隐藏的文本块(“DoyouwanPlayTextBlock”)变得可见。这是我目前在XAML中得到的: <TextBox x:Name="playerNameTextbox" Grid.Column="1" Grid.Row="2" VerticalAlignment="Top"
<TextBox x:Name="playerNameTextbox"
Grid.Column="1" Grid.Row="2"
VerticalAlignment="Top"
HorizontalAlignment="Center"
BorderBrush="Black"
Height="auto"
Width="160"
HorizontalContentAlignment="Center"
CaretBrush="red"
FontFamily="Segoe Print"
FontSize="30"
ToolTip="Type your name and then press Enter"
KeyUp="playerNameTextbox_KeyUp" />
<TextBlock Grid.Column="0" Grid.Row="3" Grid.ColumnSpan="2"
x:Name="doYouWannaPlayTextblock"
FontFamily="Segoe Print"
FontSize="16"
FontWeight="SemiBold"
Foreground="Red"
Padding="20"
Visibility="Hidden"
TextAlignment="Center"
TextWrapping="Wrap" Margin="0,0.4,0.2,-25">
Hi,
<TextBlock Text="{Binding Path=Text, ElementName=playerNameTextbox}"/>
- it's good to see you. Would you like to play 'Tables'? If so, just click the 'Choose Game' button.
</TextBlock>
但当我试图在WPF中的代码隐藏中使用它时,我无法超越以下内容:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void playerNameTextbox_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
doYouWannaPlayTextblock.Visibility = Visible;
}
}
}
}
“可见”和我尝试过的所有东西都会吐出一条红色的曲线
任何帮助都将不胜感激。首先,更改
可见性的正确方法是:
private void playerNameTextbox_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
this.doYouWannaPlayTextblock.Visibility = Visibility.Visible;
}
}
doYouWannaPlayTextblock.Visibility = Visibility.Visible;
第二,您确定要使用键控
KeyDown
在这种情况下更有意义,因为它会在您按Enter键时触发,而不是在您松开它时触发
第三,如果您的doYouWannaPlayTextblock在按Enter键之前是不可见的,那么就不需要在XAML中包含文本,因为文本将通过代码进行设置。添加文本的代码为
doYouWannaPlayTextblock.Text = "Hi, " + playerOneNameTextbox.Text + ". " +
"It's good to see you! " +
"\r\nWould you like to play with us? " +
"\r\nIf you would, just click right here in this box.";
非常感谢,马特-这非常有效。我花了很多时间试图解决这个问题,在我读过的所有教程、视频和书籍中,我认为我没有遇到“xxx.Visibility=Visibility.xxx”的构造。我可以问一下,从技术上讲,它到底发生了什么?前一种感觉更适合我,但感谢你的观察。Re是我从某个地方(不确定在哪里或为什么)得到的印象,将这些东西放在XAML中比放在代码中要好。@MikeVisibility
属性接受一个可见性枚举,因此,您必须首先调用枚举,然后在该枚举中调用所需的值。这就是为什么它看起来像Visibility.XXXX
doYouWannaPlayTextblock.Text = "Hi, " + playerOneNameTextbox.Text + ". " +
"It's good to see you! " +
"\r\nWould you like to play with us? " +
"\r\nIf you would, just click right here in this box.";