如何在代码中定义WPF GridView列的“自动”宽度?

时间:2022-06-21 22:44:25

I want to define the "Auto" width of a GridView Column in the code. How can I do that?

我想在代码中定义GridView列的“自动”宽度。我怎样才能做到这一点?

var grid = (GridView)myListview.View;
grid.Columns.Add(new GridViewColumn
{
   Header = "My Header",
   DisplayMemberBinding = new Binding("MyBinding"),
   Width = ??? // Auto
});

2 个解决方案

#1


14  

GridViewColumn's Width property is of type double, but according to the MSDN page you can set it to Double.NaN ("not a number") to tell it to auto-size.

GridViewColumn的Width属性是double类型,但根据MSDN页面,您可以将其设置为Double.NaN(“非数字”)以告诉它自动调整大小。

If you do that, you have to ask for its ActualWidth if you want to know the width it has auto-sized to.

如果你这样做,你必须要求它的ActualWidth,如果你想知道它自动调整大小的宽度。

#2


2  

In case you're looking to do the same thing in code for the Width property of a Column of a normal Grid control, use GridLength.Auto.

如果您希望在代码中为普通网格控件的列的Width属性执行相同的操作,请使用GridLength.Auto。

#1


14  

GridViewColumn's Width property is of type double, but according to the MSDN page you can set it to Double.NaN ("not a number") to tell it to auto-size.

GridViewColumn的Width属性是double类型,但根据MSDN页面,您可以将其设置为Double.NaN(“非数字”)以告诉它自动调整大小。

If you do that, you have to ask for its ActualWidth if you want to know the width it has auto-sized to.

如果你这样做,你必须要求它的ActualWidth,如果你想知道它自动调整大小的宽度。

#2


2  

In case you're looking to do the same thing in code for the Width property of a Column of a normal Grid control, use GridLength.Auto.

如果您希望在代码中为普通网格控件的列的Width属性执行相同的操作,请使用GridLength.Auto。