WPF DataTemplate 和用户控件生命周期
我有一个带有几个选项卡的选项卡控件。当选择一个选项卡时,我将选项卡的内容设置为其相应的视图模型。
我还为所有其他视图模型派生自的基本视图模型定义了一个 DataTemplate:
<DataTemplate DataType="{x:Type vm:BaseViewModel}">
<view:BaseView/>
</DataTemplate>
这样,几乎相同的视图模型将使用相同的基本视图显示。
BaseView 是一个用户控件。在 BaseView 中,我定义了一个 Infragistics XamDataGrid。似乎只为所有视图模型创建了该网格的一个实例,这意味着我可以根据需要多次在选项卡之间切换,但用户控件永远不会从头开始重新创建。
与 DataTemplate 结合使用时,WPF 如何处理用户控件的生命周期?
我试图解决的问题是,在 BaseView 的 xaml 中,我在 XamDataGrid 中定义了一个字段,如下所示:
<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>
IsDirty 列(所有视图模型都有 IsDirty 属性)仅在第一次网格折叠时正确折叠显示。当我单击另一个选项卡时,网格的数据源会更改,网格会创建一个新的 FieldLayout,并且它不会选择 IsDirty 的 Collapsed 设置。结果 IsDirty 列可见。我的想法是,如果我可以强制完全重新创建用户控件,我就可以避免这个问题。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将
DataTemplate
添加到资源并设置x:Shared="false"
Add
DataTemplate
to Resources and setx:Shared="false"