2012-08-02 119 views
1

我正在用GridView構建Windows 8 Metro應用程序(C#,XAML),並且我想在用戶點擊的GridViewItem附近顯示一個彈出窗口。我正計劃通過click事件參數獲取GridViewItem UIElement,並使用它的座標來確定放置彈出窗口的位置。Windows 8 Metro:如何獲得點擊GridViewItem?

但是,我還沒有找到一種方法來獲得對被點擊的實際GridViewItem UIElement的引用!我已經試過以下的事件似乎是通過他們的EventArgs僅暴露出的DataContext,而不是實際的UIElement:

object sender // is the GridView 
ItemClickEventArgs.ClickedItem // is the DataContext of the GridViewItem 
ItemClickEventArgs.OriginalSource // is the GridView 
SelectionChangedEventArgs.OriginalSource // is null 
SelectionChangedEventArgs.AddedItems.First() // is the DataContext of the GridViewItem 

如果它的事項,我GridView.ItemSource是CollectionViewSource,其源綁定到一個集合的viewmodels。

是否有可能通過我忽略的某個事件來獲取單擊的GridViewItem?如果不是,我應該考慮以什麼角度解決它?我至少可以通過PointerPressed事件獲取相對於GridView的點擊座標,並查看我能做些什麼來以這種方式定位項目,但真的希望我不必沿着這條路線走。

回答

0

VisualTreeHelper可能會幫助您將其放置到GridView/GridViewItem並找到它的子/父母,即使您想要查找UIElement。要確定在容器內點擊的UIElement應該使用VisualTreeHelper來解決。

更多VisualTreeHelper這裏Visual Tree Helper example

發現,如果你不希望使用VisualTreeHelper,我將創建一個附加屬性,我所有的GridViewItem點擊將通過自己作爲DependencyObject的給GridView的附加屬性(是自定義的,你可以從中獲得更多)。

+0

謝謝,那破解了它。 VisualTreeHelper.FindElementsInHostCoordinates()是要走的路,它返回給定點(來自PointerPressed事件)的UIElements集合,然後可以過濾到GridViewItem。 – user1454265 2012-08-02 19:52:53

6

我也在應用中實現了這種行爲 - 使用Callisto庫中的Flyout彈出窗口與單擊的GridViewItem一起使用。

這是很容易簡單地調用ContainerFromItem來獲得相關GridViewItem控制:

private void itemGridView_ItemClick(object sender, ItemClickEventArgs e) 
{ 
    var clickedItem = itemGridView.ItemContainerGenerator.ContainerFromItem(e.ClickedItem); 

    // Open the flyout now 
    Flyout flyOut = new Flyout(); 
    if (clickedItem is GridViewItem) 
     flyOut.PlacementTarget = clickedItem as UIElement; 
    else 
     flyOut.PlacementTarget = sender as UIElement; 

    flyOut.Placement = PlacementMode.Left; 
    SolidColorBrush br = new SolidColorBrush(Colors.Blue); 
    flyOut.Background = br; 
    TextBlock tb = new TextBlock(); 
    tb.Text = "I'm in your flyout messing with your text"; 

    flyOut.Content = tb; 
    flyOut.IsOpen = true; 
} 

感謝this thread here指着我在正確的方向。