Question about ViewModel Management (DesignTime Vs Run Time)

前端 未结 3 999
庸人自扰
庸人自扰 2020-12-31 13:42

I have a fairly basic WPF UI whereby user requests cause a new tab to open in my TabControl. The TabControl is bound to an ObservableCollection

相关标签:
3条回答
  • 2020-12-31 14:28

    Yes I think it will interfere with your current setup

    The ViewModelLocator is a static class that returns a dummy object at design time, and a static ViewModel at runtime. This means that

    • The ViewModelLocator, not your ParentViewModel, contains your TabViewModels

    • You cannot have multiple instances of the same Tab (ViewModel) open at once

    • You cannot manage Open/Closed tabs unless you reference the UserControl, which is a violation of the MVVM principle where the ViewModel doesn't know of the View

    • You can't instantiate new copies of the TabViewModel with parameterized constructors. For example, OpenTabs.Add(new CustomerViewModel(CustomerId));

    Perhaps an alternative could be a Converter? One that returns a static object if in design time, or the bound object during runtime? I've never tested such a thing but in theory it should work :)

    0 讨论(0)
  • 2020-12-31 14:31

    The built in MS stuff is not bad, but another more elegant and structurally sound alternative which I am busy incorporating in my project is: http://msdn.microsoft.com/en-us/magazine/dn169081.aspx

    Basically, you use the MVVM Light toolkit with the SimpleIoc container it comes with and end up with the ability to serve up data for the following three scenarios:

    Design time, Run time, and Test time.

    Better still, the whole point of MVVM Light is to have your stuff be directly editable in Blend and there is a whole series of videos and blogs and sample apps describing it all. I wish I had found these earlier in my WPF explorations.

    0 讨论(0)
  • 2020-12-31 14:32

    There is an easier way to do this. Have a DesignTimeUserAdministrationViewModel and populate it with static data in the constructor and refer that in UserControl as:

    <UserControl d:DataContext="{d:DesignInstance designTimeVMs:DesignTimeUserAdministrationViewModel, IsDesignTimeCreatable=True}">
    

    This way you have a design time test data bound to d:DataContext and runtime live data bound to the actual DataContext. More details here.

    0 讨论(0)
提交回复
热议问题