[WPF] MVVM패턴을 이용한 오브젝트 Visible 컨트롤

JEONGKI'S Note·2023년 2월 9일
0

1. Create a property in the ViewModel:

public class MyViewModel : INotifyPropertyChanged
{
    private bool isVisible;

    public bool IsVisible
    {
        get => isVisible;
        set
        {
            isVisible = value;
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

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

2. Bind to the View:

<Window x:Class="MyWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <StackPanel>
        <TextBlock x:Name="MyTextBlock" Visibility="{Binding IsVisible, Converter={StaticResource BooleanToVisibilityConverter}}">
            This is some text
        </TextBlock>
    </StackPanel>
</Window>

Note: In the example above, we are using a BooleanToVisibilityConverter to convert the bool value of the IsVisible property to a Visibility value. This converter can be implemented as follows:

public class BooleanToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (bool)value ? Visibility.Visible : Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (Visibility)value == Visibility.Visible;
    }
}

3. Update the property in the ViewModel:

private void SomeMethod()
{
    MyViewModel vm = new MyViewModel();
    vm.IsVisible = true;
}
profile
주니어 개발자 공부노트입니다 :)

0개의 댓글