2014-05-25 56 views
1

的App.xamlWPF獲取選定行的Datagrid從模板

<Application.Resources> 
    <Style x:Key="datagridRowStyle" TargetType="{x:Type DataGridRow}"> 
     <Setter Property="Height" Value="100"/> 
     <Setter Property="Template"> 
      <Setter.Value> 
       <ControlTemplate TargetType="{x:Type DataGridRow}"> 
        <Border BorderBrush="Black" BorderThickness="1" MouseDown="row_MouseDown" Background="White"> 
        </Border> 
       </ControlTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 
</Application.Resources> 

App.xaml.cs

public partial class App : Application 
    { 
     private void row_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e) 
     { 
      /* I WANT TO KNOW WHICH ROW ON THE DATAGRID I CLICKED */ 
      Navegacao.Switch(new service(/* SO I CAN USE IT HERE */)); 
     } 
    } 

index.xaml

<Border BorderBrush="Black" BorderThickness="1"> 
    <DataGrid Name="datagrid1" Margin="50,50,50,50" ItemsSource="{Binding Path=MyDataBinding}" RowStyle="{StaticResource datagridRowStyle}" HeadersVisibility="None" VerticalScrollBarVisibility="Auto" CanUserAddRows="False"/> 
</Border> 

index.xaml.cs

​​

正如你可以看到我創建了一個包含每一個在數據網格行邊界的模板。 問題是,我怎麼知道我點擊了datagrid上的哪一行。 有沒有辦法知道我點擊了第一個邊框,還是第二個邊框?

回答

0

DataGridRow將是發件人視覺父這將是Border。你可以使用VisualTreeHelper

private void row_MouseDown(object sender, MouseButtonEventArgs e) 
{ 
    DataGridRow row = (DataGridRow)System.Windows.Media.VisualTreeHelper 
            .GetParent((Border)sender); 
} 

在一個側面說明,你可以行駛父可視化樹遞歸地使用這種helper方法。如果對鼠標關閉的行索引感興趣,可以很容易地計算出它。

private void row_MouseDown(object sender, MouseButtonEventArgs e) 
{ 
    DataGridRow row = FindParent<DataGridRow>((Border)sender); 
    DataGrid dataGrid = FindParent<DataGrid>(row); 

    int rowIndex = dataGrid.ItemContainerGenerator.IndexFromContainer(row); 
} 

private T FindParent<T>(DependencyObject child) where T : DependencyObject 
{ 
    var parent = System.Windows.Media.VisualTreeHelper.GetParent(child); 

    if (parent is T || parent == null) 
     return parent as T; 
    else 
     return FindParent<T>(parent); 
} 
+1

非常感謝。我真的被困在這裏。你的第一個答案是足夠的,我然後用row.GetIndex()它覆蓋它(: – jofitesi

+0

哦,是的,它也會有效。很高興幫助.. !! :) –