【问题标题】:Stretch line to width of Itemstemplate canvas in itemscontrol在 itemscontrol 中将线条拉伸到 Itemstemplate 画布的宽度
【发布时间】:2011-11-04 21:54:24
【问题描述】:

我有这个代码。出于某种原因,我无法让 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 的上下文。

【问题讨论】:

    标签: wpf xaml itemscontrol itemtemplate itemspanel


    【解决方案1】:

    如果你想绑定到拉伸对象的宽度你应该绑定到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 是一个有用的“布局调试”技巧,可以查看它是否真的存在。从那里你的一种方法应该有效。

    【讨论】:

    • 我试过了,但我的 ContentPresenters 仍然有一个固定的宽度 3。画布宽度随窗口的宽度而变化(使用 Snoop 在运行时检查控件)。
    • ContainerStyle 中的绑定应该是:{Binding ActualWidth, RelativeSource={RelativeSource AncestorType=Canvas}}
    • 优秀。我不需要对齐拉伸,但我会将此标记为答案,因为我认为有人会需要它。
    • @mydogisbox:你说得对,我测试它的“框架”有问题,相应地编辑了我的答案。
    • 我可能正在挖掘一个旧线程,但我正在做类似的事情,令我惊讶的是它在 xaml 中的复杂程度......我的意思是所有这些 东西,为什么甚至必须在那里吗?有什么好的教程吗?
    猜你喜欢
    • 1970-01-01
    • 2014-03-29
    • 2018-05-26
    • 2012-02-04
    • 1970-01-01
    • 2013-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多