wpf 如何仅通过一键单击事件隐藏或显示图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21456283/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to hide or show image with just one button click event
提问by Marss
I am adding the button and image element using code. My wpf application is able to display an image stored on my project when I click the button. I want to hide the displayed image if I clicked the button again. How will I be able to achieve this if I only have one event handler for my button?
我正在使用代码添加按钮和图像元素。当我单击按钮时,我的 wpf 应用程序能够显示存储在我的项目中的图像。如果我再次单击该按钮,我想隐藏显示的图像。如果我的按钮只有一个事件处理程序,我将如何实现这一目标?
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
grid_parent.RowDefinitions.Add(new RowDefinition { Height = new GridLength(150, GridUnitType.Pixel) });
grid_parent.RowDefinitions.Add(new RowDefinition { Height = new GridLength(150, GridUnitType.Auto)});
Button btn_submit = new Button { Content = "Submit" };
btn_submit.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
Grid.SetRow(btn_submit, 1);
btn_submit.Click += btn_submit_Click;
grid_parent.Children.Add(btn_submit);
}
void btn_submit_Click(object sender, RoutedEventArgs e)
{
image = new Image { Source = new BitmapImage(new Uri(@"/AddControlsThroughClass;component/images/julie.jpg", UriKind.Relative)) };
image.Stretch = Stretch.Uniform;
Grid.SetRow(image, 0);
grid_parent.Children.Add(image);
}
}
采纳答案by Sheridan
The Buttoncontrol has no notion of when it has been clicked. Instead of using a regular Button, it would make more sense for you to use a ToggleButton, which doesknow when it has been clicked. The ToggleButtonclass has an IsCheckedproperty that will be set to trueafter the first click and back to falseafter another click. Therefore there is a very simple solution using this ToggleButtonproperty:
该Button控件没有关于它何时被单击的概念。除了使用常规的Button,那就更有意义了您使用ToggleButton,它不会被点击时,它知道。该ToggleButton班有一个IsChecked将被设置为属性true的第一次点击和回后false接一个地点击。因此,使用此ToggleButton属性有一个非常简单的解决方案:
image.Visibility = toggleButton.IsChecked ? Visiblity.Visible : Visiblity.Collapsed;
回答by Ismail Gunes
You can do it by a button however you can do also with keypreview property
您可以通过按钮来完成,但是您也可以使用 keypreview 属性来完成
Here is a code with keypreview
这是一个带有keypreview的代码
private void HideShow(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.S)
pictureBox1.Visible = true;
else if (e.KeyCode == Keys.H)
pictureBox1.Visible = false;
}
From the properties of your form add to keydown propery you can hide and show your picture
从表单的属性添加到 keydown 属性,您可以隐藏和显示您的图片
Or you can do by a button
或者你可以通过一个按钮来做
by this code
通过这个代码
pictureBox1.Visible = !pictureBox1.Visible
each time you click the button it will be visible or invisible)
每次单击按钮时,它将可见或不可见)

