从数据网格选择中获取价值

时间:2013-09-17 05:37:01

标签: wpf c#-4.0 mvvm binding datagrid

我是wpf mvvm的新手。为了在选择时从数据网格获取值,我创建了一个对象数据类型的属性。当我点击数据网格行时,我得到一组包含名字,姓氏的值, city,state,pin,mobileno,mail id,employee id etc.i需要从中检索员工id以进行更新。但我不知道如何从object数据类型中声明的属性中检索这些值。请帮助我.... \

这是我的观点模型

public object selectedEmployee;
public object SelectedEmployee
{
    get
    {
        return selectedEmployee;
    }
    set
    {
        selectedEmployee = value;
        OnPropertyChanged("SelectedEmployee");
    }
}

这是我的xaml代码

<DataGrid Grid.Row="2" x:Name="grdEmployee" SelectedItem="{Binding SelectedEmployee, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" ItemsSource="{Binding EmployeeDatatable, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, NotifyOnSourceUpdated=True}" AutoGenerateColumns="False"  IsReadOnly="True"  HorizontalAlignment="Center" Margin="59,0,86,12" Width="492" CanUserAddRows="False"  
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Emp_id}" Header="Employee ID"></DataGridTextColumn>
            <DataGridTextColumn Binding="{Binding FirstName}" Header="FirstName"></DataGridTextColumn>
            <DataGridTextColumn Binding="{Binding LastName}" Header="LastName"></DataGridTextColumn>
            <DataGridTextColumn Binding="{Binding Age}" Header="Age"></DataGridTextColumn>
            <DataGridTextColumn Binding="{Binding ZipCode}" Header="ZipCode"></DataGridTextColumn>
            <DataGridTextColumn Binding="{Binding PhoneNumber}" Header="PhoneNumber"></DataGridTextColumn>
            <DataGridTextColumn Binding="{Binding MobileNumber}" Header="MobileNumber"></DataGridTextColumn>
            <DataGridTemplateColumn>
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Button Name="btnEdit" Content="Edit"></Button>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

        </DataGrid.Columns>

    </DataGrid>

1 个答案:

答案 0 :(得分:0)

老兄,你必须将某种类型的自定义对象(具有这些属性)放入object变量中。您所要做的就是将object转换回原始类型,然后您就可以再次访问这些属性。因为我不知道它是什么类型,对于这个例子,我想象你有一个名为Employee的类具有这些属性。这是你投射物体的方式:

Employee employee = (Employee)yourRowObject;
// Now you can access the properties. For example...
string fullName = string.Concat(employee.Firstname, " ", employee.LastName);
int employeeId = employee.Id;