【问题标题】:How does one get row data from a Silverlight DataGrid?如何从 Silverlight DataGrid 中获取行数据?
【发布时间】:2011-05-27 14:40:46
【问题描述】:

在 Silverlight 中,如何从充满数据的 DataGrid 中获取行数据?

我已经走到了这一步(在一个接收按钮点击一行的方法中(:

DataGridRow item = (DataGridRow)dg.SelectedItem;

现在,我如何获取我猜是选定行的项目的各个组件?

在这里帮帮我。如何将 observablecollection 绑定到网格?

在投射到对象时如何使用投射系统?

当我将数据读入网格时,我使用了这个类:

public class Data
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public bool Available { get; set; }
    public int index_1 { get; set; }
    public int index_2 { get; set; }
    public int index_3 { get; set; }
    public int index_4 { get; set; }
    public int index_5 { get; set; }
    public int index_6 { get; set; }
    public int index_7 { get; set; }
    public int index_8 { get; set; }
    public int index_9 { get; set; }
    public int index_10 { get; set; }
    public int index_11 { get; set; }
    public int index_12 { get; set; }
    public int index_13 { get; set; }
    public int index_14 { get; set; }
    public int index_15 { get; set; }
}

所以当我读回时我是如何投射的

这不起作用:

Data _mydata = new Data();  
YValue = (_mydata.index_1)dg.SelectedItem;

这不起作用:

YValue = (index_1)dg.SelectedItem;

这不起作用:

YValue = (Data().index_1)dg.SelectedItem;

【问题讨论】:

    标签: silverlight-4.0 datagrid


    【解决方案1】:
    DataGridRow item = (DataGridRow)dg.SelectedItem;
    int index1 = ((Data)item).index_1;
    

    这将为您提供第一个索引的值。

    【讨论】:

    • 它给了我一个例外。但是当我投射到我的自定义对象时,它可以工作。无论如何,我想获得 DataGridRow。
    【解决方案2】:

    如果您已将 ObservableCollection<Foo> 绑定到您的网格,则您选择的项目可以直接投射到您的对象中 - (Foo)dg.SelectedItem

    编辑——更新以回答更新后的问题

    简单的答案是,如果您不使用 MVVM(我在您的帖子中假设您不是),请在后面的代码中创建一个数据集合(最好是 ObservableCollection)并将网格 itemsource 属性设置为您的集合

    public ObservableCollection<Data> MyCollection{get;set;}
    
    void SetGridItemsSource()
    {
    // populate your collection here, then use the below line to associate it with your
    // grids itemssource      
    MyGrid.ItemsSource = MyCollection;
    
    }
    
    public void GetSelectedItem()
    {
       //Simply cast the selected item to your type
       Data selectedItem = (Data)MyGrid.SelectedItem;
    }
    

    【讨论】:

    • 在这里帮帮我。如何将 observablecollection 绑定到网格?投射到对象时如何使用 (Foo) ?当我将数据读入网格时,我使用了这个类: public class Data { public string FirstName { get;放; } 公共字符串姓氏 { 获取;放; } 公共 int 年龄 { 得到;放; } 公共布尔可用 { 获取;放; } 公共 int index_1 { 获取;放; } 公共 int index_2 { 获取;放; } }
    • @xarzu,希望我更新的答案有帮助
    猜你喜欢
    • 2010-11-25
    • 2011-04-28
    • 2011-11-17
    • 1970-01-01
    • 2017-11-22
    • 1970-01-01
    • 1970-01-01
    • 2010-09-11
    • 2011-04-14
    相关资源
    最近更新 更多