0

I googled for an answer to this for more than two weeks now. This usually means either I am blind or the idea is absurd. Anyways:

In a middle-sized, quite flexible project I'm storing configuration data in a hierarchical structure in the like of this one:

  • Configuration (collection)
    1. Audio (class)
      • BaseDir (struct)
      • PlayMode (enum)
      • Input (class)
      • CalibrateOnConnect (bool)
      • KnownDevices (collection)
        1. ... (class)
          • ...
      • UseDevice (integer)
      • Playlist (collection)
        1. FirstAudio (class)
          • Path (string)
          • Repeat (integer)
      • ...

I already managed to display these in a TreeView in a MVVM pattern. Since I can't exactly tell which options will be added in future, I used a generic approach, creating ViewModels for class, ienumerable, my custom structs and the basic value types (string, bool, enum, ...).

In my XAML these have their corresponding (Hierarchical)DataTemplates, e.g. with a CheckBox for booleans or a textblock for general value types.

Each ViewModel instance has a field to store the data of the underlying Model.

I manage to edit these values in the View and via TwoWay-Binding also in the ViewModel.
But what makes my head hurt is how to update this data in the Model.
Since I create the hierarchical ViewModel structure through reflection, the parents do not have get/set properties corresponding to the field names / indexers / ... of the equivalent configuration class / collection. Though each ViewModel instance knows the field/property name of the parent's model's data structure it was created from and knows its parent ViewModel instance, too (but not its parent Model instance).
Every attempt to solve this problem via Commands or by calling some parent's update function made a knot into my brain.

Isn't there a simple way to achieve this via regular binding techniques?
Would it be better if I created ViewModels for each configuration (sub)class I'm using?
Hint: Each ViewModel instance knows its field / property name in the parent's model's data structure.

4

1 回答 1

1

通读评论,我认为视图模型应该与它试图表示的模型紧密耦合。拥有动态视图模型也很难测试。

但是,如果您真的想尝试解决这个问题,您可以考虑使用DynamicObject,它允许您以完全通用的方式获取/设置实例的属性。使用 DynamicObjects,您将获得在设置或获取属性时调用的钩子,这将使您(例如)能够为给定的动态属性引发 NotifyPropertyChange 事件。

于 2013-07-22T14:54:52.730 回答