AutoGeneratedColumn Event in Datagrid?

744 views Asked by At

When I search up for the AutoGeneratedColumn event this is all that I get.

If the AutoGenerateColumns property is set to true, the AutoGeneratingColumn event is raised for each column created. When all columns are created, this event will occur.

The AutoGeneratedColumns event is raised every time the DataGrid attempts to generate columns. For example, AutoGeneratedColumns is raised when the DataGrid is initialized, AutoGenerateColumns is set to true, or the ItemsSource is changed, even if the ItemsSource is null. This event occurs when the auto-completion process is completed by the DataGrid.

By this event, the Datagrid Columns property is filled with the generated columns and you can modify any generated column by giving index to Columns property.

My question is what is the use of this event and how can I use this event. Can anyone give an example like how I can access the columns using this event and what could I possibly change using this?

Example I tried to use the AutoGeneratedTrigger in a simple application. But I am stuck. I want to put some logic in the Auto function so I created a text block and bound with the Text property which I am initializing in the Auto Function which will run when the AutoGeneratedColumn event will trigger. But the Text Property does not store any value.

Xaml Code

<Grid>
        <StackPanel Orientation="Vertical">
            <DataGrid x:Name="DG" Width="400" AutoGenerateColumns="True" ItemsSource="{Binding emp,Mode=TwoWay}">
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="AutoGeneratedColumn">
                        <i:InvokeCommandAction Command="{Binding CmdAuto}"/>
                    </i:EventTrigger>
                </i:Interaction.Triggers>
            </DataGrid>
            <TextBlock Name="MyTextBlock" Text="{Binding Text,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" Width="200" Background="Aqua" Height="100"></TextBlock>
        </StackPanel>
    </Grid>

Class Code

public class Employees:ViewModelPropertyChanged
    {
        private ObservableCollection<Emp> _emp;

        public ObservableCollection<Emp> emp
        {
            get { return _emp; }
            set
            {
                _emp = value; OnPropertyChange("emp");
            }
        }
        public Employees ()
        {
             emp = new ObservableCollection<Emp>();
             emp.Add(new Emp { ID = 1, Name = "Kapil Malhotra", IsMale = true, Type = EmployeeType.Normal, SiteID = new Uri("http://localhost/4322"), BirthDate = new DateTime(1980, 1, 1) });
             emp.Add(new Emp { ID = 2, Name = "George", IsMale = true, Type = EmployeeType.Manager, SiteID = new Uri("http://localhost/4432"), BirthDate = new DateTime(1980, 2, 1) });
        }
        private string _Text;

        public string Text
        {
            get { return _Text; }
            set { _Text = value;
                OnPropertyChange("Text");
            }
        }

        public ICommand Cmdauto
        {
            get
            {
                return new DelegateCommand<object>(Auto);
            }
        }

        private void Auto(object obj)
        {
          
            //logic
            //Text ="Data Uploaded";
        }

    }
    public class Emp
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public bool IsMale { get; set; }
        public EmployeeType Type { get; set; }
        public Uri SiteID { get; set; }
        public DateTime BirthDate { get; set; }
    }
    public enum EmployeeType
    {
        Normal,
        Supervisor,
        Manager
    }
}
1

There are 1 answers

3
Hammas On

AutoGenerateColumns is indeed helpful in many scenarios. And this event OnAutoGeneratingColumn gives you control on how you want the columns to be generated. So now although the columns are being generated automatically but you are in control.

Like in following piece of code you can see, in one of my project i'm autogenerating columns for any list of string column names. This is kind of a Dynamic DataGrid which can show any kind of data and i don't have to write every time a new DataGrid code.

Formatting Header Text, Formatting bindings, Including or Excluding columns to be generated (because by default all columns are auto generated for all properties) and also controlling their display index and Width of columns. So, this is one of the way you can use it. Hope you got the idea.

private void DataGridAnything_OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{

    try
    {
        var existsCol = IncludeColumnsList.FirstOrDefault(x => x.IncludingColumnName.ToLower() == e.Column.Header.ToString().ToLower());

        if (existsCol == null)
        {
            e.Cancel = true;
            return;
        }

        if (existsCol.IncludingColumnName.Contains("Date") && e.PropertyType == typeof(DateTime))
        {
            (e.Column as DataGridTextColumn).Binding.StringFormat = "dd/MM/yyyy";
        }
        else if (existsCol.IncludingColumnName.Contains("Time") && e.PropertyType == typeof(TimeSpan))
        {
            (e.Column as DataGridTextColumn).Binding.StringFormat = "hh\\:mm\\:ss";
        }



        e.Column.DisplayIndex = existsCol.DisplayIndex;
        e.Column.Width = new DataGridLength(0,DataGridLengthUnitType.Auto);
        e.Column.Header = AddSpacesToSentence(e.Column.Header.ToString());
    }
    catch (Exception ex)
    {
        Intelli.ShowIntelliMessage(ex.Message, ex.ToString(), "Close");
        Log.Error(ex, "");
    }

}