如何根据 WPF 中的窗口大小调整某个控件的大小? [英] How to resize a certain control based on Window size in WPF?
问题描述
我有一个 ListView
控件,我想在其中调整最后一列的大小以与 Window
的大小同步.因此,如果 Window
的宽度增加 100 个单位,我希望列的宽度也增加 100.
I have a ListView
control where I want to resize the last column in sync with the size of the Window
. So if the Window
's width increases by 100 units, I want the columns' width to also increase by 100.
我是否应该在窗口上使用 Resize
事件并使用幻数手动调整列标题的大小,有点像?:
Should I be using the Resize
event on the Window and use a magic number to resize the column header manually, sort of like?:
columnHeader.Width = windowSize.X - 400;
推荐答案
我不能完全相信这个答案,因为我知道了 这里
I can't take full credit for this answer, because I got it here
但基本上就是这个想法:
But basically this is the idea:
用GridView替换listView中的View".然后,您可以为第一列指定所需的任何宽度.在本例中为 100、50、50.然后我们在最后一列上添加一个绑定,它将父 ListView 控件作为输入.但是我们允许转换器为我们做脏活.
Replace the "View" in the listView with a GridView. Then, you can specify whatever width you want for the first columns. In this case 100, 50, 50. Then we add a binding on the final column, that takes as input the parent ListView control. But we are allowing a converter to do the dirty work for us.
<ListView>
<ListView.View>
<GridView>
<GridViewColumn Header="Title" DisplayMemberBinding="{Binding}" Width="100"/>
<GridViewColumn Header="Title" DisplayMemberBinding="{Binding}" Width="50"/>
<GridViewColumn Header="Title" DisplayMemberBinding="{Binding}" Width="50"/>
<GridViewColumn Header="4" DisplayMemberBinding="{Binding}">
<GridViewColumn.Width>
<MultiBinding Converter="{StaticResource starWidthConverter}">
<Binding Path="ActualWidth" RelativeSource="{RelativeSource AncestorType=ListView}"/>
<Binding RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=ListView}"/>
</MultiBinding>
</GridViewColumn.Width>
</GridViewColumn>
</GridView>
</ListView.View>
<ListViewItem>item1</ListViewItem>
<ListViewItem>item2</ListViewItem>
<ListViewItem>item3</ListViewItem>
<ListViewItem>item4</ListViewItem>
</ListView>
因此,在转换器Convert"函数中,我们这样做:
So, in the converter 'Convert' function we do this:
ListView listview = value[1] as ListView;
double width = listview.ActualWidth;
GridView gv = listview.View as GridView;
for(int i = 0;i < gv.Columns.Count-1;i++)
{
if(!Double.IsNaN(gv.Columns[i].Width))
width -= gv.Columns[i].Width;
}
return width - 5;// this is to take care of margin/padding
获取列表视图的宽度,并计算新的大小.
Which grabs the listview width, and calculates the new size.
这篇关于如何根据 WPF 中的窗口大小调整某个控件的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!