[英]How to convert DbSet to ObservableCollection
I want to create a value converter which will convert DbSet<MyEntity>
to ObservableCollection<MyEntity>
so that I can bind it easily to a combobox in WPF XAML.我想创建一个值转换器,它将DbSet<MyEntity>
转换为ObservableCollection<MyEntity>
以便我可以轻松地将它绑定到 WPF XAML 中的组合框。 I want it to work across all types.我希望它适用于所有类型。
I have tried this so far.到目前为止,我已经尝试过这个。
class DbSetToObservableCollectionConverter:IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
try
{
DbSet<T> d = (DbSet<T>)value; //How do I know what to put in place of T
return new ObservableCollection<T>(d);
}
catch(Exception ex)
{
return value;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
This does not work as T is not really a type.这不起作用,因为 T 不是真正的类型。 Can somebody help me what to do?有人可以帮我做什么吗?
Don't do this in a converter.不要在转换器中执行此操作。 Do it in the ViewModel.在 ViewModel 中执行此操作。 That way, your ViewModel will have a strongly typed reference to the DbSet<T>
(not just an object
) and will know what type T
is.这样,您的 ViewModel 将具有对DbSet<T>
(不仅仅是object
)的强类型引用,并且将知道T
是什么类型。
Having:拥有:
DbSet<Thread> Threads;
Use:采用:
ObservableCollection<Thread> Threads;
using (var db = new MyContext())
{
Threads =new ObservableCollection<Thread>(db.Threads);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.