在ItemsControl中将线拉伸到ItemsTemplate画布的宽度 [英] Stretch line to width of Itemstemplate canvas in itemscontrol
问题描述
我有这个代码.由于某种原因,我无法让contentpresenter拉伸以填充画布的宽度.我的几次尝试都在xaml中被注释掉了.
I have this code. For some reason I can't get the contentpresenter to stretch to fill the width of the canvas. Several of my attempts are commented out in the xaml.
<ItemsControl ItemsSource="{Binding MarkerLocations, Mode=OneTime}" HorizontalContentAlignment="Stretch">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Canvas.Top" Value="{Binding}" />
<Setter Property="Canvas.Left" Value="0" />
<!--Setter Property="Width" Value="{Binding Path=Width, RelativeSource={RelativeSource FindAncestor, AncestorType=Canvas, AncestorLevel=1}}"/-->
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<!--Rectangle Stroke="Black" Height="2" Stretch="Fill"/-->
<Line Stretch="Fill" X2="2" Y1="{Binding Mode=OneTime}" Y2="{Binding Mode=OneTime}" Stroke="Black" StrokeThickness="1"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
我觉得我不了解ItemContainters的上下文.
I have a feeling I'm not understanding the context of the ItemContainters.
推荐答案
如果要绑定到拉伸对象的宽度,则应绑定到ActualWidth
:
If you want to bind to the width of stretching objects you should bind to the ActualWidth
:
{Binding ActualWidth, RelativeSource={RelativeSource AncestorType=Canvas}}
这可能不是必需的
除非您告诉画布,否则画布有根本不占用任何空间的习惯:
Canvases have the habit of not occupying any space at all unless you tell them:
<ItemsControl ItemsSource="{Binding MarkerLocations, Mode=OneTime}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas Background="Red"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
设置其Background
是有用的布局调试"技巧,以查看其实际位置.从那里开始,您的方法之一应该起作用.
Setting its Background
is a useful "layout-debugging" trick to see if its actually there. From there one of your approaches should work.
这篇关于在ItemsControl中将线拉伸到ItemsTemplate画布的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!