How to change the visible property of TextBox and ListView from MVVM

Sarah 186 Reputation points
2022-04-22T20:32:02.617+00:00

I have a ListView and a TextBox in my window. I want to set the Visibilty of these controls to Hidden. How do I do that from the MVVM?

<Window x:Class="Enum.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Enum"
        mc:Ignorable="d"
        Title="Window1" Height="450" Width="400">
    <Grid>
        <StackPanel Orientation="Vertical">
            <ListView Width="300" Height="400" Visibility="{Binding LvIsVisible}">
                <ListView.View >
                    <GridView AllowsColumnReorder="False">
                        <GridViewColumn Header="Pro" Width="120">
                            <GridViewColumn.CellTemplate>
                                <DataTemplate>
                                    <TextBlock Text="{Binding ItemContent}" TextWrapping="Wrap"/>
                                </DataTemplate>
                            </GridViewColumn.CellTemplate>
                        </GridViewColumn>
                    </GridView>
                </ListView.View>
            </ListView>
            <TextBox Width="300" Height="25" Visibility="{Binding TxtBoxIsVisible}" />
        </StackPanel>        
    </Grid>
</Window>
Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,671 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Michael Taylor 48,046 Reputation points
    2022-04-22T21:05:10.85+00:00

    The VM should expose dependency properties indicating whether the UI element(s) should be visible or not (boolean). Then you bind the property to the visibility state of the control using XAML. Most likely you'll need to use the BooleanToVisibilityConverter in the XAML to convert the boolean value to/from Visibility but otherwise it should just work.

    0 comments No comments

  2. Hui Liu-MSFT 38,251 Reputation points Microsoft Vendor
    2022-04-25T08:34:22.677+00:00

    You could try to refer to the code below.
    MainWindow.xaml:

    196054-b.txt
    MainWindow.xaml.cs:

    using System;  
    using System.Collections.ObjectModel;  
    using System.ComponentModel;  
    using System.Globalization;  
    using System.Runtime.CompilerServices;  
    using System.Windows;  
    using System.Windows.Data;  
    
    namespace ControlVisibleChangeByMVVM  
    {  
      public partial class MainWindow : Window  
      {  
        ViewModel vm=new ViewModel();  
        public MainWindow()  
        {  
          InitializeComponent();  
          DataContext=vm;  
        }  
      }  
      public class ViewModel: INotifyPropertyChanged  
      {  
        private bool myVisibility  =false;  
        public bool MyVisibility  
        {  
          get { return myVisibility; }  
          set { myVisibility=value; OnPropertyChanged("MyVisibility");}  
        }  
        ObservableCollection<Item> datas = new ObservableCollection<Item>();  
        public ObservableCollection<Item> Datas  
        {  
          get  
          {  
            return datas;  
          }  
          set  
          {  
            datas=value;  
            OnPropertyChanged("Datas");  
          }  
        }  
        public ViewModel()  
        {  
          datas.Add(new Item("name1"));  
          datas.Add(new Item("name2"));  
          datas.Add(new Item("name3"));  
          datas.Add(new Item("name4"));  
        }  
        public event PropertyChangedEventHandler PropertyChanged;  
        protected void OnPropertyChanged([CallerMemberName] string name = null)  
        {  
          PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));  
        }  
      }  
      public class BindingProxy : Freezable  
      {  
        public static readonly DependencyProperty DataProperty =  
           DependencyProperty.Register("Data", typeof(object),  
              typeof(BindingProxy));  
    
        public object Data  
        {  
          get { return GetValue(DataProperty); }  
          set { SetValue(DataProperty, value); }  
        }  
        protected override Freezable CreateInstanceCore()  
        {  
          return new BindingProxy();  
        }  
    
      }  
      public class Item  
      {  
        public string Name { get; set; }  
        public Item()  
        {  
        }  
        public Item(string name)  
        {  
          Name = name;  
        }  
      }  
      [ValueConversion(typeof(bool), typeof(Visibility))]  
      public sealed class BooleanToVisibilityConverter : IValueConverter  
      {  
        public bool IsReversed { get; set; }  
        public bool UseHidden { get; set; }  
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)  
        {  
          var val = System.Convert.ToBoolean(value, CultureInfo.InvariantCulture);  
          if (this.IsReversed)  
          {  
            val = !val;  
          }  
          if (val)  
          {  
            return Visibility.Visible;  
          }  
          return this.UseHidden ? Visibility.Hidden : Visibility.Collapsed;  
        }  
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)  
        {  
          throw new NotImplementedException();  
        }  
      }  
    }  
    

    The result:
    196026-55.gif


    If the response is helpful, please click "Accept Answer" and upvote it.
     Note: Please follow the steps in our [documentation][5] to enable e-mail notifications if you want to receive the related email notification for this thread. 

    [5]: https://learn.microsoft.com/en-us/answers/articles/67444/email-notifications.html

    0 comments No comments