1

How do I bind the datagrid visibility using MVVM so that if there is no data, set the visibility of the DataGrid to Collapsed, in such a way that the code could be reusable.
Thanks.

sll
  • 61,540
  • 22
  • 104
  • 156
user282807
  • 905
  • 3
  • 13
  • 26

1 Answers1

2

In ViewModel expose property like

// In setter consider INotifyPropertyChanged 
public bool IsDataAvailable
{
  get; set;
}

In XAML:

<DataGrid Visibility="{Binding IsDataAvailable, 
                      Converter={StaticResource BooleanToVisibilityConverter}}" />

Some useful links:

Community
  • 1
  • 1
sll
  • 61,540
  • 22
  • 104
  • 156
  • I have tried using that but only works the first time the grid is loaded (i put a break point to monitor that and only gets hit the first time) If i click the search button, the break point does not get hit. Does this has to do with the fact that the VISIBILITY property is not a dependency property? – user282807 Nov 08 '11 at 17:32
  • 1
    I believe because you've not supported INotifyPropertyChanged in your ViewModel, search StackOverflow regarding INotifyPropertyChanged and cusotm properties, for instance [this SO post](http://stackoverflow.com/questions/5285377/wpf-mvvm-inotifypropertychanged-implementation-model-or-viewmodel) – sll Nov 08 '11 at 17:35
  • I did implement INotifyPropertyChanged. Is there a working sample that shows the visibility working when clicking a search button to get data on the datagrid? The visibility is not like the ItemsSource property. – user282807 Nov 08 '11 at 17:54
  • Anyone who did show/hide datagrid if items source is null using a behavior? – user282807 Nov 14 '11 at 04:24
  • @user282807 : which behaviour you mean? – sll Nov 14 '11 at 09:01
  • I am using MVVM, and my scenario is that i have a search screen and would like to create a behavior for the datagrid, if there is no data then the datagrid behavior would set the visibilty of the datagrid to not show up. – user282807 Nov 14 '11 at 21:46