Search code examples
c#.netwpfpropertiesisenabled

WPF IsEnabled Grid


I want to get my grid disabled when my property is Null and enabled when is Not null.

In my .XAML :

  <Grid Grid.Row="2" IsEnabled="{Binding ElementName=dgCustomers, Path=SelectedItem}">
      <my:ProductsHistoryDetailView />
  </Grid>

In my ViewModel.cs :

    public ProductHistory SelectedItem
    {
        get { return _SelectedItem; }
        set
        {
            if (_SelectedItem != value)
            {
                _SelectedItem = value;
                RaisePropertyChanged(() => SelectedItem);
            }
        }
    }

Solution

  • You should add an extra property to your viewmodel.

        public bool IsGridEnabled
        {
            get 
              { 
                 return this.SelectedItem != null;
              }
        }
    
    <Grid Grid.Row="2" IsEnabled="{Binding IsGridEnabled}">
         <my:ProductsHistoryDetailView />
    </Grid>
    

    And when your SelectedItem changes, call the OnPropertyChanged event for IsGridEnabled:

    public ProductHistory SelectedItem
    {
        get { return _SelectedItem; }
        set
        {
            if (_SelectedItem != value)
            {
                _SelectedItem = value;
                RaisePropertyChanged(() => SelectedItem);
                RaisePropertyChanged(() => IsGridEnabled);
            }
        }
    }