如何获取绑定到wpf中的datagrid列的属性的名称?

时间:2014-10-09 17:08:12

标签: c# wpf

我有一个包含近30列的数据网格,我需要获取绑定到列的属性的名称。我正在使用datagrid的datagrid_selectedcellschanged(sender,selectedeventargs)事件。

3 个答案:

答案 0 :(得分:0)

您可以在selectionChanged,

上执行此操作
 private void peopleGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
  {
         var selectedObj= peopleGrid.SelectedItem as YourObject;
         if(selectedObj != null)
         {
         int PersonID   = selectedObj.PersonID;
         }
  }

答案 1 :(得分:0)

我不确定您的意思属性名称 - 列标题单元格值

如果你的意思是列标题,你可以像这样得到它

string selectedColumnHeader = (string)myGrid.SelectedCells[0].Column.Header;

如果你的意思是Cell Value,你可以像这样得到它

DataRowView dataRow = (DataRowView)dataGrid1.SelectedItem;
int index = datagrid1.CurrentCell.Column.DisplayIndex;
string cellValue= dataRow.Row.ItemArray[index].ToString();

答案 2 :(得分:0)

这是我根据数据网格模板列和使用可编辑列设法解决相同问题的方法。

首先是转换要编辑元素的绑定表达式。接下来,检索在单元格中显示的关联属性名称。

<DataGrid Name="dgMaterialSorter" AutoGenerateColumns="False" Grid.Column="1" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" 
          PreparingCellForEdit="dgMaterialSorter_PreparingCellForEdit" 
          CellEditEnding="dgMaterialSorter_CellEditEnding">
    <DataGrid.Columns>
        <DataGridTextColumn Header="" Binding="{Binding MaterialName}"  IsReadOnly="true" Width="Auto" HeaderStyle="{StaticResource GridHdr_Right}" CellStyle="{StaticResource GridCol_Right}"/>
        <DataGridTextColumn Header="Code" Binding="{Binding MaterialCode}"  IsReadOnly="true" Width="Auto" HeaderStyle="{StaticResource GridHdr_Center}" CellStyle="{StaticResource GridCol_Center}" />
        <DataGridTemplateColumn Header="Qty"  HeaderStyle="{StaticResource GridHdr_Center}" CellStyle="{StaticResource GridCol_Center}"  >
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Quantity}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
            <DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <TextBox x:Name="EditTextbox" Text="{Binding Quantity, Mode=TwoWay, UpdateSourceTrigger=LostFocus, ValidatesOnDataErrors=True}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellEditingTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>

private void dgMaterialSorter_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
    if (e.EditAction == DataGridEditAction.Commit)
    {

        BindingExpression binding = (BindingExpression)e.EditingElement.BindingGroup.BindingExpressions[0];
        string bindingField = binding.ResolvedSourcePropertyName;
        if (bindingField.Equals(nameof(MaterialSorter.Quantity))) { /*DO SOMETHING*/ }
    }
}