2017-05-10 59 views
0

選擇像我使用C#和我創建UWP應用。 我使用Windons.Ui.Xaml.Controls.Image和我已經創建follwoing代碼,其中列出我的圖片從StackPanel的C#UWP(添加動作監聽的UIElement和形象的UIElement)

UxHelpers.DispatchToASTAThread(
async() => 
{ 
    imageIndex++; 
    StackPanel stackPanel = new StackPanel(); 
    stackPanel.Children.Add(image);   
} 
this.Results.Children.Add(stackPanel); 
}).Forget(); 

這是在for循環中,我要當某些圖像上用戶點擊才能夠拯救它。

我有保存的代碼,我只是不知道如何將鼠標監聽器添加到每個圖像,以便在將鼠標移到它上方時進行標記(因此用戶知道通過點擊它會發生某些事情)和當他點擊我想它來調用我的函數與此圖片索引....

我看過的UIElement,但我仍然無法弄清楚。

謝謝!

回答

0

我們可以PointerEntered事件添加到Image控制,當用戶移動鼠標到它,然後我們可以改變UI。然後我們就可以在Tapped事件添加到Image控制,如果用戶點擊它,就會被解僱。

要獲得Image的索引,我們可以將索引設置爲ImageName屬性。

例如:

protected override async void OnNavigatedTo(NavigationEventArgs e) 
{ 
    StackPanel stackPanel = new StackPanel(); 
    for (int i = 0; i < 3; i++) 
    { 
     Windows.Storage.Streams.IRandomAccessStream random = await Windows.Storage.Streams.RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/sun2set.jpg")).OpenReadAsync(); 
     Image image = new Image(); 
     BitmapImage bitmapImage = new BitmapImage(); 
     StackPanel mystackPanel = new StackPanel(); 
     image.Name = i.ToString(); 
     bitmapImage.SetSource(random); 
     image.Source = bitmapImage; 
     mystackPanel.Children.Add(image); 
     image.PointerEntered += Image_PointerEntered; 
     image.PointerExited += Image_PointerExited; 
     stackPanel.Children.Add(mystackPanel); 
    } 
    this.Results.Children.Add(stackPanel); 
} 

private void Image_PointerExited(object sender, PointerRoutedEventArgs e) 
{ 
    var image = sender as Image; 

    var parent = VisualTreeHelper.GetParent(image) as StackPanel; 
    parent.BorderBrush = new SolidColorBrush(Colors.Red); 
    parent.BorderThickness = new Thickness(0); 
    image.Tapped -= Image_Tapped; 
} 

private void Image_PointerEntered(object sender, PointerRoutedEventArgs e) 
{ 
    var image = sender as Image; 
    Debug.WriteLine("The" + image.Name + "is Selected!"); 
    var parent = VisualTreeHelper.GetParent(image) as StackPanel; 
    parent.BorderBrush = new SolidColorBrush(Colors.Red); 
    parent.BorderThickness = new Thickness(5); 
    image.Tapped += Image_Tapped; 
} 

private void Image_Tapped(object sender, TappedRoutedEventArgs e) 
{ 
    var image = sender as Image; 
    //download the image 
}