【发布时间】:2013-01-24 08:50:13
【问题描述】:
我正在尝试将 ViewModel 中集合的结果绑定到组合框。下面是我的代码。任何帮助,将不胜感激。如果您需要查看其他内容或需要更多信息,请告诉我。
XAML:
DataContext="clr-namespace:Alliance.Library.Email.EmailViewModel"
<ComboBox x:Name="cboProviders" ItemsSource="{Binding Source=AddressProviders}" DisplayMemberPath="ProviderName" Grid.Row="0" Grid.Column="1"></ComboBox>
那是我的组合框。我意识到代码是完全错误的,但我是新手,所以我试图通过反复试验来解决它。
代码:
这是在我的 VeiwModel “EmailViewModel.cs”中:
public IEnumerable<IEmailAddressesProvider> AddressProviders { get; set; }
这是我的界面“IEmailAddressesProvider”:
public interface IEmailAddressesProvider
{
string ProviderName { get; }
IEnumerable<EmailAddress> GetEmailUsers();
}
}
包含 GetEmailUsers() 的“EmailAddressProviders.cs”代码:
[Export(typeof(IEmailAddressesProvider))]
public class EmailAddressProvider : IEmailAddressesProvider
{
#region Private Properties
private static readonly IEncryptionService encryptionService = AllianceApp.Container.GetExportedValue<IEncryptionService>();
#endregion
public string ProviderName
{
get { return "Alliance Users"; }
}
public IEnumerable<EmailAddress> GetEmailUsers()
{
IUserRepository userRepo = AllianceApp.Container.GetExportedValue<IUserRepository>();
IEnumerable<User> users = userRepo.GetAllUsers().Where(a => a.IsDeleted == false).OrderBy(a => a.UserID).AsEnumerable();
List<EmailAddress> AddressList = new List<EmailAddress>();
foreach (var user in users)
{
if (user.DisplayName != null && user.EmailAddress != null && user.DisplayName != string.Empty && user.EmailAddress != string.Empty)
AddressList.Add(new EmailAddress() { DisplayName = encryptionService.DecryptString(user.DisplayName), Email = encryptionService.DecryptString(user.EmailAddress) });
}
AddressList.OrderBy(u => u.DisplayName);
return AddressList;
}
}
我使用 MEF 来了解如何设置这些值,我喜欢称之为“魔术”。我没有写这个的电子邮件部分。我只是想照顾组合框中的元素。再次感谢!
【问题讨论】:
-
1.究竟是什么行不通? 2. 发布您用于绑定的 StaticResource 是如何定义的。
-
它只是不包含集合,我还没有定义我的静态资源。就像我说的,我对此很陌生。我发现它不是那么直观。
-
我已经有一段时间没有做 WPF 了,但这不需要是 ObservableCollection,而不是 IEnumerable?
-
@IronMan84 不。observable 的优点很简单,如果 UI 添加/删除/编辑项目,则基础集合也会更改,如果基础集合更新,则 UI 也会更新.如果您使用
IEnumerable,则它是该序列到控件的一次性副本。
标签: c# wpf xaml data-binding collections