WPF .Net 4.0 MVVM Binding DataGrid Cells To Array Element object
I am Creating a Timesheet application where there is a list of employees together with a list of Codings to assign time to.
I have Created a DataMatrix And I have Got the grid looking Just fine EXCEPT the data entry of the hours
The grid looks something like
Work Coding | AL | Sick | Job1 | Job2
____________________________________________
Employee1 | | | |
Employee2 | | | |
public class DataMatrix : IEnumerable
{
开发者_C百科 public List<MatrixColumn> Columns { get; set; }
// public List<object[]> Rows { get; set; }
public List<TimesheetDetail[]> Rows { get; set; }
IEnumerator IEnumerable.GetEnumerator()
{
return new GenericEnumerator(Rows.ToArray());
}
}
The datagrid ItemsSource is TimesheetArray.
The Issue I am having is when I enter data for Employee1 Job1 the datagrid looks like
Work Coding | AL | Sick | Job1 | Job2
____________________________________________
Employee1 | 2 | 2 | 2 | 2
Where I Want it looking like
Work Coding | AL | Sick | Job1 | Job2
____________________________________________
Employee1 | | | 2 |
The Data Template looks like
<DataTemplate x:Key="TimesheetEntryDetailCellTemplate"
DataType="{x:Type data:TimesheetDetail}">
<Grid>...
<Label Content="ST" />
<TextBox x:Name="txtStandardTime"
Text="{Binding Path=HoursWorked, ...}"></TextBox>
</Grid>
</DataTemplate>
With debugging I am getting a TimesheetDetail[] object to bind to
I think I need something like
<TextBox Text="{Binding Source = TimesheetDetail[ColumnDisplayIndex].HoursWorked}" />
Does anyone know how I can get the cell template to bind to the element it is hooked to???
Thanks in Advance
One way is to create dynamic binding expression through the code and generating your datagrid columns (AutoGenerateColumns="False" in xaml), apporx. code given below (not compiled):
public void AddColumns(string[] myHeaderList, List<TimesheetDetail[]> myList)
{
for (int i = 0; i < myHeaderList.Length; i++)
{
DataGridTemplateColumn gridCol = new DataGridTemplateColumn();
gridCol.Header = myHeaderList[i];
gridCol.CellTemplate =
(DataTemplate)this.Resources["TimesheetEntryDetailCellTemplate"];
gridCol.Binding = new Binding("[" + i + "].HoursWorked");
_dataGrid.Columns.Add(gridCol);
}
}
List<TimesheetDetail[]> myList=...;
_dataGrid.ItemsSource = myList;
In XAML you need to set AutoGenerateColumns to false:
< DataGrid Name="_dataGrid" AutoGenerateColumns="False" ...>
精彩评论