0
 <Employees>
  <Employee>
    <EmpId>1</EmpId>
    <Name>Sam</Name>
    <Sex>Male</Sex>
  </Employee>
  <Employee>
    <EmpId>2</EmpId>
    <Name>Lucy</Name>
    <Sex>Female</Sex>    
  </Employee>
</Employees>

  <Grid x:Name="LayoutRoot">
    <Grid.RowDefinitions>
        <RowDefinition Height="0.8*"/>
        <RowDefinition Height="0.05*"/>
    </Grid.RowDefinitions>
    <DataGrid x:Name="DgrdEmployeeDetails" Grid.Row="0" FontSize="14.667" FontWeight="Bold" RowHeight="60" ColumnHeaderHeight="60" RowHeaderWidth="40" ColumnWidth="*"/>
    <StackPanel Orientation="Horizontal" Grid.Row="1" HorizontalAlignment="Center">         
        <Button x:Name="BtnGetSelectedRow" Content="GetSelectedRow" Width="120" Height="50" Click="BtnGetSelectedRow_Click" />
    </StackPanel>
</Grid>

private void Window_Loaded(object sender, RoutedEventArgs e)
    {

        XDocument emplyeeDetails = XDocument.Load("Employees.xml");
        var emplyees = from emp in emplyeeDetails.Descendants("Employee").Take(10)
                       orderby emp.Element("EmpId").Value ascending
                       select new
                       {
                           Id = emp.Element("EmpId").Value,
                           Name = emp.Element("Name").Value,
                           Sex = emp.Element("Sex").Value
                       };
        DgrdEmployeeDetails.ItemsSource = emplyees.ToList();
    }
    private void BtnGetSelectedRow_Click(object sender, RoutedEventArgs e)
    {
        DataRowView dr= DgrdEmployeeDetails.SelectedItem as DataRowView;
    }

当我单击 GetSelectedRow按钮时,博士返回

4

2 回答 2

0

Null,因为您不能将动态对象强制转换为 DataRowView。

var dr= DgrdEmployeeDetails.SelectedItem;

博士是一个实例

{
    Id,
    Name,
    Sex
};
于 2013-01-28T09:20:39.863 回答
0
 ObservableCollection<EmpData> _EmpDetail =
    new ObservableCollection<EmpData>();

  public ObservableCollection<EmpData> EmpDetail
    { get { return _EmpDetail; } }            
    public class EmpData
    {
        public int Id{ get; set; }
        public string Sex{ get; set; }
        public int name{ get; set; }                    
    }      

      var emplyees = from emp in emplyeeDetails.Descendants("Employee").Take(10)
                   orderby emp.Element("EmpId").Value ascending
                   select new
                   {
                       Id = emp.Element("EmpId").Value,
                       Name = emp.Element("Name").Value,
                       Sex = emp.Element("Sex").Value
                   };

      foreach (var Emp in emplyees )
        {                             
            _EmpDetail.Add(new EmpData
            {
                Id= Emp.Id,
                Sex= Emp.Sex,
                Name= Emp.Name
            });
        }

   DgrdEmployeeDetails.ItemsSource = _EmpDetail;



 private void BtnGetSelectedRow_Click(object sender, RoutedEventArgs e)
{
    EmpData dr= DgrdEmployeeDetails.SelectedItem as EmpData;
}
于 2013-01-28T09:38:43.933 回答