I would like to create a UserControl containing a DataGrid and then define the columns directly inside my UserControl:
<my:ControlContainingDataGrid ItemsSource="{Binding}">
<my:ControlContainingDataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path=Property1}" Header="Property 1"/>
In the UserControl I expose the columns of the DataGrid :
static ControlContainingDataGrid()
{
ColumnsProperty = DependencyProperty.Register(
"Columns",
typeof(ObservableCollection<DataGridColumn>),
typeof(ControlContainingDataGrid),
new UIPropertyMetadata(new ObservableCollection<DataGridColumn>())
);
}
[Description("Columns"), Category("Columns")]
public ObservableCollection<DataGridColumn> Columns
{
get { return _datagGrid.Columns; }
}
public static readonly DependencyProperty ColumnsProperty;
=> it doesn't work : the column binded to Property1 is not created.
I try to create the column programatically :
_datagGrid.Columns.Add(new DataGridTextColumn {
Header = "Property 1",
Binding = new Binding {
Path = new PropertyPath("Property1"),
Mode = BindingMode.TwoWay,
},
});
_datagGrid.ItemsSource = testList;
=> it doesn't work : the header is displayed but each row of my DataGrid is empty (bad binding ?).
1- What is the simpliest way to bind the columns of a DataGrid via the UserControl in the XAML part ?
2- What is the simpliest way to bind the columns of a DataGrid via the UserControl programatically ?