I'm making an WPF-application that has a databound ListView. When loading the application, the width of the ListViewColumns will auto-resize, but when adding or changing an item it doesn't auto-resize. I've tried refreshing the listview, setting the width of the column to auto, -1 or -2 in both xaml and VB-code and I've tries changing the itemssource to nothing before refilling it with items. This is the xaml code:
我正在制作一个具有数据绑定ListView的WPF应用程序。加载应用程序时,ListViewColumns的宽度将自动调整大小,但在添加或更改项目时,它不会自动调整大小。我已经尝试刷新listview,在xaml和VB代码中将列的宽度设置为auto,-1或-2,并且我尝试将itemssource更改为空,然后再使用项目重新填充它。这是xaml代码:
<ListView x:Name="lsvPersons" Margin="5,5,5,35" ItemsSource="{Binding Persons}">
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding Name}" Header="Name"/>
<GridViewColumn DisplayMemberBinding="{Binding Gender}" Header="Gender"/>
<GridViewColumn DisplayMemberBinding="{Binding Age}" Header="Age"/>
</GridView>
</ListView.View>
</ListView>
<Button x:Name="btnAddPerson" Content="Add" Height="25" Margin="0,0,200,5" Width="80"/>
The binding works with a controller, which gets the persons with Person.getPersons from a SQL-database:
绑定与控制器一起使用,该控制器从SQL数据库获取具有Person.getPersons的人员:
Private oController As New MainController()
Public Sub New()
MyBase.New()
Me.InitializeComponent()
Me.DataContext = oController
End Sub
After pressing the button, a window will open to add a person. After the window is closed, the item is added to the listview with following code, which refreshes the items in the listview:
按下按钮后,将打开一个窗口以添加一个人。窗口关闭后,该项目将添加到列表视图中,并带有以下代码,该代码将刷新列表视图中的项目:
lsvPersons.ItemsSource = Person.getPersons()
So, what do I need to do to auto-resize the columns of the listview when an item is added or editted?
那么,在添加或编辑项目时,我需要做什么来自动调整列表视图的列?
1 个解决方案
#1
0
GridView gv = lvSrchResulsGrid.View as GridView;
if (gv != null)
{
int colNum = 0;
foreach (GridViewColumn c in gv.Columns)
{
// Code below was found in GridViewColumnHeader.OnGripperDoubleClicked() event handler (using Reflector)
// i.e. it is the same code that is executed when the gripper is double clicked
// if (adjustAllColumns || App.StaticGabeLib.FieldDefsGrid[colNum].DispGrid)
// if (adjustAllColumns || fdGridSorted[colNum].AppliedDispGrid)
// {
if (double.IsNaN(c.Width))
{
c.Width = c.ActualWidth;
}
c.Width = double.NaN;
// }
}
}
#1
0
GridView gv = lvSrchResulsGrid.View as GridView;
if (gv != null)
{
int colNum = 0;
foreach (GridViewColumn c in gv.Columns)
{
// Code below was found in GridViewColumnHeader.OnGripperDoubleClicked() event handler (using Reflector)
// i.e. it is the same code that is executed when the gripper is double clicked
// if (adjustAllColumns || App.StaticGabeLib.FieldDefsGrid[colNum].DispGrid)
// if (adjustAllColumns || fdGridSorted[colNum].AppliedDispGrid)
// {
if (double.IsNaN(c.Width))
{
c.Width = c.ActualWidth;
}
c.Width = double.NaN;
// }
}
}