WPF从模板获取Datagrid上的选定行

时间:2014-05-25 18:52:02

标签: c# wpf xaml binding datagrid

的App.xaml

<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

public partial class index : Page
{
    public index()
    {
        InitializeComponent();
        BindGrid();
    }

    private void BindGrid()
    {
        DataSet bind = database.BindGrid("SELECT * FROM (projecto.encomenda INNER JOIN projecto.encom_contem ON id_enc = encom_id) INNER JOIN (SELECT codigo, tipo, descricao FROM Projecto.Produto INNER JOIN Projecto.Servico ON codigo = produto_codigo) AS T1 ON produto_codigo = codigo WHERE estado <> 'Pronto'");
        datagrid1.DataContext = bind;
    }
}

如您所见,我创建了一个模板,其中包含数据网格中每个行的边框。 问题是,我怎么知道我点击的数据网格上的哪一行。 有没有办法知道我是否点击了第一个边框,第二个边框或其他边框?

1 个答案:

答案 0 :(得分:0)

DataGridRow 将是 Border 的发件人的可视父级。您可以使用 VisualTreeHelper

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

在旁注中,您可以使用此辅助方法递归地向上移动父视觉树。如果对鼠标关闭的行索引感兴趣,也可以轻松计算。

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);
}