Search code examples
wpfdata-bindingdatagridview

AutoGenerateField not working in wpf datagrid


I am binding my datagrid to an observableCollection of Class CustomerDetails, I want to hide one of the property from being displayed on the UI as column, for which i am using AutoGenerateField to false, still this column is getting displayed in UI, what am i missing ?

my xaml file is like below :

<DataGrid AutoGenerateColumns="True" ItemsSource="{Binding DataGridItems}" 
                      Margin="1" IsReadOnly="True" SelectedIndex="{Binding SelectedItem }"

ViewModel.cs:

 public ObservableCollection<CustomerDetails> DataGridItems => _model.CustomerDetailsList;

Model.cs

 public ObservableCollection<CustomerDetails> CustomerDetailsList { get; set; }


public MyModel()
        {            
            CustomerDetailsList = new ObservableCollection<CustomerDetails>();    // assume that my list of customers is initialized here      
        }  


 public class CustomerDetails 
    {

        #region Constructor

        public CustomerDetails()
        {

        }

        #endregion

        #region Public Members        

        public string CustomerName
        {
           get; set;
        }

        public string CustomerID
        {
            get;set;
        }

        public string ProductCode
        {
            get;set;
        }
// want to hide this from getting shown in Datagrid
        [Display(AutoGenerateField = false)]
        public string ProductInternalId { get; set; }

Solution

  • Likely you are running into the same underlying problem as:

    You should handle the AutoGeneratingColumn event to cancel the generation of the column (you can base your logic on the field attributes to still make use of [Display(AutoGenerateField=false)]):

    Alternatively you could turn off AutoGenerateColumns and add the ones you want to the datagrid columns template manually.