使用其他datagrid的标头宽度绑定一个数据网格的标头宽度

时间:2013-09-19 11:02:24

标签: .net wpf xaml datagrid styles

我有两个网格,如下面

<DataGrid ScrollViewer.CanContentScroll="False" GridLinesVisibility="All" VerticalGridLinesBrush="#bdced4" HorizontalGridLinesBrush="#bdced4" 
                RowHeaderWidth="41" HeadersVisibility="All" x:Name="MonitorListHeader" Loaded="MonitorList_Loaded" LoadingRow="dg_LoadingRow" 
                CanUserAddRows="False" CanUserResizeRows="False" 
                CanUserReorderColumns="False" SelectionUnit="Cell" HorizontalAlignment="Stretch" AutoGenerateColumns="false"
                HorizontalScrollBarVisibility="Hidden" >
            <DataGrid.Columns>
                <DataGridTemplateColumn Width="75" Header="ID">
                </DataGridTemplateColumn>

                <DataGridTemplateColumn 
                    Width="{Binding ElementName=CableColumn, Path=ActualWidth}" 
                    Header="Cable">
                </DataGridTemplateColumn>

                <DataGridTemplateColumn Width="*" Header="Port/IP">
                </DataGridTemplateColumn>

                <DataGridTemplateColumn Width="*" Header="Status">
                </DataGridTemplateColumn>    
            </DataGrid.Columns>                
        </DataGrid>

<DataGrid ScrollViewer.CanContentScroll="False" GridLinesVisibility="All" VerticalGridLinesBrush="#bdced4" HorizontalGridLinesBrush="#bdced4" 
                RowHeaderWidth="41" HeadersVisibility="All" x:Name="MonitorList" Loaded="MonitorList_Loaded" LoadingRow="dg_LoadingRow" 
                CanUserAddRows="False" CanUserResizeRows="False" 
                CanUserReorderColumns="False" SelectionUnit="Cell" HorizontalAlignment="Stretch" AutoGenerateColumns="false"
                HorizontalScrollBarVisibility="Hidden" >
            <DataGrid.Columns>
                <DataGridTemplateColumn Width="75" Header="ID">
                </DataGridTemplateColumn>

                <DataGridTemplateColumn x:Name="CableColumn"
                    Width="*" Header="Cable">
                </DataGridTemplateColumn>

                <DataGridTemplateColumn Width="*" Header="Port/IP">
                </DataGridTemplateColumn>

                <DataGridTemplateColumn Width="*" Header="Status">
                </DataGridTemplateColumn>    
            </DataGrid.Columns>                
        </DataGrid>

现在我想将第二个网格的第三列标题宽度与第一个网格的第三列标题宽度绑定。

有人可以告诉我这个绑定代码吗?

谢谢!!!!!!

1 个答案:

答案 0 :(得分:1)

我重新命名了元素以使其更清晰:

XAML:

... First DataGrid ...
<DataGridTemplateColumn Width="*" Header="Cable" x:Name="SourceColumn" />
...

...Second DataGrid ...
<DataGridTemplateColumn Width="*" Header="Cable" x:Name="TargetColumn" />
...

后面的代码(在构造函数中,紧跟在InitializeComponent();之后):

var binding = new Binding("Width");
binding.Source = SourceColumn;
binding.Mode = BindingMode.TwoWay;
BindingOperations.SetBinding(TargetColumn, DataGridColumn.WidthProperty, binding);

我找了一个纯XAML解决方案,但我没有工作。