【问题标题】:how to hide or show image with just one button click event如何通过一键单击事件隐藏或显示图像
【发布时间】:2014-01-30 12:15:29
【问题描述】:

我正在使用代码添加按钮和图像元素。当我单击按钮时,我的 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);
    }
}

【问题讨论】:

标签: c# wpf xaml button wpf-controls


【解决方案1】:

Button 控件不知道何时单击。与其使用常规的Button,不如使用ToggleButton 更有意义,确实知道它何时被点击。 ToggleButton 类有一个IsChecked 属性,在第一次单击后将设置为true,在再次单击后返回false。因此使用ToggleButton 属性有一个非常简单的解决方案:

image.Visibility = toggleButton.IsChecked ? Visiblity.Visible : Visiblity.Collapsed;

【讨论】:

    【解决方案2】:

    您可以通过按钮来完成,但您也可以使用 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;
        }
    

    从表单的属性添加到 keydown 属性,您可以隐藏和显示您的图片

    或者你可以通过一个按钮来做

    通过此代码

    pictureBox1.Visible = !pictureBox1.Visible 
    

    每次单击按钮时,它都会可见或不可见)

    【讨论】:

    • -1 这是 WPF,不是 Winforms...查看问题标签。你像在 WPF 中那样设置Visibilty
    猜你喜欢
    • 1970-01-01
    • 2013-03-04
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 2017-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多