如何设置 DataGridColumn 的宽度以适合内容(“自动”),但完全填充 MVVM 中 DataGrid 的可用空间?

发布于 2024-10-17 12:37:35 字数 1735 浏览 2 评论 0原文

我有一个包含一些数据的 WPF DataGrid。我想设置列的宽度,使内容适合并且永远不会被裁剪(相反,水平滚动条应该变得可见)。此外,我希望 DataGrid 填充整个可用位置(我正在使用 DockPanel)。我正在使用以下代码(简化):

<DataGrid ItemsSource="{Binding Table}">
    <DataGrid.Columns>
        <DataGridTextColumn MinWidth="100" Width="Auto" Header="Column 1" Binding="{Binding Property1}" />
        <DataGridTextColumn MinWidth="200" Width="Auto" Header="Column 2" Binding="{Binding Property2}" />
    </DataGrid.Columns>
</DataGrid>

这显然不能用 Width="Auto" 开箱即用,因为它总是看起来像这样:

DataGrid: 仅该行的第一部分被标记为“选定”

这显然看起来很难看。我想选择整行,或者选择列来填充整个宽度,这会更好,但正如人们所看到的,这是行不通的。

如果我使用 Width="*" ,列的内容会被裁剪,这对我来说更糟糕。

我在这里发现了一个类似的问题,并且那里发布了一个解决方法。这可能有效,但我正在使用 MVVM 模式,因此 ItemsSource 在 ViewModel 中更新,并且我无法考虑从那里执行此操作的方法,因为我无法访问 ActualWidth DataGridColumn 属性。另外,如果可能的话,我只想在 XAML 中执行此操作。

我将不胜感激任何帮助。谢谢!

编辑:由于我仍然不知道该怎么办,所以我开始了一笔小额赏金。如果有人提出可以解决我的问题的建议,我将非常高兴。再次感谢!

编辑2:在saus的回答之后,我再次考虑了这些选项。问题是我还需要在应用程序运行期间更新 WidthMinWidth 属性,因此不仅仅是在加载窗口之后。我已经尝试做类似

column.Width = new DataGridLength(1, DataGridLengthUnitType.Auto);
column.MinWidth = column.ActualWidth;
column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);

DataGrid 的底层 ItemsSource 更新时触发的某些事件。但是,这不起作用,因为在将 Width 设置为 Auto 后,ActualWidth 属性似乎没有改变。是否可以选择以某种方式“重新绘制”它以便更新 ActualWidth 属性?谢谢!

I have a WPF DataGrid that contains some data. I would like to set the width of the columns such that the content fits in and never gets cropped (instead, a horizontal scroll bar should become visible). Additionally, I want the DataGrid to fill the whole place available (I am working with a DockPanel). I am using the following code (simplified):

<DataGrid ItemsSource="{Binding Table}">
    <DataGrid.Columns>
        <DataGridTextColumn MinWidth="100" Width="Auto" Header="Column 1" Binding="{Binding Property1}" />
        <DataGridTextColumn MinWidth="200" Width="Auto" Header="Column 2" Binding="{Binding Property2}" />
    </DataGrid.Columns>
</DataGrid>

This apparently does not work out of the box with Width="Auto" as it always looks something like this:

DataGrid: only the first part of the row is marked as "selected"

This obviously looks ugly. I would like to have the whole row selected, or, which would be much better, the columns to fill the whole width, but as one can see, this does not work.

If I use Width="*" instead, the content of the columns gets cropped which is even worse for me.

I found a similar question here, and a workaround was posted there. This may work, but I am working with the MVVM pattern, so the ItemsSource gets updated in the ViewModel and I cannot think about a way of doing it from there, because I cannot access the ActualWidth property of the DataGridColumn. Also, I would like to do it only in XAML if possible.

I would appreciate any help. Thanks!

Edit: As I still don't have a clue what to do about it, I start a small bounty. I would be very happy about a suggestion what one could do about my problem. Thanks again!

Edit 2: After saus' answer I thought about the options again. The problem is that I need to update the Width and the MinWidth properties also during the application is running, so not only after loading the window. I already tried to do something like

column.Width = new DataGridLength(1, DataGridLengthUnitType.Auto);
column.MinWidth = column.ActualWidth;
column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);

in some event that is fired when the underlying ItemsSource of the DataGrid is updating. However, this does not work, as the ActualWidth property does not seem to change after setting the Width on Auto. Is there an option to somehow "repaint" it in order to get the ActualWidth property updated? Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

