【问题标题】:What is wrong with Canvas.SetTop(element,position)Canvas.SetTop(element,position) 有什么问题
【发布时间】:2016-06-24 11:02:54
【问题描述】:

我正在尝试使用鼠标和通过代码移动和重新定位元素。但我想我错过了什么或做错了什么。所以我构建了一个小示例应用程序。它只是一个带有此 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;
    }

【问题讨论】:

  • @Clemens:为什么要评论

标签: wpf canvas mouse controls move


【解决方案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);

【讨论】:

  • 好的 - 明白了。如何在不成为画布子项的情况下移动控件。我的意思是,如果我没有像我的例子那样的画布。
  • 如果您没有 Canvas,请在您的 XAML 中添加一个。当然还有其他方法可以定位元素,比如设置它的MarginLayoutTransformRenderTransform,但Canvas 是典型的方法。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-18
    • 2011-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多