I want to Save and Restore DataGrid
columns width, I tried this:
private void dataGrid_LayoutUpdated(object sender, EventArgs e)
{
foreach (var item in dataGrid.Columns.GetEnumeratorWithIndex())
{
Settings.ColumnWidth[item.Index] =
new DataGridLength(item.Value.Width.Value,
DataGridLengthUnitType.Pixel,
item.Value.Width.DesiredValue, item.Value.Width.DisplayValue);
}
}
Restore:
foreach (var item in dataGrid.Columns.GetEnumeratorWithIndex())
{
item.Value.Width = new
DataGridLength(Settings.ColumnWidth[item.Index].Value,
DataGridLengthUnitType.Pixel,
Settings.ColumnWidth[item.Index].DesiredValue,
Settings.ColumnWidth[item.Index].DisplayValue);
}
But not working and all columns stored as Auto.
Update:
Try using the property ActualWidth
:
for (int index = 0; index < dataGrid.Columns.Count; index++)
Settings.ColumnWidth[index] = new
DataGridLength(dataGrid.Columns[index].ActualWidth);
Example of reading column sizes:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void GetWidthsClick(object sender, RoutedEventArgs e)
{
MessageBox.Show(string.Join("; ",
dataGrid.Columns.Select(column => column.Width))
+ Environment.NewLine + string.Join("; ",
dataGrid.Columns.Select(column => column.ActualWidth)));
}
}
public class TextsViewModel
{
public ObservableCollection<Texts> Rows { get; } =
new ObservableCollection<Texts>()
{
new Texts() {Text1="123", Text2="45678",
Text3="90qwer", Text4="tyuiio", Text5="as"},
new Texts() {Text1="asad", Text2="gfg",
Text3="hkjhk", Text4="kl", Text5="fgfhgf"}
};
}
public class Texts
{
public string Text1 { get; set; }
public string Text2 { get; set; }
public string Text3 { get; set; }
public string Text4 { get; set; }
public string Text5 { get; set; }
}
XAML:
<Grid DataContext="{DynamicResource viewModel}">
<FrameworkElement.Resources>
<local:TextsViewModel x:Key="viewModel"/>
</FrameworkElement.Resources>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<DataGrid x:Name="dataGrid" ItemsSource="{Binding Rows}"
HorizontalAlignment="Center"/>
<Button Content="Get Widths" Grid.Row="1"
Click="GetWidthsClick"
Margin="5" Padding="15 5"/>
</Grid>