Mefhisto1
Mefhisto1

Reputation: 2228

Visiblity binding in WPF on a Grid

While the data is loading, I want to hide the content of the WPF control (which is all contained in a grid) and display a loading trobber.

MainWindow.xaml:

<Grid Visibility="{Binding IsContentVisible}">
<!-- MyCustomView is hosted here -->
</Grid>

The data context of MainWindow is MainWindowViewModel, which also derives from ViewModelBase

public class MainWindowViewModel : ViewModelBase
{}

MyCustomView.xaml:

<Grid>
<TextBox Text="{Binding Data}" />
<TextBlock>This shouldn't be visible during the 2.5 sec loading time, but it is!</TextBlock>
</Grid>

MyCustomViewModel.cs:

public class MyCustomViewModel : ViewModelBase
{
    public async void LoadData()
    {
        IsContentVisible = Visibility.Hidden;
        OnPropertyChanged("IsContentVisible");
        // Display loading.gif
        Data = await repository.LoadData();
        // Hide loading.gif
        IsContentVisible = Visibility.Visible;
        OnPropertyChanged("IsContentVisible");
    }
}

ViewModelBase.cs:

public class ViewModelBase : INotifyPropertyChanged
{
     private Visbility isContentVisible = Visibility.Visible;
     public Visbility IsContentVisible
     {
        get { return isContentVisible; }
        set { isContentVisible = value; }
     }

     protected virtual void OnPropertyChanged(string propertyName)
     {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
     }

        private ViewModelBase currentViewModel;
        public ViewModelBase CurrentViewModel
        {
            get { return currentViewModel; }
            set { SetProperty(ref currentViewModel, value); }
        }
}

and repository.LoadData():

Thread.Sleep(2500);
return "some text";

LoadData() is called as a command of a button

What am I doing wrong? If bind visiblity to the grid of the MyCustomView it works, but that's not the solution, since I'd have many views, and I only want to have binding in one place, the MainWindow.

Upvotes: 0

Views: 82

Answers (1)

Picco
Picco

Reputation: 9

Have you tried this?

private Visbility isContentVisible = Visibility.Visible;
public Visbility IsContentVisible
{
    get { return isContentVisible; }
    set 
    { 
        isContentVisible = value; 
        OnPropertyChanged("IsContentVisible");
    }
}

Upvotes: 1

Related Questions