Type for ObservableCollection<T> to hold generic interface
Assume the following classes:
public interface ITabViewModel<T> {}
public class FooTabViewModel : ITabViewModel<FooTabViewModel> {}
public class BarTabViewModel : ITabViewModel<BarTabViewModel> {}
public class MainWindowViewModel
{
private readonly ObservableCollection<?> _tabs;
public MainWindowViewModel(
ITabViewModel<FooTabViewModel> fooTabViewModel
ITabViewModel<BarTabViewModel> barTabViewModel)
{
}
public ObservableCollection<?> Tabs
{
get { return _tabs; }
}
}
The MainWindowViewModel holds a list of tabs (e.g. workspaces) that 开发者_StackOverflowwill be bound to a view and displayed with XAML.
The issue I'm having is that I don't know what generic type to give to the ObservableCollection. I could give it a type of object, but I'm not very fond of that idea. I realize I can create IFooTabViewModel and IBarTabViewModel, however it seems to make much more sense creating one generic interface that every TabViewModel can use.
Is there perhaps another design I should be looking at?
There are two questions which you need to address:
- What value do you plan to get out of
ITabViewModel<T>if it doesn't have any members? - How do you plan on using the
Tabsproperty?
My guess is that Tabs exposes a list of view models to the UI so it can create a view-specific representation of a tab for each. In that case, you don't need a common type compile-time because, as the empty ITabViewModel<T> points out, they don't have anything in common besides being included in Tabs.
If that guess is correct, I would say you can eliminate the ITabViewModel<T> type entirely, accept FooTabViewModel and BarTabViewModel directly in the constructor, and make Tabs be of type ObservableCollection<object>.
I am basing these decisions on the fact that you are never using the ITabViewModel<T> type, and are (apparently) looking for some common interface to group a set of otherwise unrelated classes. That can be cleanly represented by using object instead of inventing an abstraction which doesn't abstract anything away.
加载中,请稍侯......
精彩评论