2017-02-20 34 views
0

我有一個DataGrid列在XAML看起來像這樣:如何獲取該行已點擊,而不是行中的WPF數據中選擇網格

<DataGridTemplateColumn Header="" Width="35" IsReadOnly="True"> 
    <DataGridTemplateColumn.CellTemplate> 
     <DataTemplate> 
      <Image Source="{Binding PostIcon}" Stretch="None" MouseDown="Post_MouseDown" /> 
     </DataTemplate> 
    </DataGridTemplateColumn.CellTemplate> 
</DataGridTemplateColumn> 

一個觸發應該搶事件datagrid行中的另一條數據:在這種情況下,是一個URL代碼。然後運行這個當事件被觸發:

private void Post_MouseDown(object sender, MouseButtonEventArgs e) 
    { 
     int index = ThreadList.SelectedIndex; 
     DataRowView row = (DataRowView)ThreadList.SelectedItems[0]; 

     string topicID = Convert.ToString(row["URL"]); 
     string thisURL = "http://www.myforums.com/perm/topic/" + topicID; 

     System.Diagnostics.Process.Start(thisURL); 
    } 

這裏的想法是,當你點擊在數據表中的圖像圖標,它吸引你點擊該行的索引,找到相關的線程ID並構建出網址,然後將您帶到那裏。

這一切都有效,但DataGrid.SelectedItems實際上並不捕獲點擊的內容。它捕捉點擊時選擇的內容。

這意味着如果你點擊一行,它總是選擇你以前點擊過的內容,而不是你剛纔點擊的內容。我如何製作它以便選擇我剛剛點擊的內容?似乎沒有成爲一個「ClickedItem」相當於明顯「SelectedItems」

--SOLUTION--

完整解決方案,我結束了使用,這要歸功於AnjumSKhan,看起來像這樣(移動特色變量 'DC',以明確的DataRowView的變量):

private void Post_MouseDown(object sender, MouseButtonEventArgs e) 
    { 
     int index = ThreadList.SelectedIndex; 

     var dc = (sender as Image).DataContext; 

     DataRowView row = (DataRowView)dc; 

     string topicID = Convert.ToString(row["URL"]); 
     string thisURL = "http://www.myforums.com/perm/topic/" + topicID; 
     System.Diagnostics.Process.Start(thisURL); 
    } 
+0

「它總是選擇你以前點擊過的東西,而不是你剛纔點擊的東西。 「,這是什麼意思? – AnjumSKhan

+0

在WPF DataGrid中,'selected'和'clicked'是兩件不同的事情,行爲最終可以通過左鍵點擊'選擇'Row 3,然後單擊第1行中的元素。結果將是,當您單擊第1行元素時,任何類似onclick的事件都會觸發,但當代碼查看實際選定的內容時,它將返回Row 3。 – mkautzm

回答

1

你有沒有嘗試過這樣的:

private void Post_MouseDown(object sender, MouseButtonEventArgs e) 
    { 
     var dc = (sender as Image).DataContext; 
     ... 
    } 
1

漢dle MouseLeftButtonUp event and try this:

private void DataGrid_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) 
    { 
     DependencyObject dep = (DependencyObject)e.OriginalSource; 
     while ((dep != null) && !(dep is DataGridRow)) 
     { 
      dep = VisualTreeHelper.GetParent(dep); 
     } 

     if (dep is DataGridRow) 
     { 
      DataGridRow row = dep as DataGridRow; 
      // do something 
     } 
    }