I’m facing an issue in my WPF application regarding synchronizing the column widths of a DataGrid and its row details. While I’ve managed to achieve one-to-one adaptive alignment of column widths, I also need to combine the widths of multiple columns.
I’m using a multi-value converter to calculate the total width of the DataGrid columns and applying it to Row Details.
enter image description here
my first table:
<UserControl x:Class="TableUserControl">
<DataGrid x:Name="DTGrid" ItemsSource="{Binding ItemsViewCollection, UpdateSourceTrigger=PropertyChanged}">
<DataGrid.Columns>
<DataGridTextColumn Header="Col1" Binding="{Binding Date}" x:Name="DateElement"/>
<DataGridTextColumn Header="Col2" Binding="{Binding Id}" x:Name="IdElement"/>
<DataGridTextColumn Header="Col3" Binding="{Binding Info}" x:Name="InfoElement"/>
</DataGrid.Columns>
<DataGrid.RowDetailsTemplate>
<DataTemplate>
<DockPanel>
<uc:DetailsTableUserControl ItemsSource="{Binding EditHistoryStore}" />
</DockPanel>
</DataTemplate>
</DataGrid.RowDetailsTemplate>
</DataGrid>
</UserControl>
my second table:
<UserControl x:Class="DetailsTableUserControl">
<UserControl.Resources>
<converters:WidthConverter x:Key="WidthConverter"/>
<DiscreteObjectKeyFrame x:Key="DateElementColProxy" Value="{Binding ElementName=DateElement}"/>
<DiscreteObjectKeyFrame x:Key="IdElementColProxy" Value="{Binding ElementName=IdElement}"/>
<DiscreteObjectKeyFrame x:Key="InfoElementColProxy" Value="{Binding ElementName=InfoElement}"/>
</UserControl.Resources>
<DataGrid x:Name="DetailsTable" ItemsSource="{Binding ItemsSource,RelativeSource={RelativeSource AncestorType=UserControl}}">
<DataGrid.Columns>
<DataGridTextColumn Header="Col1" Binding="{Binding IdDetails}" x:Name="IdDetailsElement"
Width="{Binding Path=Value.Width, Mode=TwoWay, Source={StaticResource IdElementColProxy}}"/>
<DataGridTextColumn Header="Col2_3" Binding="{Binding InfoDetails}" x:Name="AboutElement">
<DataGridTextColumn.Width>
<MultiBinding Converter="{StaticResource WidthConverter}">
<Binding Source="{StaticResource DateElementColProxy}" Path="Value.Width" Mode="TwoWay"/>
<Binding Source="{StaticResource InfoElementColProxy}" Path="Value.Width" Mode="TwoWay"/>
</MultiBinding>
</DataGridTextColumn.Width>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</UserControl>
my converter with eror :
InvalidCastException: Unable to cast object of type ‘MS.Internal.NamedObject’ to type ‘System.Double’.
public class WidthConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
double totalWidth = 0;
foreach (double Width in values)
{
if (Width is double)
totalWidth += Width;
}
return new DataGridLength(totalWidth);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
How can I modify the converter so that it correctly calculates the size of the multi columns?