2016-06-24 39 views
0

我試圖用鼠標和代碼移動和重新定位元素。但我想我錯過了什麼或者做錯了什麼。所以我建了一個小樣本應用程序。這只是一個空的WPF應用程序與此主窗口功能Canvas.SetTop(元素,位置)有什麼問題

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

@Clemens:爲什麼發表評論 –

回答

0

的解決方案是,左在讀取它之前,必須在Xaml中設置頂部屬性。我總是得到NaN,因此無法設置正確的值。

1

的附加屬性Canvas.LeftCanvas.Top(在後面的代碼是由Canvas.SetLeftCanvas.SetTop方法來設置)只因爲這是一個直接子元素的效果一個Canvas控件。

於是宣佈畫布在你的主窗口的XAML內容元素:

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

然後在代碼中的元素添加到畫布Children系列背後:

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

好 - 理解。我如何移動控件而不是畫布的孩子。我的意思是如果我沒有像我的例子一樣的畫布。 – freeskydiver

+0

如果您沒有Canvas,請將其添加到您的XAML中。當然還有其他方法來定位一個元素,比如設置「Margin」或「LayoutTransform」或「RenderTransform」,但Canvas是實現它的典型方法。 – Clemens