Switching data patterns at run time - update issue

I am using MVVM architecture to separate my application. That is, you often see something like

var u = new UserControl(); u.Content = new MyCustomType(); // MyCustomType is not a control 

The user interface is defined using data templates found in resource dictionaries in their own XAML files.

 <ResourceDictionary ...> <DataTemplate DataType="{x:Type local:MyCustomType}"> ... 

I load resources when the application starts, and the application happily displays my user interface. But if I delete the data template and add a new one (same key, same data type), the user interface still uses the old data template. Of course, I can reinstall the contents of my container for a forced update, but that seems silly because I have to notify each control about the change, like this

 var tmp = control.Content; control.Content = null; control.Content = tmp; // New data template will be used 

Any other approaches?

+4
source share
1 answer

This is because the resources in your dictionary are static. Once they are used, they will not be updated. You can try reloading the dictionaries, but this will only update the new controls, not the old ones.

If you want to support multiple DataTemplates, you can consider the DataTemplateSelector class, which will select the template according to your conditions: http://msdn.microsoft.com/en-us/library/system.windows.controls.datatemplateselector.aspx

If you need to switch templates on the fly, you can always use the ControlTemplates and the Binding for Template property of your control ...

 {Binding Converter={StaticResource YourAwesomeTemplateSwitcherConverter}} 

NTN

+4
source

All Articles