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));
}
}
<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;
}
}
private void SomeMethod()
{
MyViewModel vm = new MyViewModel();
vm.IsVisible = true;
}