つ低調成傷 2024-10-24 12:37:35

我建议使用您链接到的解决方法。它确实有效。在视图的代码隐藏中,将以下内容添加到构造函数中的 InitializeComponent(): 后

Griddy.Loaded += SetMinWidths; // I named my datagrid Griddy

,并将 SetMinWidths 定义为:

public void SetMinWidths(object source, EventArgs e )
        {
            foreach (var column in Griddy.Columns)
            {
                column.MinWidth = column.ActualWidth;
                column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
            }
        }

我假设您不想使用此解决方案的原因是您认为 MVVM 禁止代码隐藏中的代码。但由于这完全是视图特定的逻辑,我相信在这种情况下这是合理的。整个“MVVM 禁止代码隐藏中的代码”这件事有点误解。

但是,如果您受到样式指南的约束,或者您希望此逻辑可用于应用程序中的所有数据网格,则可以创建一个附加行为来完成如下工作:

public class SetMinWidthToAutoAttachedBehaviour 
    {
        public static bool GetSetMinWidthToAuto(DependencyObject obj)
        {
            return (bool)obj.GetValue(SetMinWidthToAutoProperty);
        }

        public static void SetSetMinWidthToAuto(DependencyObject obj, bool value)
        {
            obj.SetValue(SetMinWidthToAutoProperty, value);
        }

        // Using a DependencyProperty as the backing store for SetMinWidthToAuto.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SetMinWidthToAutoProperty =
            DependencyProperty.RegisterAttached("SetMinWidthToAuto", typeof(bool), typeof(SetMinWidthToAutoAttachedBehaviour), new UIPropertyMetadata(false, WireUpLoadedEvent));

        public static void WireUpLoadedEvent(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var grid = (DataGrid)d;

            var doIt = (bool)e.NewValue;

            if (doIt)
            {
                grid.Loaded += SetMinWidths;
            }
        }

        public static void SetMinWidths(object source, EventArgs e)
        {
            var grid = (DataGrid)source;

            foreach (var column in grid.Columns)
            {
                column.MinWidth = column.ActualWidth;
                column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
            }
        }
    }

然后对于您想要应用此行为的任何数据网格,添加以下内容:

<DataGrid ItemsSource="{Binding Table}" local:SetMinWidthToAutoAttachedBehaviour.SetMinWidthToAuto="true">

然后你的良心以及你的代码隐藏就会变得清晰。

I would suggest using the workaround that you linked to. It does work. In the codebehind of your view, add the following to the constructor after InitializeComponent():

Griddy.Loaded += SetMinWidths; // I named my datagrid Griddy

and define SetMinWidths as:

public void SetMinWidths(object source, EventArgs e )
        {
            foreach (var column in Griddy.Columns)
            {
                column.MinWidth = column.ActualWidth;
                column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
            }
        }

I'm assuming that the reason you don't want to use this solution is that you believe that MVVM prohibits code in the codebehind. But since this is entirely view specific logic I believe that it is justified in this case. The whole "MVVM prohibits code in the codebehind" thing is a bit of a misconception.

But if you are bound by style guides, or you want this logic to be available for all datagrids in your app, you can make an attached behaviour that does the job like this:

public class SetMinWidthToAutoAttachedBehaviour 
    {
        public static bool GetSetMinWidthToAuto(DependencyObject obj)
        {
            return (bool)obj.GetValue(SetMinWidthToAutoProperty);
        }

        public static void SetSetMinWidthToAuto(DependencyObject obj, bool value)
        {
            obj.SetValue(SetMinWidthToAutoProperty, value);
        }

        // Using a DependencyProperty as the backing store for SetMinWidthToAuto.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SetMinWidthToAutoProperty =
            DependencyProperty.RegisterAttached("SetMinWidthToAuto", typeof(bool), typeof(SetMinWidthToAutoAttachedBehaviour), new UIPropertyMetadata(false, WireUpLoadedEvent));

        public static void WireUpLoadedEvent(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var grid = (DataGrid)d;

            var doIt = (bool)e.NewValue;

            if (doIt)
            {
                grid.Loaded += SetMinWidths;
            }
        }

        public static void SetMinWidths(object source, EventArgs e)
        {
            var grid = (DataGrid)source;

            foreach (var column in grid.Columns)
            {
                column.MinWidth = column.ActualWidth;
                column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
            }
        }
    }

