Silverlight DataGrid自適應數據
silverlight的DataGrid如果改成fill模式 那么當數據超長也不會出現橫向滾動條 如果改成按單元格模式 如果數據較短又會出現空白的地方
所以我自己寫了個算法 目前實現了以list為數據源的形式 根據數據長短 標題長短 當前實際寬度進行了算法運算 并進行了調整 不多說直接上代碼
public static class DataGridHelper { private static double withunit = 7.2;//單個英文所占像素大小 private static int hzwithunit = 3;//漢字與應為對比值(1個漢字相當與多少個英文) public static void initGrid<T>(List<T> lml,DataGrid DataGrid) { Dictionary<int, int> dic = new Dictionary<int, int>(); Dictionary<int, int> dic2 = new Dictionary<int, int>(); for (int j = 0; j < lml.Count; j++) { DataGrid.SelectedIndex = j; DataGrid.UpdateLayout(); DataGrid.ScrollIntoView(lml[j], DataGrid.Columns[0]); for (int i = 0; i < DataGrid.Columns.Count; i++) { T mi = lml[j]; string s1 = ((TextBlock)DataGrid.Columns[i].GetCellContent(mi)).Text.ToString(); string s2 = DataGrid.Columns[i].Header.ToString(); int n1 = 0; int n2 = 0; for (int mm = 0; mm < s1.Length; mm++) { if (((int)s1[mm]) > 127) { n1 = n1 + hzwithunit; } else { n1 = n1 + 1; } } for (int mm = 0; mm < s2.Length; mm++) { if (((int)s2[mm]) > 127) { n2 = n2 + hzwithunit; } else { n2 = n2 + 1; } } if (!dic.Keys.Contains(i)) { if (n1 > n2) { dic.Add(i, n1); } else { dic.Add(i, n2); } } else { int s = 0; if (n1 > n2) { s = n1; } else { s = n2; } if (dic[i] < s) { dic[i] = s; } } } } DataGrid.SelectedIndex = 0; DataGrid.UpdateLayout(); DataGrid.ScrollIntoView(lml.First(), DataGrid.Columns[0]); setColumnsWith(dic,dic2,DataGrid); } private static void setColumnsWith(Dictionary<int, int> dic, Dictionary<int, int> dic2, DataGrid DataGrid) { int n = 1; foreach (int i in dic.Values) { if (n > i) { n = i; } } foreach (int k in dic.Keys) { if (dic[k] % n == 0) { if (!dic2.Keys.Contains(k)) { dic2.Add(k, dic[k] / n); } } else { if (!dic2.Keys.Contains(k)) { dic2.Add(k, (dic[k] / n) + 1); } } } int n1 = 0; foreach (int v in dic2.Values) { n1 = n1 + v; } if (n1 * withunit < DataGrid.ActualWidth) { for (int i = 0; i < DataGrid.Columns.Count; i++) { DataGrid.Columns[i].Width = new DataGridLength(dic2[i], DataGridLengthUnitType.Star); } } else { for (int i = 0; i < DataGrid.Columns.Count; i++) { DataGrid.Columns[i].Width = new DataGridLength(dic2[i] * withunit); } } } }
這里面當數據最大長度比列標題長度短的時候就會采用列寬 當整體寬度小于DataGrid寬度的時候就會按照權重進行分配。調用的時候直接將數據源和DataGrid對象傳進去就行了。另外如果是其他類型數據源 各位也可以根據實際需求改一下 很簡單的。

浙公網安備 33010602011771號