WPF DataGrid:调整列大小 [英] WPF DataGrid: resizing columns

查看:425
本文介绍了WPF DataGrid:调整列大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个System.Windows.Controls.DataGrid,其属性CanUserResizeColumns分配给True。现在,我可以通过在2个列标题之间单击鼠标左键来调整列的宽度。

I have a System.Windows.Controls.DataGrid with property CanUserResizeColumns assigned to True. Now I can adjust the width of the columns by using the mouse left button click between 2 column headers.

但是我也希望能够更改列的宽度在dataGrid的任何行中,不仅在列标题中。

But I also want to be able to change the width of the columns in any row of the dataGrid, not only in the column headers. Is it possible?

推荐答案

在您的dataGrid中,您可以使用 DataGridTemplate

In your dataGrid you can use a DataGridTemplate column alogn with a GridSplitter to achieve this..

 <toolkit:DataGridTemplateColumn Header="Text" >
     <toolkit:DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
           <Grid>
              <Grid.ColumnDefinitions>
                 <ColumnDefinition Width="*"/>
                 <ColumnDefinition  Width="Auto"/>
              </Grid.ColumnDefinitions>
              <TextBlock Text="{Binding Text}"/>
              <GridSplitter Grid.Column="1" Width="3"
                            DragIncrement="1"
                            DragDelta="GridSplitter_DragDelta"
                            Tag="{Binding BindsDirectlyToSource=True,
                                    RelativeSource={RelativeSource
                                      AncestorType={x:Type toolkit:DataGridCell}}}"/>
           </Grid>
        </DataTemplate>
     </toolkit:DataGridTemplateColumn.CellTemplate>
 </toolkit:DataGridTemplateColumn>

然后在您的代码后面...执行此操作...

Then in your code behind... do this...

    private void GridSplitter_DragDelta(
         object sender,
         System.Windows.Controls.Primitives.DragDeltaEventArgs e)
    {
        var gridSplitter = sender as GridSplitter;

        if (gridSplitter != null)
        {
            ((DataGridCell) gridSplitter.Tag).Column.Width
                = ((DataGridCell) gridSplitter.Tag).Column.ActualWidth +
                  e.HorizontalChange;
        }
    }

这样,单个单元格级别的GridSplitter可以调整其大小整列。

This way a GridSplitter at individual cell level can resize its entire column.

如果您使用的是MVVM,则应将上述事件处理程序置于附加行为中

这篇关于WPF DataGrid:调整列大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