2016-02-15 5 views
0

Я создаю POS-систему Retail Clothing и хочу отображать элементы, связанные со стилем в специально отформатированном DataGrid.Связывание строк с DataGrid с динамическими столбцами

Такие, как:

Color_S_M_L_X_2_
| Красный | 2 | 2 | 2 | 0 | 1 |
| Синий | 0 | 1 | 2 | 0 | 0 |
| Розовый | 0 | 2 | 1 | 1 | 1 |

У меня есть столбцы на сетке, добавленные во время выполнения, в зависимости от размеров в стиле. Единственная проблема, с которой я сталкиваюсь, - это когда я пытаюсь привязать свойство Senses к столбцу.

private void SetColumns() 
{ 

    ObservableCollection<DataGridColumn> columns = new ObservableCollection<DataGridColumn>(); 

    var color_col = new DataGridTextColumn() 
    { 
     Header = "Color", 
     Binding = new Binding("Color") 
    }; 

    columns.Add(color_col); 
    if (AttributeVisible == Visibility.Visible) 
    { 
     columns.Add(new DataGridTextColumn() 
     { 
      Header = AttributeType, 
      Binding = new Binding("Attribute") 
     }); 
    } 
    foreach (string s in Items.Select(i => i.Size).Distinct()) 
    { 
     columns.Add(new DataGridTextColumn() 
     { 
      Header = s, 
      Binding = new Binding("Sizes[0].Item2") 
      //This works, for binding one Size's Quantity to all of the Columns 
      //But I need something that does it for each column like a Hashmap 
      //`Sizes[s].Item2`, or a list `Sizes.Where(i => i.Item1 == s).Select(i => i.Item2)` 
     }); 
    } 
    ColumnCollection = new ObservableCollection<DataGridColumn>(columns); 
} 

Модель для строки является:

class StyleGridRow 
{ 
    public string Color 
    { 
     get; 
     set; 
    } 
    public string Attribute 
    { 
     get; 
     set; 
    } 

    //The Sizes Property also contains the quantity for the size. 
    /*public Hashtable Sizes 
    { 
     get; 
     set; 
    }*/ 

    public List<Tuple<string, int>> Sizes 
    { 
     get; 
     set; 
    } 


    public StyleGridRow() 
    { 
     this.Color = ""; 
     this.Attribute = ""; 
     this.Sizes = new Hashtable(); 
    } 
    public StyleGridRow(ref string Color, ref string Attribute, ref Hashtable Sizes) 
    { 
     this.Color = Color; 
     this.Attribute = Attribute; 
     this.Sizes = Sizes; 
    }   
} 

Я еще не придумал, как, чтобы позволить PropertyPath брошюрования сотрудничать.

Есть ли какой-либо тип данных, который будет работать для этой цели, или мне нужно изменить свой стиль StyleGridRow, чтобы лучше подойти к дизайну?

ответ

0

Вы пробовали изменения индекса массива вручную:

// Add an index to specify the array offset 
int index = 0; 
// The Distinct() will cause issues finding the correct array offset. 
// You may need to use GroupBy() or another mechanism to group the 
// column with the size. 
foreach (string s in Items.Select(i => i.Size).Distinct()) 
{ 
    columns.Add(new DataGridTextColumn() 
    { 
     Header = s, 
     // The array index must exist already. You can put a check for it above if needed. 
     Binding = new Binding(string.Format("Sizes[{0}].Item2", index)), 
    }); 
    index++; 
} 

EDIT: Это может быть лучше использовать ObservableCollection для размеров. Вы можете использовать два массива или создать другой класс. В идеале, вы должны использовать другой класс и реорганизовать отчетливый() на более высокий уровень, так все StyleGridRow элементов имеют одинаковый порядок и длину:

// implement INPC for notifications, but I won't show it for brevity 
public class SizeColumn : INotifyPropertyChanged 
{ 
    public string Header { get; set; } 
    public int Count { get; set; } 
    public int Index { get; set; } 
} 

class StyleGridRow 
{ 
    // ... 
    public ObservableCollection<SizeColumn> SizeColumns { get; set; } 
    // ... 
} 

// ... 
int index = 0; 
var sizeColumns = new List<SizeColumn>(); 
// TODO: Refactor `Select().Distinct()` this so all rows will have same order and length 
var sizes = Items.Select(i => i.Size).Distinct().ToList(); 
foreach (string s in sizeColumns) 
{ 
    // Assuming you are summing the values, and the property name is `Value` 
    var count = Items.Where(x => x.Size == s).Sum(i => i.Value); 
    sizeColumns.Add(new SizeColumn() 
    { 
     Header = s, 
     Count = count, 
     Index = index, 
    }); 
    columns.Add(new DataGridTextColumn() 
    { 
     Header = s, 
     Binding = new Binding(string.Format("SizeColumns[{0}].Count", index)), 
    }); 
    ++index; 
} 
SizeColumns = new ObservableCollection<SizeColumn>(sizeColumns); 
ColumnCollection = new ObservableCollection<DataGridColumn>(columns); 
+0

Индексация подход работает для моих потребностей! Я не могу поверить, что это проскользнуло мимо меня. Спасибо!! –

Смежные вопросы