开发者

WPF MVVM Dilemma: ViewModel as Control-derivate with Style or as POCO with UserControl?

I am currently working on a new project of mine that is going to be a data record visualizer (for records in Pascal). It should provide a way to define a given record with data fields and pointer fields and then there will be an example view where you can see the record "in action".

Now the problem I am having is that in this model there are records and components and the relationship between them is that one record has multiple components (data and pointer as mentioned above).

I want to use MVVM for the app but I am now unsure how I should approach this. I modelled the record and components into RecordViewModel and ComponentViewModel (with derivates DataComponentVM, PointerComponentVM).

Now to pro开发者_如何转开发vide a look for these VMs there are 2 options as far as I know:

  • Deriving the ViewModels from Control and providing a ControlTemplate
  • Creating a UserControl using the ViewModel as DataContext

The UserControl approach works fine for the RecordViewModel but when I try to design the way the ComponentViewModels are shown (in a ContentPresenter) this approach fails because I would need to provide a collection of UserControls (instead of DataComponentViewModels) in my RecordViewModel that would make that work (and I am pretty sure that is not a good idea).

The Control approach also has the problem that the ViewModels aren't POCOs anymore which I think has a strange feel to it and is also not considered good practice.

Is there any other way to solve the problem? Do you have any other good advice for me in this regard?

Thanks in advance!

Code:

public class RecordViewModel : BaseViewModel
{
    public RecordViewModel()
    {
        Components = new ObservableCollection<ComponentViewModel>();
    }

    public ObservableCollection<ComponentViewModel> Components { get; set; }
}

public class DataComponentViewModel : ComponentViewModel
{
    public string Type { get; set; }
}

public class PointerComponentViewModel : ComponentViewModel
{
    public object Target { get; set; }
}


Oh god why didn't I think of this before?

I was only thinking about ControlTemplates (therefore needing my ViewModels to derive from Control) when there are also DataTemplates that work exactly like I wanted them to.


I got lost as to why you think you need to provide a collection of user controls, but it sounds like what you really want is for the RecordViewModel to have some variation of:

ObservableCollection<ComponentViewModel> Components

Components is then bound in xaml to the ItemsSource property of some sort of ItemsControl. Whether or not the ComponentViewModel needs it's own UserControl depends on what you are trying to do with it.

If that doesn't start to click for you then you may want to post some code so we can sort it out.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