0

データの人、場所、量をバインドするデータグリッドがあります。SelectionChanged イベントで、データにアクセスしようとしましたが、タイプが匿名であるとのことでした。

ここに画像の説明を入力

このオブジェクトを変換して値を取得するにはどうすればよいですか?

どんな助けや提案も大歓迎です!!!

4

1 に答える 1

1

Reflection を使用してプロパティ値を取得できます。

private void workgrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    object selectedItem = ((DataGrid)sender).SelectedItem;
    Type type = selectedItem.GetType(); 

    string name = (string)type.GetProperty("PersonName").GetValue(selectedItem, null);
    int amount = (int)type.GetProperty("Amount").GetValue(selectedItem, null);
    string place = (string)type.GetProperty("Place").GetValue(selectedItem, null);
}

ただし、推奨される方法は、DataGrid のバインドに使用するコレクションの独自の型を作成することです。これにより、匿名型に直接バインドすることを回避できます。

public class AccountInfo
{
    public string PersonName { get; set; }
    public int Amount { get; set; }
    public string Place { get; set; }
}
于 2013-03-28T07:14:43.807 に答える