首页 > 解决方案 > 根据 WPF 控件的当前位置设置 X、Y 边距

问题描述

我制作了一个简单的用户控件来呈现一个简单的音乐栏。

<UserControl x:Class="EzHarmony.ScoreUserControl.BarRenderer"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:EzHarmony.ScoreUserControl"
         mc:Ignorable="d" >
<Canvas>
    <StackPanel Name="StackPanel_Staff" Orientation="Vertical" Canvas.ZIndex="1">
        <Line Stroke="Black" X1="0" Y1="10" X2="200" Y2="10"></Line>
        <Line Stroke="Black" X1="0" Y1="10" X2="200" Y2="10"></Line>
        <Line Stroke="Black" X1="0" Y1="10" X2="200" Y2="10"></Line>
        <Line Stroke="Black" X1="0" Y1="10" X2="200" Y2="10"></Line>
        <Line Stroke="Black" X1="0" Y1="10" X2="200" Y2="10"></Line>
    </StackPanel>

    <Line Stroke="Black" X1="0" Y1="10" X2="0" Y2="52"></Line>
    <Line Stroke="Black" X1="200" Y1="10" X2="200" Y2="52"></Line>
</Canvas>

这是一个呈现 4 小节乐谱的示例用户控件

<UserControl x:Class="EzHarmony.ScoreUserControl.OneStaffScore"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:EzHarmony.ScoreUserControl"
         mc:Ignorable="d" >
<WrapPanel>
    <local:BarRenderer></local:BarRenderer>
    <local:BarRenderer></local:BarRenderer>
    <local:BarRenderer></local:BarRenderer>
    <local:BarRenderer></local:BarRenderer>
</WrapPanel>

但结果只显示一个条形图。 在此处输入图像描述

我想这是因为LineX、Y边距都相同。我该如何解决它,以便在其区域中绘制每个 Bar 渲染器的线条?

预期的输出应该是这样的: 在此处输入图像描述

谢谢你。

标签: wpfcanvasuser-controls

解决方案


不知何故,所有 BarRenderer(画布)都缩小到零。添加一些尺寸:

<WrapPanel>
    <local:BarRenderer Width="200" Height="52"/>
    <local:BarRenderer Width="200" Height="52"/>
    <local:BarRenderer Width="200" Height="52"/>
    <local:BarRenderer Width="200" Height="52"/>
</WrapPanel>

它看起来只有一个栏,因为 Canvas 内容甚至显示在边界之外,并且 4 个 BarRenderer 在同一位置彼此顶部显示


推荐阅读