WPF Получить выбранную строку на сетке данных из шаблона

1

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

Как вы видите, я создал шаблон, содержащий границу для каждой из строк в datagrid. Вопрос в том, как я могу узнать, какую строку в datagrid я нажал. Есть ли способ узнать, нажал ли я первую границу, или вторую, или другие?

Теги:
xaml
wpf
binding
datagrid

1 ответ

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);
}
  • 1
    Большое спасибо. Я был действительно застрял здесь. Ваш первый ответ был вполне достаточно, я тогда использовал row.GetIndex (), и он покрывает его (:
  • 0
    О да. Это бы сработало. Рад помочь..!! :)

Ещё вопросы

Сообщество Overcoder
Наверх
Меню