【MVVM Dev】PART_Editor的使用

一、前言

      在日常的界面开发中,我们大多使用MVVM模式进行开发。通常情况下,一个PropertyGridControl或者DataGrid的ItemsSource设置好,

然后每一列绑定好某一条ItemsSource中的某一个字段就可以跑起来了。

但是也有另一种情况:

假设一个界面Temp.xaml,它的ViewModel为TempViewModel.cs;

有一个PropertyGridControl的ItemsSource以ObservableCollection<Model>绑定;

PropertyGridControl中的一个PropertyDefinition要重写Template,它所绑定的信息并不只有Model中的某个字段,

还可能包括Model中的若干个字段,甚至TempViewModel中的一些其它信息,这个时候该如何操作?

二、实例

Temp.xaml:

 <services:DockablePane.Resources>
<ResourceDictionary>
<DataTemplate x:Key="EditTemplate">
<special:SpEdit x:Name="PART_Editor"/> //这里是关键!!!!!!!!!!!!!!!
</DataTemplate>
</ResourceDictionary>
</services:DockablePane.Resources> <dxprg:PropertyGridControl
Margin="" VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
SelectedObjects="{Binding Infos}" ShowProperties="WithPropertyDefinitions"
ShowDescriptionIn="ToolTipAndPanel" ShowCategories="True" ExpandCategoriesWhenSelectedObjectChanged="True"
ShowMenuButtonInRows="False" ShowToolPanel="False" ShowSearchBox="False" SortMode="Definitions"> <dxprg:PropertyGridControl.PropertyDefinitions>
<!--通用-->
<dxprg:PropertyDefinition IsReadOnly="True" Path="Code"/>
<dxprg:PropertyDefinition IsReadOnly="True" Path="AProperty"/>
<dxprg:PropertyDefinition Path="BProperty"/>
<dxprg:PropertyDefinition Path="CProperty"/>
<dxprg:PropertyDefinition Path="DProperty"/>
<dxprg:PropertyDefinition Path="EProperty" ContentTemplate="{StaticResource EditTemplate}"/>
</dxprg:PropertyGridControl.PropertyDefinitions>
</dxprg:PropertyGridControl>

在这里,我们重写的DataTemplate中的窗体名称为:PART_Editor

这个名字特别重要,不能改其它的。

这样我们就可以在SpEdit这个窗体中调用TempViewModel的全部信息,因为这个时候TempViewModel已经赋值给了SpEdit的DataContext的某个属性上,

可能的情况是这样的:

SpEdit.xaml.cs:

var source = this.DataContext as RowData;
if (source != null)
_sourceData = (source.Definition.DataContext) as VM;

这样,我们就把Temp.xaml的ViewModel传给了SpEdit的_sourceData。

三、小结

       本文主要描述了如何在重写界面中获取源UI中的ViewModel信息。PART_Editor是一个非常实用的隐藏方法。

上一篇:使用Redis List简单实现抢红包


下一篇:hdu-3449 Consumer---有依赖性质的背包