簡體   English   中英

如何有效地將數組添加為WPF DataGrid行?

[英]How to efficiently add an array as WPF DataGrid row?

我的應用程序接收到一個需要在WPF DataGrid中顯示的16字節數組(實際上是代表字節的字符串數組):每列一個字節,每行16個字節。 我想創建列並將字節數組添加到新行,而不必在每個新記錄中重復執行代碼16次。

我當前的(重復的)方法如下所示:

創建16列:

for (int i = 0; i < 16; i++)
{
    HexadecimalGrid.Columns.Add(new DataGridTextColumn
    {
        Binding = new Binding("b" + i.ToString()),
    });
}

收到的數組:

string[] theData = new string[16] { "1A", "2C", "05", "11", "D2" ... "F9" };

向DataGrid添加新行:

HexadecimalGrid.Items.Add(new {b0 = theData[0], b1 = theData[1] ... b15 = theData[15]});

那么,有沒有更好的方法呢? 而不是輸入bx = theData[x] 16次?

我同意有更好的方法可以做到這一點,但是要回答您的問題:您可以使用LINQ使用聚合來構建ExpandoObject的方法:

var newItem = Enumerable.Range(0, theData.Length)
    .Aggregate<int, ICollection<KeyValuePair<string, object>>, ICollection<KeyValuePair<string, object>>>(
        new ExpandoObject(),
        (collection, index) =>
        {
            collection.Add(new KeyValuePair<string, object>($"b{index}", theData[index]));
            return collection;
        },
        collection => collection);

更新:實際上,如果使用其IDictionary接口,它的可讀性更高:

var newItem = Enumerable.Range(0, theData.Length)
    .Aggregate<int, IDictionary<string, object>, IDictionary<string, object>>(
        new ExpandoObject(),
        (dict, index) =>
        {
            dict.Add($"b{index}", theData[index]);
            return dict;
        },
        dict => dict);

或者,您可以使用循環。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM