WPF DataGrid TargetType =“DataGridRow”不适用于Event =“MouseDoubleClick”

时间:2017-11-11 00:19:03

标签: c# wpf datagrid

我正在尝试在DataGrid行上添加onclick事件,但它不能用于我的代码。它仅在TargetType="DataGridCell"时有效。这是我的DataGrid;

<DataGrid Name="CourtCasesGrid" Grid.Column="0" BeginningEdit="dataGrid_BeginningEdit" Grid.Row="0" SelectedItem="{Binding SelectedCourtCase}" CanUserReorderColumns="True" CanUserResizeColumns="True" CanUserResizeRows="False" CanUserSortColumns="True">
    <DataGrid.Resources>
        <Style TargetType="DataGridRow">
            <EventSetter Event="MouseDoubleClick" Handler="CourtCasesGridRowDoubleClick"/>
        </Style>
    </DataGrid.Resources>
</DataGrid>

1 个答案:

答案 0 :(得分:0)

我已经完成了这项工作,并且成功地完成了 - 双击所选择的行刺激事件,同样允许收集行的值。我使用Code-Behind完成了这项工作,但如果对您有用,也可以协助使用MVVM方法。

这是&#39; MainWindow.xaml&#39;代码隐藏:

using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

/// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public DataGridRow SelectedRow { get; set; }
        public ObservableCollection<CourtCase> CourtCases { get; set; }
        public MainWindow()
        {
            InitializeComponent();

            CourtCases = new ObservableCollection<CourtCase>();
            CourtCases.Add(new CourtCase("1"));
            CourtCases.Add(new CourtCase("2"));
            CourtCases.Add(new CourtCase("3"));
            CourtCases.Add(new CourtCase("4"));

            SelectedRow = new DataGridRow();

            CourtCasesGrid.DataContext = CourtCases;
        }

        private void CourtCasesGridRowDoubleClick(object sender, MouseButtonEventArgs e)
        {
            DataGridRow row = sender as DataGridRow;
        }
    }

这是&#39; MainWindow.xaml&#39;视图:

<Grid>
        <DataGrid ItemsSource="{Binding CourtCases,RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}"  Name="CourtCasesGrid" ColumnWidth="*"
                  SelectionUnit="FullRow">
            <DataGrid.Resources>
                <Style TargetType="DataGridRow">
                    <EventSetter Event="MouseDoubleClick" Handler="CourtCasesGridRowDoubleClick"/>
                </Style>
            </DataGrid.Resources>
        </DataGrid>
    </Grid>

即便是我用来举行法庭数据的简单课程,供你参考:

 public class CourtCase
{
    public string Name { get; set; }
    public CourtCase()
    {
        Name = "";
    }
    public CourtCase(string n)
    {
        Name = n;
    }
}

希望这有帮助!