在DataGrid中选择一行

时间:2012-08-15 12:39:52

标签: c# wpf datagrid wpfdatagrid

我定义了一个包含三行的初始表。如果用户选择一行并单击“开始新表”按钮,它将打开一个带有新表的新tabItem。 问题是我不知道如何在DataGrid中选择整行。

C# Code:
//this my initial Table
private ObservableCollection<TableDataRowStringItem> tableobject = new ObservableCollection<TableDataRowStringItem>();
List<TableDataRowStringItem> rowstringList = new List<TableDataRowStringItem>();
TableDataRowStringItem item = new TableDataRowStringItem();
item.RowNumber = 1; item.saveFlag = true; item.ObjectType = "E"; item.Name = "E"; item.PredecessorRowNumber = "0";
rowstringList.Add(item);
item = new TableDataRowStringItem();
item.RowNumber = 2; item.ObjectType = "Function"; item.Name = "Function";    item.PredecessorRowNumber = "1";
rowstringList.Add(item);
item = new TableDataRowStringItem();
item.RowNumber = 3; item.ObjectType = "E"; item.Name = "E"; item.PredecessorRowNumber = "2";
rowstringList.Add(item);
rowstringListEPK = rowstringList;
for (int i = 0; i < rowstringList.Count; i++)
{
    tableobject.Add(rowstringList[i]);
}
DataGrid1.ItemsSource = tableobject;


//Button Code
foreach (TableDataRowStringItem item in rowstringListEPK)
{
    if (item.ObjectType == "Function" **(&& Hier i schould write if row.Isselected)**)
    {
       rowStringItem.Name = item.Name;
       tabControl.Items.Add(tabItem);
       tabItem.Focus();
       tabItem.IsSelected = true;
       tabItem.Header = rowStringItem.Name;
       TableTab.Visibility = Visibility.Visible
    }
    else do nothing
}

//XAML Code
 <DataGrid.RowStyle>
    <Style TargetType="DataGridRow">
        <Style.Triggers>
            <Trigger Property="IsSelected" Value="True">
               <Setter Property="BorderBrush" Value="Blue" />
               <Setter Property="BorderThickness" Value="1" />
               <Setter Property="AllowDrop" Value="True" />
            </Trigger>
        </Style.Triggers>
    </Style>
 </DataGrid.RowStyle>

2 个答案:

答案 0 :(得分:1)

这可能有所帮助:

<DataGrid SelectionMode="Single" SelectionUnit="FullRow" ...

DataGrid dataGrid = new DataGrid();
dataGrid.SelectionUnit = DataGridSelectionUnit.FullRow;
dataGrid.SelectionMode = DataGridSelectionMode.Single;

答案 1 :(得分:0)

你的考试将是:

if (dataGrid1.SelectedItem != null) //test if a row is selected

之后

您可以使用

访问数据行
  dataGrid1.SelectedItem