WPF DataTemplate and usercontrol lifetime
I have a tab control with a few tabs. When a tab is selected, I set the content of the tab to its corresponding view model.
I also have a DataTemplate defined for the base view model that all of the other view models derive from:
<DataTemplate DataType="{x:Type vm:BaseViewModel}">
<view:BaseView/>
</DataTemplate>
This way, my view models, which are nearly identical, will be displayed using the same base view.
BaseView is a user control. In BaseView I have an Infragistics XamDataGrid defined. It seems that only one instance of this grid is开发者_如何学运维 created for all of the view models, meaning I can switch between tabs as many times as I want but the user control is never recreated from scratch.
How does WPF handle the lifetime of user controls when combined with DataTemplates?
The problem I am trying to solve is that in the xaml of BaseView, I have defined a Field in the XamDataGrid like so:
<igDP:XamDataGrid.FieldLayouts>
<igDP:FieldLayout>
<igDP:FieldLayout.FieldSettings>
<igDP:FieldSettings DataValueChangedNotificationsActive="true"
AllowCellVirtualization="False"
AllowResize="True"
AllowRecordFiltering="True"/>
</igDP:FieldLayout.FieldSettings>
<igDP:Field Name="IsDirty" Visibility="Collapsed"/>
</igDP:FieldLayout>
</igDP:XamDataGrid.FieldLayouts>
The IsDirty column (all of the view models have an IsDirty property) is only correctly collapsed the first time the grid is displayed. When I click another tab, the grid's data source changes, a new FieldLayout is created by the grid, and it doesn't pick up the Collapsed setting for IsDirty. As a result the IsDirty column is visible. My thinking was if I can force the user control to be totally recreated, I could avoid this issue.
Add DataTemplate
to Resources and set x:Shared="false"
精彩评论