【问题标题】:get value from data grid onselection从数据网格 onselection 中获取价值
【发布时间】:2013-09-17 05:37:00
【问题描述】:

我是 wpf mvvm 的新手。为了在选择时从数据网格中获取值,我创建了一个对象数据类型的属性。当我单击数据网格行时,我得到一组包含名字、姓氏、城市、州、别针、手机号、邮件 ID、员工 ID 等。我需要从中检索员工 ID 以进行更新。但我不知道如何从对象数据类型中声明的属性中检索这些值。请帮助我....\

这是我的视图模型

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>

【问题讨论】:

    标签: wpf c#-4.0 mvvm binding datagrid


    【解决方案1】:

    老兄,您必须将某种类型的自定义对象(具有这些属性)放入您的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;
    

    【讨论】:

    • 我有另一种方法可以访问 datagrid 的列值。无论如何,谢谢您的帮助...
    猜你喜欢
    • 2016-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-29
    • 1970-01-01
    • 2019-08-16
    • 1970-01-01
    • 2018-10-08
    相关资源
    最近更新 更多