and then for any datagrid that you want to apply this behaviour to, add the following:

<DataGrid ItemsSource="{Binding Table}" local:SetMinWidthToAutoAttachedBehaviour.SetMinWidthToAuto="true">

And then your conscience, as well as your codebehind, will be clear.

清君侧 2024-10-24 12:37:35

使用在模板列内进行文本换行的 TextBlock:

<DataGrid ItemsSource="{Binding Table}">      
    <DataGrid.Columns>          
        <DataGridTextColumn MinWidth="100" Width="Auto" Header="Column 1"
                            Binding="{Binding Property1}" />          
        <DataGridTemplateColumn Width="*" Header="Column 2">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Property2}" TextWrapping="Wrap" />  
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>  
</DataGrid>

Use a TextBlock with text wrapping inside template column:

<DataGrid ItemsSource="{Binding Table}">      
    <DataGrid.Columns>          
        <DataGridTextColumn MinWidth="100" Width="Auto" Header="Column 1"
                            Binding="{Binding Property1}" />          
        <DataGridTemplateColumn Width="*" Header="Column 2">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Property2}" TextWrapping="Wrap" />  
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>  
</DataGrid>
酷遇一生 2024-10-24 12:37:35

怎么样:

对于你的列的 MinWidth,你设置一个到 dataGrid 的 ScrollContent 的宽度的绑定,使用一个转换器将该宽度除以你需要在转换器后面编写一些代码的列数

,但这将使你的 MVVM 结构保持完整。

虽然可能性很小,但没有时间尝试。

编辑:我对此进行了更多思考,并有一个问题:如果您有一个巨大的列和一些小的列,那么它不会很好地工作。我假设所有列的宽度都相同,但这里的情况显然不是这样。

不过,您可能想探索这种方式。在宽度上使用转换器的绑定是我能想到的唯一可行的方法:因为在计算列的宽度时基本上有两个条件需要考虑,所以没有简单的方法可以做到这一点。

how about this:

for your columns' MinWidth, you setup a binding to the dataGrid's ScrollContent's Width, with a converter that divide this width by the number of columns

you need some code behind for the converter, but this would keep your MVVM structure intact.

might be a long shot though, did not have the time to try it.

Edit: I put some more thought into this and there a pb: it will not work well if you have, say, one huge column and a few small ones. I assumed that all cols are the same width, which is obviously not the case here.

You might want to explore this way though. Using bindings on the Widths with converters is about the only thing I can think of that could work: since you basically have 2 conditions to take into account when calculating a column's width, there will be no easy way to do this.

千纸鹤带着心事 2024-10-24 12:37:35

我将 Event 添加到 DataGrid 中,根据 DataGrid 的实际宽度重新定义它们的宽度:

 private static void OnLoaded(object sender, RoutedEventArgs e)
    {
        DataGrid dg = sender as DataGrid;
        foreach (var column in dg.Columns)
        {
            column.Width = new DataGridLength(dg.ActualWidth / dg.Columns.Count, DataGridLengthUnitType.Pixel);
        }
    }

这行:

column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);

绝对毫无意义。 DataGridLengthUnitType.Star 的定义将列宽度缩小到最小宽度,并使其宽度静态且不可编辑。

I added the Event to the DataGrid that redefine their width regarding to the actual width of the DataGrid:

 private static void OnLoaded(object sender, RoutedEventArgs e)
    {
        DataGrid dg = sender as DataGrid;
        foreach (var column in dg.Columns)
        {
            column.Width = new DataGridLength(dg.ActualWidth / dg.Columns.Count, DataGridLengthUnitType.Pixel);
        }
    }

The line:

column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);

was absolutely senceless. Definition of DataGridLengthUnitType.Star shrinks the columns width to their minimum width, and makes their width static and uneditable.

挽清梦 2024-10-24 12:37:35

将此用于您想要适合其内容的任何列:
宽度=“尺寸到单元格”

use this for any column you want to fit to its content:
Width = "SizeToCells"

梨涡少年 2024-10-24 12:37:35

强制最后一列占据数据网格中的所有剩余空间

grid.Columns[grid.Columns.Count -1].Width = new 
                  DataGridLength(250, DataGridLengthUnitType.Star);

Force the last column to take all the remaining space in datagrid

grid.Columns[grid.Columns.Count -1].Width = new 
                  DataGridLength(250, DataGridLengthUnitType.Star);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文