我正在尝试以编程方式将列的宽度从一个表绑定到另一个表中的列的宽度。我该怎么做?这是我的代码:
DataGridTextColumn classNameColumn = new DataGridTextColumn();
classNameColumn.Header = "CLASS";
classNameColumn.Binding = new Binding("CLASS_NAME");
classNameColumn.IsReadOnly = true;
ScheduleGrid.Columns.Add(classNameColumn);
DataGridTextColumn noneColumn = new DataGridTextColumn();
noneColumn.Header = "";
var bindingWidth = new Binding("Width") { Source = classNameColumn, Mode = BindingMode.TwoWay };
BindingOperations.SetBinding(noneColumn, WidthProperty, bindingWidth);
WeeekHeaderGrid.Columns.Add(noneColumn);
在XAML代码中,这工作正常:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<DataGrid x:Name="ScheduleGrid" Grid.Row="1" AutoGenerateColumns="False" SelectionMode="Single"
CanUserReorderColumns="False" CanUserAddRows="False" CanUserSortColumns="False"
CellEditEnding="ScheduleGrid_CellEditEnding">
<DataGrid.Columns>
<DataGridTextColumn x:Name="ClassName" Header="CLASS" Binding="{Binding CLASS_NAME}" />
</DataGrid.Columns>
</DataGrid>
<DataGrid x:Name="WeeekHeaderGrid" Grid.Row="0" CanUserReorderColumns="False" CanUserAddRows="False" CanUserSortColumns="False" CanUserResizeColumns="True">
<DataGrid.Columns>
<DataGridTextColumn Header="" Width="{Binding Source={x:Reference ClassName}, Path=Width, Mode=TwoWay}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
答案 0 :(得分:1)
您在代码中使用了错误的WidthProperty
DP。
将其更改为
BindingOperations.SetBinding(noneColumn, DataGridColumn.WidthProperty, bindingWidth);
DataGridColumn.WidthProperty
的类型为DataGridLength
。
答案 1 :(得分:0)
Width="{Binding ElementName=ClassName, Path=ActualWidth}"
那应该有用。