TreeList Data Binding to Interface
Since version 2.27, the TreeList supports binding to a collection of multiple model types that implement the same interface.
Note the usage of OnModelInit
in the example below. The event handler sets the model type to be used for new items in the TreeList. One-type model creation is supported out-of-the-box. If you need to support adding instances of different types:
- Use custom Add buttons in the TreeList Toolbar, one for each model type.
- In each button click handler, define an
InsertedItem
of the correct type in the TreeList State. - Put the TreeList in Insert mode with the SetStateAsync method.
<TelerikTreeList Data="@TreeListData"
IdField="Id"
ParentIdField="ParentId"
EditMode="TreeListEditMode.Inline"
OnUpdate="@UpdateHandler"
OnDelete="@DeleteHandler"
OnCreate="@CreateHandler"
OnModelInit="@(() => new Model1())">
<TreeListToolBarTemplate>
<TreeListCommandButton Command="Add" Icon="@SvgIcon.Plus">Add</TreeListCommandButton>
</TreeListToolBarTemplate>
<TreeListColumns>
<TreeListColumn Field="IntProperty" Expandable="true" />
<TreeListCommandColumn>
<TreeListCommandButton Command="Edit">Edit</TreeListCommandButton>
<TreeListCommandButton Command="Save" ShowInEdit="true">Save</TreeListCommandButton>
<TreeListCommandButton Command="Cancel" ShowInEdit="true">Cancel</TreeListCommandButton>
</TreeListCommandColumn>
</TreeListColumns>
</TelerikTreeList>
@code {
public interface IModel
{
public int? Id { get; set; }
public int? ParentId { get; set; }
public int IntProperty { get; set; }
}
public class Model1 : IModel
{
public int? Id { get; set; }
public int? ParentId { get; set; }
public int IntProperty { get; set; }
}
public class Model2 : IModel
{
public int? Id { get; set; }
public int? ParentId { get; set; }
public int IntProperty { get; set; }
}
List<IModel> TreeListData { get; set; }
protected override void OnInitialized()
{
var data = new List<IModel>();
data.Add(new Model1()
{
Id = 1,
ParentId = null,
IntProperty = 1
});
data.Add(new Model2()
{
Id = 2,
ParentId = 1,
IntProperty = 2
});
TreeListData = data;
}
public void UpdateHandler(TreeListCommandEventArgs args)
{
var model = (IModel)args.Item;
var matchingItem = TreeListData.FirstOrDefault(c => c.Id == model.Id);
if (matchingItem != null)
{
matchingItem.IntProperty = model.IntProperty;
}
}
public void DeleteHandler(TreeListCommandEventArgs args)
{
var model = (IModel)args.Item;
TreeListData.Remove(model);
}
public void CreateHandler(TreeListCommandEventArgs args)
{
var model = (IModel)args.Item;
model.Id = TreeListData.Max(d => d.Id) + 1;
TreeListData.Insert(0, model);
}
}
Up to version 2.26, the
Data
collection of the TreeList must contain instances of only one model type.