【问题标题】:wpf stretch a line when resizing the canvas parentwpf在调整画布父级时拉伸一条线
【发布时间】:2012-06-25 14:17:27
【问题描述】:

我有一条垂直线和一条水平线,当我动态调整我的画布父级时,我想调整它们的大小。 (地标)

我希望水平线始终距离画布的左右边界 25 距离,距离底部边界 13 距离。

垂直线也是如此,距上下边框 25 处,距左边框 13 处。

有简单的解决方案吗? 我可以将我的画布更改为另一个控件吗?

【问题讨论】:

    标签: wpf canvas resize line stretch


    【解决方案1】:

    只需将线条粘贴在画布顶部的网格中即可获得正确的行为

    <Grid Width="600" Height="600">
       <Canvas Background="LightBlue">
        // stuff here
       </Canvas>
       <Grid>
          <Rectangle Fill="Black" Height="1" 
             Stroke="Black" VerticalAlignment="Bottom" Margin="25,0,25,13"/>
          <Rectangle Fill="Black" 
             HorizontalAlignment="Left" Stroke="Black" Width="1" Margin="13,25,0,25"/>
       </Grid>
    </Grid>
    

    【讨论】:

    • 比使用转换器更清晰的解决方案,尽管我建议在内容 Canvas 上使用 Margin="25,0,0,25" 以避免将其绘制在线条之上
    • 可能需要在线条顶部绘制:)
    • 我已经设置了我的边距以完美地适合我的画布(我有图例的文字,我忘了提及......)谢谢大家的快速回答! !! ^^
    【解决方案2】:

    我会根据CanvasActualHeightActualWidth 使用Converters 来设置Line 对象的高度、宽度和位置

    为避免编写一堆单独的转换器,我在我的博客上发布了一个MathConverter,可用于所有计算。

    <Canvas x:Name="MyCanvas">
    
        <!-- Horizontal Line: 25 from each side, and 13 from bottom -->
        <!-- May need to adjust the Canvas.Top ConverterParameter based on Line height -->
        <Line Height="1"
              Canvas.Left="25"
              Canvas.Top="{Binding ElementName=MyCanvas, Path=ActualHeight, 
                  Converter={StaticResource MathConverter}, 
                  ConverterParameter=@VALUE-14}"
              Width="{Binding ElementName=MyCanvas, Path=ActualWidth, 
                  Converter={StaticResource MathConverter}, 
                  ConverterParameter=@VALUE-50}" ... />
    
    
        <!-- Vertical Line: 25 from top and bottom, and 13 from left -->
        <Line Canvas.Left="13" Canvas.Top="25"
              Height="{Binding ElementName=MyCanvas, Path=ActualHeight, 
                  Converter={StaticResource MathConverter}, 
                  ConverterParameter=@VALUE-50}" ... />
    
    </Canvas>
    

    因为这些都是 Bindings,所以只要绑定的属性发生变化,它们就会被刷新(MyCanvas.ActualHeightMyCanvas.ActualWidth

    【讨论】:

    • 您的解决方案看起来很完美,我可以看到与 vs 设计器完美匹配的线条边框,但线条保持透明,当我启动应用程序时,线条保持透明。我是这里的新手,所以我必须等待 8 小时才能回答我的问题。到时候我会详细给你看我的代码,也可以自己搜索^^
    • @user1462911 不要忘记给你的线条颜色和粗细。我将它们排除在我的代码示例之外,以专注于影响定位和大小的属性。
    • 我会保留你的转换器,它看起来非常有用且易于使用!!我想我以后必须在同一个项目中使用它。
    • 是的,我已经将我的 Line 的 Height、Stroke 和 StrokeThickness 属性设置为 2、White 和 2,这就是我不理解这种行为的原因
    【解决方案3】:

    如果您需要设置Margin,请使用Grid 而不是Canvas

    要使您的线条与边框有空间,请转到“属性”并在“布局区域”中使用Margin 来设置空间。对于您的水平线,将VerticalAlignment 设置为Bottom,将Horizo​​ntalAlignment 设置为Stretch。在这种情况下,保证金应为25,0,25,13

    对于您的垂直线,将VerticalAlignment 设置为Stretch 并将HorizontalAlignment 设置为Left。保证金应该是13,25,0,25

    祝你好运

    【讨论】:

    • 很高兴能帮到你;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-27
    • 1970-01-01
    • 2012-04-26
    • 1970-01-01
    • 1970-01-01
    • 2013-05-06
    • 2015-11-28
    相关资源
    最近更新 更多