2012-02-17 162 views
2

我想在鼠標懸停時更改圖像的位置。我有:更改WPF中的圖像位置

<Image 
    Name="cat" 
    Source="CatRun.bmp" 
    Visibility="Hidden" 
    HorizontalAlignment="Center" 
    VerticalAlignment="Center" 
    Width="100" 
    Height="100" 
    UIElement.MouseEnter="cat_MouseEnter"/> 

在XAML和:

private void cat_MouseEnter(object sender, MouseEventArgs e) 
{ 

} 
在C#

如何在畫布上專門設置位置?

+2

VAR =圖像(圖像)發送者; Canvas.SetLeft(image,42); – 2012-02-17 22:49:00

回答

4

下面是一個例子:

<Canvas x:Name="canvas"> 
    <Rectangle x:Name="rect" Width="20" Height="20" Canvas.Left="10" Canvas.Top="10" Fill="Blue" MouseEnter="RectangleMouseEnter" /> 
</Canvas> 

您需要頂部設置附加屬性,左(或底部,右)

private void RectangleMouseEnter(object sender, MouseEventArgs e) 
    { 
     Canvas.SetTop(rect, 50); 
     Canvas.SetLeft(rect, 50); 
    } 
1

爲了設置圖像的位置在畫布上從後臺代碼,你可以使用類似:

private void cat_MouseEnter(object sender, MouseEventArgs e) 
{ 
    Canvas.SetLeft(cat, 100); //set x coordinate of cat Image to 100 
    Canvas.SetTop(cat, 300); //set y coordinate of cat Image to 300 
} 

更新: 在某些情況下,你可能無法訪問cat按名稱從該方法中獲取對象。爲了使它工作,只需使用發件人對象,該對象應該是導致該事件的Image,如H.B.在他的評論中描述。

+1

這可能會失敗,取決於名望... – 2012-02-17 22:54:25

+0

是的,你是對的,它不會編譯。我會用更多的信息更新答案。 – 2012-02-17 22:56:09