我试图通过手动绑定这里的属性来解决我之前的问题,这是我的 XAML 代码的第一个版本。Width
DataGridTextColumn
<DataGrid AutoGenerateColumns="False" Background="White" ItemsSource="{Binding Items, Mode=OneWay}"
HorizontalGridLinesBrush="Silver" VerticalGridLinesBrush="Silver"
Margin="332,10,10,10" CanUserAddRows="False" CanUserDeleteRows="False"
x:Name="myDataGrid" ColumnWidth="*">
<DataGrid.Columns>
<DataGridTextColumn Width="{Binding Path=ActualWidth, Converter={StaticResource ResourceKey=WidthValueConverter}, RelativeSource={RelativeSource AncestorType=DataGrid}}" IsReadOnly="True" Header="Column1" Binding="{Binding Value1, Mode=OneWay}" />
<DataGridTextColumn Width="{Binding Path=ActualWidth, Converter={StaticResource ResourceKey=WidthValueConverter}, RelativeSource={RelativeSource AncestorType=DataGrid}}" IsReadOnly="True" Header="Column2" Binding="{Binding Value2, Mode=OneWay}"/>
<DataGridTextColumn Width="{Binding Path=ActualWidth, Converter={StaticResource ResourceKey=WidthValueConverter}, RelativeSource={RelativeSource AncestorType=DataGrid}}" IsReadOnly="True" Header="Column3" Binding="{Binding Value3, Mode=OneWay}"/>
</DataGrid.Columns>
</DataGrid>
经过一番研究,我发现这篇文章似乎为我的问题提供了答案,我更新了我的DataGrid
代码。
<DataGrid AutoGenerateColumns="False" Background="White" ItemsSource="{Binding Items, Mode=OneWay}"
HorizontalGridLinesBrush="Silver" VerticalGridLinesBrush="Silver"
Margin="332,10,10,10" CanUserAddRows="False" CanUserDeleteRows="False"
x:Name="myDataGrid" ColumnWidth="*">
<DataGrid.Columns>
<DataGridTextColumn Width="{Binding Path=ActualWidth, Converter={StaticResource ResourceKey=WidthValueConverter}, Source={x:Reference Name=myDataGrid}}" IsReadOnly="True" Header="Column1" Binding="{Binding Value1, Mode=OneWay}" />
<DataGridTextColumn Width="{Binding Path=ActualWidth, Converter={StaticResource ResourceKey=WidthValueConverter}, Source={x:Reference Name=myDataGrid}}" IsReadOnly="True" Header="Column2" Binding="{Binding Value2, Mode=OneWay}"/>
<DataGridTextColumn Width="{Binding Path=ActualWidth, Converter={StaticResource ResourceKey=WidthValueConverter}, Source={x:Reference Name=myDataGrid}}" IsReadOnly="True" Header="Column3" Binding="{Binding Value3, Mode=OneWay}"/>
</DataGrid.Columns>
</DataGrid>
但现在我得到了这个 XamlParseException
Cannot call MarkupExtension.ProvideValue because of a cyclical dependency. Properties inside a
MarkupExtension cannot reference objects that reference the result of the MarkupExtension.
The affected MarkupExtensions are:
'System.Windows.Data.Binding' Line number '37' and line position '37'.
'System.Windows.Data.Binding' Line number '38' and line position '37'.
'System.Windows.Data.Binding' Line number '39' and line position '37'.
那么如何将 a 的Width
属性绑定到其父级DataGridColumn
的属性ActualWidth
DataGrid