C# WPF可重用的ComboBox填充方法

huangapple go评论75阅读模式
英文:

C# WPF Reuseable combobox populate method

问题

以下是代码的翻译部分:

我有以下代码来使用LookupItem数据服务来填充一个ConboBox 是否有办法通过能够传递模型/类名和用于DisplayMember的'Name'属性来使此代码可重用,即在下面的情况下'GradeName'。

非常感谢。

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();
    }
}
英文:

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&lt;IEnumerable&lt;LookupItem&gt;&gt; GetGradeLookupAsync()
        {
            using (var ctx = _contextCreator())
            {
                return await ctx.Grades.AsNoTracking()
                    .Select(g =&gt;
                    new LookupItem
                    {
                        Id = g.Id,
                        DisplayMember = g.GradeName

                    })
                    .ToListAsync();
            }
        }

答案1

得分: 1

你可以尝试使用通用方法。类似这样的:

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();
    }
}

示例用法:

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

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

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

                });
        .ToListAsync();
    }
}

Sample usage:

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

huangapple
  • 本文由 发表于 2023年6月2日 00:22:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76383912.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定