I have a DataGrid with autogenerate columns is true because it's columns are getting added dynamically from view model. Still i want to enable the text wrapping because on resizing the columns the text is getting hidden.
XAML Code:
<DataGrid x:Name="individualGrid" Margin="0,2,0,0" Visibility="{Binding ElementName=individualFilter, Path=IsChecked, Converter={StaticResource BoolToVisibility}}"
Grid.Row="4" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" AutoGenerateColumns="True" VerticalScrollBarVisibility="Auto" Height="500"
ItemsSource="{Binding ElementName=deptFilter, Path=SelectedItem.Individuals.View}" AutomationProperties.AutomationId="AID_UH_individualGrid" ColumnWidth="*" MinColumnWidth="140" />
Please help.
UPDATE 1
I tried the code behind approach by handling auto generating event.It worked but multiple columns of the same type are added.
private void IndividualGrid_OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
//cancel the auto generated column
e.Cancel = true;
//Get the existing column
DataGridTextColumn dgTextC = (DataGridTextColumn)e.Column;
//Create a new template column
DataGridTemplateColumn dgtc = new DataGridTemplateColumn();
DataTemplate dataTemplate = new DataTemplate(typeof(DataGridCell));
FrameworkElementFactory tb = new FrameworkElementFactory(typeof(TextBlock));
tb.SetValue(TextBlock.TextWrappingProperty, TextWrapping.Wrap);
dataTemplate.VisualTree = tb;
dgtc.Header = dgTextC.Header;
dgtc.CellTemplate = dataTemplate;
tb.SetBinding(TextBlock.TextProperty, dgTextC.Binding);
//add column back to data grid
DataGrid dg = sender as DataGrid;
if (dg != null) dg.Columns.Add(dgtc);
}
Can someone suggest why the multiple columns are added whereas it should have only two columns.
UPDATE 2
I finally found a solution by handling autogenerating. Here is the solution:
private void IndividualGrid_OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
//Get the existing column
DataGridTextColumn dgTextC = (DataGridTextColumn)e.Column;
if (dgTextC != null)
dgTextC.ElementStyle = individualGrid.Resources["wordWrapStyle"] as Style;
}
But now there is an additional issue.There is an extra column at the start looks like an index column. Any suggestions to this?