Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Wpf 如何在XAML中设置项的高度,使它们在父项控件中始终占据相同比例的可用空间?_Wpf_Xaml_Itemscontrol - Fatal编程技术网

Wpf 如何在XAML中设置项的高度,使它们在父项控件中始终占据相同比例的可用空间?

Wpf 如何在XAML中设置项的高度,使它们在父项控件中始终占据相同比例的可用空间?,wpf,xaml,itemscontrol,Wpf,Xaml,Itemscontrol,我有一个带有以下ItemTemplate的ItemsControl: <DataTemplate x:Key="myItemTemplate"> <TextBlock Height="???" Text="{Binding Path=Description}" /> </DataTemplate> 我的问题是,如何设置模板中文本块的高度,使其自动假定ItemsControl.Height div itemsunt垂直空间量 当只有一件物品时,我希

我有一个带有以下ItemTemplate的ItemsControl:

<DataTemplate x:Key="myItemTemplate">
    <TextBlock Height="???" Text="{Binding Path=Description}" />
</DataTemplate>

我的问题是,如何设置模板中文本块的高度,使其自动假定
ItemsControl.Height div itemsunt
垂直空间量

当只有一件物品时,我希望它是容器的全高,当有两件物品时,每件都应该是大小的一半,依此类推


如果可能的话,我更愿意完全在XAML中这样做,以保持我的ViewModel没有UI逻辑。

您可以使用
UniformGrid
作为
ItemsPanelTemplate
,并将
Rows
属性绑定到
ItemsControl
中的项数,如下所示:

<ItemsControl>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Rows="{Binding Items.Count, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}" IsItemsHost="True"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

我没有测试这段代码,所以您需要检查它,但我认为这个想法很清楚

编辑:正如John在下面指出的,这段代码更简单:

<ItemsControl>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Columns="1" IsItemsHost="True"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>


我将尝试并记住这是一个智力练习,因为我对WPF非常陌生。我确信我会在适当的时候得到纠正。我认为您可以通过在高度值后面添加%符号来指定一个恒定的比例,即Height=“50%”。这是欺骗性的,因为它会将父元素内元素高度的所有数值相加,并将每个数值的大小作为其在该总和中的比例。例如,三个文本块,每个高度为=“50%”,每个文本块的高度为(50/150)*datatemplate的高度为1/3。

我想,您考虑的是一个“星形”网格,但在这里不起作用,因为行数未知且不固定。嗯,也许有一个可行的解决方案,但我认为这需要更多的工作。事实上,它比这个简单。如果设置Columns=“1”,UniformGrid将自动为您处理行计数。你需要使用ItemsControl.ItemsPanel来代替ItemTemplate。哦,这很酷。我不知道那件事。谢谢你的提示!感谢您指出我的示例代码中的“bug”。我不小心写了“ItemTemplate”而不是“ItemsPanel”。在上面的消息中修复了它。