在网格上的WPF中的可见性绑定

时间:2015-10-07 09:51:52

标签: c# .net wpf xaml

在加载数据时,我想隐藏WPF控件的内容(全部包含在网格中)并显示加载控件。

MainWindow.xaml:

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

MainWindow的数据上下文为MainWindowViewModel,也来自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); }
        }
}

repository.LoadData():

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

LoadData()被称为按钮命令

我做错了什么?如果将MyCustomView的网格绑定可见性,但这不是解决方案,因为我有很多视图,而我只想在一个地方绑定{{1} 1}}。

1 个答案:

答案 0 :(得分:1)

你试过这个吗?

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