1

我有这个代码。出于某种原因,我无法让 contentpresenter 拉伸以填充画布的宽度。我的一些尝试在 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 的上下文。

4

1 回答 1

4

如果要绑定到拉伸对象的宽度,则应绑定到ActualWidth

{Binding ActualWidth, RelativeSource={RelativeSource AncestorType=Canvas}}

编辑: 这可能没有必要

除非您告诉画布,否则画布有不占用任何空间的习惯:

  <ItemsControl ItemsSource="{Binding MarkerLocations, Mode=OneTime}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Canvas Background="Red"
                        HorizontalAlignment="Stretch"
                        VerticalAlignment="Stretch"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
  </ItemsControl>

设置它Background是一个有用的“布局调试”技巧,可以查看它是否真的存在。从那里你的一种方法应该有效。

于 2011-11-04T22:34:18.880 回答