Search code examples
c#wpfcombobox

C# WPF Reuseable combobox populate method


I have the following code to populate a ConboBox using a LookupItem data service. Is there any way to make this code reuseable by being able to pass in the Model/Class name and the 'Name' property which is used for the DisplayMember, i.e. in the case below 'GradeName'.

Many Thanks.

public async Task<IEnumerable<LookupItem>> GetGradeLookupAsync()
        {
            using (var ctx = _contextCreator())
            {
                return await ctx.Grades.AsNoTracking()
                    .Select(g =>
                    new LookupItem
                    {
                        Id = g.Id,
                        DisplayMember = g.GradeName

                    })
                    .ToListAsync();
            }
        }

Solution

  • You could try with a generic method. Something like this:

    public async Task<IEnumerable<LookupItem>> GetGradeLookupAsync<T>(
        Func<MyContext, IList<T>> dbSet,
        Func<T, int> idProperty,
        Func<T, string> nameProperty)
    {
        using (var ctx = _contextCreator())
        {
            var set = dbSet(ctx);
            return set
                .Select(g =>
                    new LookupItem
                    {
                        Id = idProperty(g),
                        DisplayMember = nameProperty(g)
    
                    });
            .ToListAsync();
        }
    }
    

    Sample usage:

    await GetGradeLookupAsync(ctx => ctx.Grades, g => g.Id, g => g.GradeName);