簡體   English   中英

如何在Silverlight中綁定到IEnumerable詞典?

[英]How do I bind to a IEnumerable Dictionary in Silverlight?

背景信息:我在WCF服務中具有以下代碼。 GetDataTable基於傳遞了查詢參數的SQL數據庫的調用返回System.Data.DataTable。

public IEnumerable<Dictionary<string, object>> GetData(string *query*) {
    var table = GetDataTable(query);
    var columns = table.Columns.Cast<DataColumn>();
    var dict = table.AsEnumerable()
        .Select(r => columns.Select(c => new {
            Column = c.ColumnName,
            Value = r[c]
        })
        .ToDictionary(i => i.Column, i => i.Value != DBNull.Value ? i.Value : null));
    return dict;
}

我有一個Silverlight應用程序,該程序調用GetData,傳遞一個字符串,並且接收結果。 但是,我在GridView中具有的字段是“比較器”,“計數”,“鍵”和“值”。

Silverlight代碼段

    WCFCLIENT oData = new WCFCLIENT ();
    oData.GetData+= new EventHandler<GetDataCompletedEventArgs>(oData_GetData);
    oData.GetData(*sqlquery*);
  }
}

void oData_GetDataCompleted(object sender, GetDataCompletedEventArgs e) {
  if (e.Error == null) {
    rdpPaging.Source = e.Result;    
    rgvDataResults.ItemsSource = rdpPaging.Source;
}

我的問題有兩個方面

  1. 我用來創建Dictionary的代碼不正確嗎?
  2. 如果代碼正確,如何正確設置DataGrid的數據源,使其顯示SQL調用返回的列和行?

我嘗試綁定到e.Result變量的不同屬性,但結果相似。

您有兩個選擇...

  1. 將字典直接與DataGrid綁定,但不要自動生成列。 通過遍歷總列表的第一項(詞典)中的所有鍵來手動創建列,並使用自定義綁定/轉換器顯示正確的數據。

  2. 我將其與TeleGrid GridView一起使用,但我認為這也適用於普通的Silverlight DataGrid。

    http://blogs.telerik.com/blogs/posts/09-04-23/lightweight-datatable-for-your-silverlight-applications.aspx

您可以在客戶端將列表轉換為數據表,並輕松使用此方法。

[更新]第一個選項的代碼示例

            D_Grid.ItemsSource = Data;        // Data is the collection of dictionary
            foreach (var key in Data[0].Keys)
            {
                    GridViewDataColumn dataCol = null;
                    dataCol = (GridViewDataColumn)D_Grid.Columns[key];
                    if (dataCol == null)
                    {
                        dataCol = new GridViewDataColumn();
                        dataCol.Header = key;
                        dataCol.UniqueName = key;                          
                        dataCol.DataMemberBinding = new Binding()
                        {
                            Converter =new GridConverter(key); // Put your converter that will take the key and return the value from that key.
                        };
                        D_Grid.Columns.Add(dataCol);

                    }
                }

轉換器代碼。 請注意,您需要將密鑰存儲在構造函數中傳遞的轉換器中。

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value is Dictionary<string, object>)
            {
                var input = (Dictionary<string, object>)value;
                if (input.ContainsKey(_key))
                    return input[_key];
            }   

暫無
暫無

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

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