WPF Canvas中的坐标

时间:2017-07-05 07:32:27

标签: c# wpf canvas shapes

在XAML文件中定义画布形状的坐标时,是否可以执行以下操作:

<Canvas x:Name="myCanvas"
        DockPanel.Dock="Bottom"
        VerticalAlignment="Stretch">

    <Canvas.Background>
        <SolidColorBrush Color="White" Opacity="100" />
    </Canvas.Background>

    <Ellipse x:Name="ell1"
                Width="30"
                Height="30"
                Stroke="Black"
                StrokeThickness="1"
                Fill="Red" 
                Canvas.Left="100"
                Canvas.Top="50" />

    <Ellipse x:Name="ell2"
                Width="30"
                Height="30"
                Stroke="Black"
                StrokeThickness="1"
                Fill="Red" 
                Canvas.Right="100"
                Canvas.Top="50" />

    <Line Stroke="Black"
            StrokeThickness="1" 
            X1="ell1.Canvas.Right"                              *** look here ***
            Y1="ell1.Canvas.Top + ell1.Height/2"                *** look here ***
            X2="ell2.Canvas.Left"                               *** look here ***
            Y2="ell2.Canvas.Top + ell2.Height/2" />             *** look here ***

</Canvas>

或者唯一的方法是通过C#?

谢谢, 马西莫

2 个答案:

答案 0 :(得分:0)

这应该可以产生所需的结果,而不会有太多的麻烦。您可能需要调整网格的边距。

<Grid DockPanel.Dock="Bottom" Margin="100,50">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition/>
        <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>

    <Ellipse Grid.Column="0" Width="30" Height="30"
             Stroke="Black" StrokeThickness="1" Fill="Red"/>

    <Ellipse Grid.Column="2" Width="30" Height="30"
             Stroke="Black" StrokeThickness="1" Fill="Red"/>

    <Rectangle Grid.Column="1" Fill="Black" Height="1"/>
</Grid>

这更简单:

<DockPanel DockPanel.Dock="Bottom" Margin="100,50">

    <Ellipse DockPanel.Dock="Left" Width="30" Height="30"
             Stroke="Black" StrokeThickness="1" Fill="Red"/>

    <Ellipse DockPanel.Dock="Right" Grid.Column="2" Width="30" Height="30"
             Stroke="Black" StrokeThickness="1" Fill="Red"/>

    <Rectangle Fill="Black" Height="1"/>
</DockPanel>

答案 1 :(得分:0)

您确实可以绑定到这样的附加属性:

<Line ... X2="{Binding Path=(Canvas.Left), ElementName=ell1}" />

但是XAML中没有定义+/个运算符,因此您必须编写一些代码才能将Y1属性设置为50 + 30 / 2

毕竟XAML是标记语言,C#是编程语言。