Xenogenesis
Xenogenesis

Reputation: 390

How do I define columns for inner DataGrid in a custom control

I'm trying to implement a new control (XGrid), which contains a DataGrid.

Most of the time I directly bind the data through a DependencyProperty and set AutoGenerateColumns to True.

Now, in a specific case, I need the possibility to configure the columns of the DataGrid manually. I thought about something like:

<local:XGrid AutoGenerateColumns="False" DataContext="{Binding SourceList}">
    <local:XGrid.Columns>
        <DataGridTextColumn Header="T1" Binding="{Binding Path=.Value1}"/>
        <DataGridTextColumn Header="T2" Binding="{Binding Path=.Value2}"/>
        <DataGridTextColumn Header="T3" Binding="{Binding Path=.Value3}"/>
    </local:XGrid.Columns>        
</local:XGrid>

Is this, or something similar, possible?

--- EDIT 1 ---

XGrid is actually not derived from DataGrid

Upvotes: 1

Views: 216

Answers (1)

Muds
Muds

Reputation: 4116

Changed my last answer as your edit changed the scenario....

In this case you can expose a columns property and set columns into it, and then in constructor whenever your local collection is changed, add columns to main data grid.

something like this should work..

public static readonly DependencyProperty GridColumnsProperty = DependencyProperty.Register("GridColumns", typeof(ObservableCollection<DataGridColumn>), typeof(XGrid));
        public ObservableCollection<DataGridColumn> GridColumns
        {
            get { return (ObservableCollection<DataGridColumn>)GetValue(GridColumnsProperty); }
            set { SetValue(GridColumnsProperty, value); }
        }


public XGrid()
{
        GridColumns = new ObservableCollection<DataGridColumn>();
        GridColumns.CollectionChanged += (x, y) =>
            {
                dataGrid.Columns.Clear();
                foreach (var column in this.GridColumns)
                {
                    dataGrid.Columns.Add(column);
                }
            };
        InitializeComponent();
    }

Upvotes: 1

Related Questions