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

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

C# WPF Reuseable combobox populate method

问题

以下是代码的翻译部分:

  1. 我有以下代码来使用LookupItem数据服务来填充一个ConboBox 是否有办法通过能够传递模型/类名和用于DisplayMember'Name'属性来使此代码可重用,即在下面的情况下'GradeName'
  2. 非常感谢。
  3. public async Task<IEnumerable<LookupItem>> GetGradeLookupAsync()
  4. {
  5. using (var ctx = _contextCreator())
  6. {
  7. return await ctx.Grades.AsNoTracking()
  8. .Select(g =>
  9. new LookupItem
  10. {
  11. Id = g.Id,
  12. DisplayMember = g.GradeName
  13. })
  14. .ToListAsync();
  15. }
  16. }
英文:

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.

  1. public async Task&lt;IEnumerable&lt;LookupItem&gt;&gt; GetGradeLookupAsync()
  2. {
  3. using (var ctx = _contextCreator())
  4. {
  5. return await ctx.Grades.AsNoTracking()
  6. .Select(g =&gt;
  7. new LookupItem
  8. {
  9. Id = g.Id,
  10. DisplayMember = g.GradeName
  11. })
  12. .ToListAsync();
  13. }
  14. }

答案1

得分: 1

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

  1. public async Task<IEnumerable<LookupItem>> GetGradeLookupAsync<T>(
  2. Func<MyContext, IList<T>> dbSet,
  3. Func<T, int> idProperty,
  4. Func<T, string> nameProperty)
  5. {
  6. using (var ctx = _contextCreator())
  7. {
  8. var set = dbSet(ctx);
  9. return set
  10. .Select(g =>
  11. new LookupItem
  12. {
  13. Id = idProperty(g),
  14. DisplayMember = nameProperty(g)
  15. })
  16. .ToListAsync();
  17. }
  18. }

示例用法:

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

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

  1. public async Task&lt;IEnumerable&lt;LookupItem&gt;&gt; GetGradeLookupAsync&lt;T&gt;(
  2. Func&lt;MyContext, IList&lt;T&gt;&gt; dbSet,
  3. Func&lt;T, int&gt; idProperty,
  4. Func&lt;T, string&gt; nameProperty)
  5. {
  6. using (var ctx = _contextCreator())
  7. {
  8. var set = dbSet(ctx);
  9. return set
  10. .Select(g =&gt;
  11. new LookupItem
  12. {
  13. Id = idProperty(g),
  14. DisplayMember = nameProperty(g)
  15. });
  16. .ToListAsync();
  17. }
  18. }

Sample usage:

  1. 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:

确定