Hello
I need to set the DataTemplate (TextBox, ComboBox, DateTimePicker, ecc..) in every single cell of a SfDataGrid.
The DataGrid is initialized without columns. Columns are added at runtime programmatically.
The number of columns is unknow in design time.
The data value (and data type) shown in each cell is unknow at design time.
Cells of a single column have different data type.
PropertyRows is a collection of ExpandoObject: ObservableCollection<IDictionary<string, object>> PropertiesRows.
eHeader is a ExpandoObject: IDictionary<string, object> eHeaders
MyLeaf is a class of my project, MyLeaf.Value returns a object
This is my code:
WPF of a user control:
<syncfusion:SfDataGrid Name="grid"
ItemsSource="{Binding PropertiesRows, RelativeSource={RelativeSource AncestorType=UserControl}}"
AllowEditing="True" >
</syncfusion:SfDataGrid>
Code Behind:
private void addHeaders()
{
this.grid.Columns.Clear();
this.grid.Columns.Add(new GridTextColumn() { HeaderText = "Property", MappingName = "Property" });
foreach (var item in eHeaders)
{
var HeaderLeaf = item.Value as MyLeaf;
var headerText = HeaderLeaf.GetLeaf("Value").Value.ToString();
var mappingName = HeaderLeaf.GetLeaf("Value").Value.ToString();
var column = new GridTextColumn() { HeaderText = headerText, MappingName = mappingName };
column.CellTemplateSelector = CellSelector; //CellSelector is Initialized in the class contructor
this.grid.Columns.Add(column);
}
}
CellTemplateSelector : //Used for test some datatype
public class GridCellTemplateSelector : DataTemplateSelector
{
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
if (item != null)
{
var s = ((IDictionary<string, object>)item)["Property"];
switch (s)
{
case "Value":
DataTemplate c = Application.Current.Resources["textBlock"] as DataTemplate;
return c;
case "DisplayValue":
c = Application.Current.Resources["textBlock"] as DataTemplate;
return c;
case "Type":
c = Application.Current.Resources["combobox"] as DataTemplate;
return c;
case "Format":
c = Application.Current.Resources["textBlock"] as DataTemplate;
return c;
case "Visible":
c = Application.Current.Resources["checkbox"] as DataTemplate;
return c;
case "Position":
c = Application.Current.Resources["textBlock"] as DataTemplate;
return c;
}
return null;
}
return null;
}
}
App.xaml:
<Application.Resources>
<DataTemplate x:Key="textBlock">
<TextBlock />
</DataTemplate>
<DataTemplate x:Key="checkbox">
<CheckBox />
</DataTemplate>
<DataTemplate x:Key="combobox">
<ComboBox />
</DataTemplate>
</Application.Resources>
If i don't use the CellSelector, values are shown in the cells as text.
If i use the CellSelector, DateTemplate for each cell is setted correctly but values are not shown.
Thanks in advance
Michele