Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
2.7 kB
1
Indexable
Never
<Window x:Class="WpfImageVisibility.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="WPF Image Visibility Example" Height="350" Width="525">
    <Window.Resources>
        <local:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
    </Window.Resources>
    <Grid>
        <Image Source="path/to/your/image.jpg" Width="200" Height="200" Margin="10" Visibility="{Binding IsImageVisible, Converter={StaticResource BooleanToVisibilityConverter}}" x:Name="myImage"/>
        <Button Content="Toggle Image Visibility" Click="Button_Click" HorizontalAlignment="Center" VerticalAlignment="Bottom" Margin="0,0,0,20"/>
    </Grid>
</Window>

using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;

namespace WpfImageVisibility
{
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        private bool _isImageVisible = true;

        public bool IsImageVisible
        {
            get { return _isImageVisible; }
            set
            {
                if (_isImageVisible != value)
                {
                    _isImageVisible = value;
                    OnPropertyChanged();
                }
            }
        }

        public MainWindow()
        {
            InitializeComponent();
            DataContext = this; // Set DataContext to enable data binding
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                IsImageVisible = !IsImageVisible;
            });
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace WpfImageVisibility
{
    public class BooleanToVisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is bool boolValue)
            {
                return boolValue ? Visibility.Visible : Visibility.Hidden;
            }
            return Visibility.Visible;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}