在MouseDown事件Datagrid之前获取行选定

时间:2017-05-24 08:35:26

标签: c# wpf

我在Datagrid中获得了Image-Row的XAML:

<DataGridTemplateColumn  x:Name="imgSettings" Width="*">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <Image x:Name="imgSettings"  Source="img/settings_blue.png" Stretch="None" MouseDown="Row_DoubleClick" />
            <DataTemplate.Triggers>
                <DataTrigger Binding="{Binding IsSelected, 
                  RelativeSource={RelativeSource AncestorType=DataGridRow}}" Value="True">
                    <Setter TargetName="imgSettings" Property="Source" Value="/img/settings_white.png" />
                </DataTrigger>
            </DataTemplate.Triggers>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

我的Double Click行事件是:

private void Row_DoubleClick(object sender, MouseButtonEventArgs e)
{
    Equipment classObj = clientDataGrid.SelectedItem as Equipment;
    string cellValue = classObj.EQNr;

    lblArtikel.Content = "Equipment: " + cellValue ;
    Dispatcher.BeginInvoke((Action)(() => tbControlETK.SelectedIndex = 1));
}

实际上有效,但现在我尝试为此图像按钮获取相同的功能,但是这给了我一个空的异常,因为在选择行之前触发了MouseDown事件...任何解决方案?

我已经想过了图像行的一个函数,我可以在这里得到发送者的行或类似的东西。

1 个答案:

答案 0 :(得分:1)

您可以在可视化树中搜索DataGridRow,如果您找到这样的话,将选择并使用它们。

<Image x:Name="imgSettings"  Source="img/settings_blue.png" Stretch="None" MouseDown="Mouse_Down" />



private void Mouse_Down(object sender, MouseButtonEventArgs e)
        {
            DataGridRow gridRowGettingSelection = null;
            var visParent = VisualTreeHelper.GetParent(sender as FrameworkElement);
            while (gridRowGettingSelection == null && visParent != null)
            {
                gridRowGettingSelection = visParent as DataGridRow;
                visParent = VisualTreeHelper.GetParent(visParent);
            }
            if (gridRowGettingSelection == null) { return; }

            Equipment classObj = gridRowGettingSelection.DataContext as Equipment;
            string cellValue = classObj.EQNr;

            lblArtikel.Content = "Equipment: " + cellValue;
            Dispatcher.BeginInvoke((Action)(() => tbControlETK.SelectedIndex = 1));

        }