Combox SelectedItem does not apply when restoring from serialized ViewModel

后端 未结 1 1879
轻奢々
轻奢々 2021-01-28 16:26

I\'m facing a strange problem when using C# WPF and MVVM Pattern while restoring a ViewModel (serialized using Json.Net).

The idea of the software is - when closing the

相关标签:
1条回答
  • 2021-01-28 16:48

    If you have an ItemsSource and a SelectedItem, the instance in SelectedItem MUST BE in the collection bound to ItemsSource. If it is not, then your bindings will not work as expected.

    The control uses reference equality to determine which item in ItemsSource is the one in SelectedItem and update the UI. This normally isn't a problem as the control populates SelectedItem for you, but if you are updating from the ViewModel side, you have to make sure your references are managed correctly.

    This can be an issue when serializing/deserializing your view model. Most common serializers don't track references, and so cannot restore these on deserialization. The same object may be referenced multiple places in the original object graph, but after deserialization you now have multiple instances of the original spread throughout the rehydrated graph. This won't work with your requirements.

    What you have to do is, after deserializing, find the matching instance in your collection and substitute it for the instance in SelectedItem. Or, use a serializer that tracks instances.. The XAML serializer already does this, and is a surprisingly good xml serializer for .net object graphs.

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