繁体   English   中英

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

[英]How to get the name of the property that is bound to datagrid column in wpf?

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

您可以在selectionChanged上执行此操作,

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

我不确定属性名称的含义- 列标题单元格值

如果您的意思是列标题,则可以这样获得

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

如果您的意思是单元格值,则可以这样获得

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

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

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

<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*/ }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM