Canvas.SetTop有什么问题(元素,位置)

时间:2016-06-24 11:02:55

标签: wpf canvas mouse controls move

我正在尝试使用鼠标和代码移动和重新定位元素。但我想我错过了一些东西或做错了事。所以我构建了一个小样本应用程序。它只是一个具有此MainWindow功能的空wpf应用程序

    public MainWindow()
    {
        InitializeComponent();
        Label lText = new Label();
        lText.Content = "this is my test label";
        lText.Height = 50;
        lText.Width = 50;
        lText.Background = Brushes.Aqua;
        // do I really need to do this? 
        lText.VerticalAlignment = System.Windows.VerticalAlignment.Top;
        lText.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
        // this part already fails
        Canvas.SetTop(lText, 20);
        Canvas.SetLeft(lText, 10);
        this.Content = lText;
    }

2 个答案:

答案 0 :(得分:1)

附加属性Canvas.LeftCanvas.Top(后面的代码由Canvas.SetLeftCanvas.SetTop方法设置)仅对直接元素产生影响Canvas控制的孩子。

因此,在MainWindow的XAML中声明Canvas为Content元素:

<Window ...>
    <Canvas x:Name="canvas" />
</Window>

然后在后面的代码中将元素添加到Canvas'Children集合中:

Canvas.SetTop(lText, 20);
Canvas.SetLeft(lText, 10);
canvas.Children.Add(lText);

答案 1 :(得分:0)

解决方案是必须在Xaml中设置Left和Top属性才能读取它。我总是得到NaN,因此无法设置正确的值。