How do I select a row in a WPF Grid control?

I'm using a Grid to display data which is not known until run-time. The XAML for my Grid is very simple since I add controls to it programmatically. I need the grid to be flexible.

I would like the user to be able to select(highlight) the entire row in the grid and then be able to click on a button to process the data in that row. How could I do this?

I have not been able to find any information related to my problem. Any ideas would be greatly appreciated.

Here is the XAML:

 <Grid x:Name="lstAssigned" ShowGridLines="True">
        <Grid.ColumnDefinitions>
           <ColumnDefinition Width="auto"></ColumnDefinition>
           <ColumnDefinition Width="auto"></ColumnDefinition>
           <ColumnDefinition Width="auto"></ColumnDefinition>
           <ColumnDefinition Width="auto"></ColumnDefinition>
           <ColumnDefinition Width="auto"></ColumnDefinition>
           <ColumnDefinition Width="auto"></ColumnDefinition>
           <ColumnDefinition Width="auto"></ColumnDefinition>
           <ColumnDefinition Width="auto"></ColumnDefinition>
        </Grid.ColumnDefinitions>
     </Grid>

在这里输入图像描述

Thanks Everyone!

Here are some more details: The data to be displayed will vary. The grid will have 5 columns. Columns 2 and 3 will be combo boxes. The other columns are textBoxes. The user will enter data and save it.

Another time, the data to be displayed could be: combo boxes in columns 2 and 4, and a date in column 5. Since my data source will vary, I was trying to set the control type in each column programmatically.

I initially started with a DataGrid using DataTemplates, but this would define the columns and order. Am I mistaken? I want to define them at run-time.

What would be the best way to handle this? What type of control should I use?

I would apprectiate any kind of adice you can offer.

Thanks in advance.


This sounds like you should use 2 separate DataGrid s for each case. There are ways to alter the columns programatically in runtime, but it's more messy and leads to less maintainability. If I were given this task, I would simply use 2 Different DataGrid s,

one for case #1, where you need

Text      Combo       Combo       Text      Text

and the other for case #2:

Text      Combo       Text        Combo     DateTime

Sounds like a really simple set, where there are no major headaches, then you could just create a proper DataTemplate containing each of this DataGrid s for each type of Model object.


Grid doesn't support selection of rows/columns/cells. It's used to layout controls for display. Use a something else, like a ListView instead.

链接地址: http://www.djcxy.com/p/64730.html

上一篇: 在WPF数据网格行或单元格中选择任意文本并复制它

下一篇: 如何在WPF Grid控件中选择一行?