在WPF中,我有一个定义了多个列的Grid,每列的宽度都绑定到DataGrid列的宽度,如下所示:
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{Binding ElementName=dataGrid, Path=RowHeaderWidth}" />
<ColumnDefinition Width="{Binding ElementName=Column0, Path=ActualWidth}" />
<ColumnDefinition Width="{Binding ElementName=Column1, Path=ActualWidth}" />
Etc.
<Controls:DataGrid BorderBrush="White" ItemsSource="{Binding DataTable}"
Name="datagrid1" Grid.Row="2" RowHeaderWidth="0">
<Controls:DataGrid.Columns>
<Controls:DataGridTextColumn Header="Included" Width="50" x:Name="Column0" />
<Controls:DataGridTextColumn Header="First" Width="100" x:Name="Column1" />
Etc.
当我运行程序并手动调整列的大小时,我可以看到Grid列的大小调整(ShowGridLines = true)和绑定到特定Grid列的元素相应地移动。
但是,当我尝试在代码中添加数据网格和Grid列时,我无法使绑定工作(没有绑定错误)。这是一个例子:
binding = new Binding()
{
Source = dataGrid.Columns[col],
Path = new PropertyPath("ActualWidth"),
Mode = BindingMode.OneWay,
};
colDef.SetBinding(WidthProperty, binding);
我尝试了其他变体(例如ElementName =“DataGridColumn1”,Path = new PropertyPath(“ActualWidth”)但是没有错误(没有绑定)或'找不到绑定源'错误或BindingExpression路径错误
必须有办法在代码中设置绑定...?
答案 0 :(得分:6)
我找到了答案。这一行:
colDef.SetBinding(WidthProperty, binding);
应更改为:
colDef.SetBinding(ColumnDefinition.WidthProperty, binding);
答案 1 :(得分:0)
DataGridTextColumn textColumn = new DataGridTextColumn();
textColumn.Width = DataGridLength.SizeToHeader;
Google DataGridLength
获取其他选项....
答案 2 :(得分:0)
在我的项目中我喜欢这样 - 认为值得一提,因为在我得到它之前我遇到了很多问题:
DataGridTextColumn c = new DataGridTextColumn
{
// Binding to my value (not directly related to the question)
Binding = new Binding
{
Path = new PropertyPath(cd.Title + ".Value"),
Mode = BindingMode.TwoWay
}
};
// Binding the width
BindingOperations.SetBinding(c, DataGridTextColumn.WidthProperty, new Binding
{
Source = cd, // An INotifying object
Path = new PropertyPath("Width"), // A Property of that object
Mode = BindingMode.TwoWay
});