2015-12-18 42 views
0

enter image description hereWPF如何改變畫布圖像位置編程

我對我的最後一年和IM做關於WPF項目中的學生,但我完全新的WPF,我被分配一些任務,但即時通訊目前停留在如何改變programitically從左right.below畫布上的圖像位置在代碼

<<Window x:Class="changing_bird_position.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="MainWindow" Height="450" Width="800"> 
<StackPanel> 
    <Canvas Name="canvas" Background="LightBlue" Width="500" Height="280" Margin="264,0,28,0"> 
     <Image Source="inlandbird.png" Name="Image" Height="43" Canvas.Left="55" Canvas.Top="22"/> 
    </Canvas> 

    <Button Content="Button" Click="Button_Click" Width="50" Height="50" Margin="246,0"/> 
</StackPanel> 

Xaml.cs

public partial class MainWindow : Window 
{ 
    Image img = new Image(); 
    public MainWindow() 
    { 
     InitializeComponent(); 

    } 

    private void Button_Click(object sender, RoutedEventArgs e) 
    { 
     Canvas.SetLeft(img, 200.0); 
     Canvas.SetTop(img, 200.0); 
+0

你可以使用Canvas.GetLeft來獲取圖像的當前位置和使用,在Canvas.SetLeft與增量移動圖像在一個循環內。 Canvas.SetLeft(birdImage,Canvas.GetLeft(birdImage)+ 5); – JTK

回答

0

在你的代碼背後你不需要創建一個圖像(img)的這個實例。您可以通過它的名稱屬性訪問圖像。

我將xaml中的圖像重新命名爲清晰。

XAML:

<Window x:Class="WpfApplication15.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="450" Width="800"> 
    <StackPanel> 
     <Canvas Name="canvas" Background="LightBlue" Width="500" Height="280" Margin="264,0,28,0"> 
      <Image Source="inlandbird.png" Name="BirdImage" Height="43" Canvas.Left="55" Canvas.Top="22"/> 
     </Canvas> 

     <Button Content="Button" Click="Button_Click" Width="50" Height="50" Margin="246,0"/> 
    </StackPanel> 
</Window> 

後面的代碼:

/// <summary> 
    /// Interaction logic for MainWindow.xaml 
    /// </summary> 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
     } 

     private void Button_Click(object sender, RoutedEventArgs e) 
     { 
      Canvas.SetLeft(BirdImage, 200.0); 
      Canvas.SetTop(BirdImage, 200.0); 
     } 
    } 
}