Silverlight 4已经出局了,似乎我们再次错过了这个版本中的DataTemplate DataType功能,这对于MVVM支持IMHO来说是非常关键的.对于我的
WPF应用程序,此时,我已经非常习惯将我的Views的DataTemplates全局添加到我的Application.Resources,其中DataTypes用于我的相应ViewModel:
即.
<DataTemplate DataType="{x:Type viewModels:myViewModel}"> <views:myView/> </DataTemplate>
我喜欢这种方法,因为我所有绑定的ViewModel都会自动显示正确的内容…当我在视图中将某些ItemSource绑定到ViewModels集合时尤其有用…例如,这将自动确保每个选项卡中的每个选项卡TabControl绑定到Collection< SomeViewModel>显示与SomeViewModel关联的视图.
我为SL 3尝试过的一些事情包括:
>创建“DataTemplatePresenterContentControl”,在控件加载时自动为内容应用DataTemplate
>使用TypeConverter,动态应用于控制负载,沿着可视树向下查找数据绑定对象
>使用在控制负载上动态应用的样式,沿着可视树向下查找数据绑定对象
但是,这些方法都没有真正以可接受的方式解决我上面提到的情况,这非常关键.
因此,由于Silverlight 4中仍然无法开箱即用,我很高兴知道是否有人提出了一些合理的替代方案.
谢谢.
解决方法
我在几个商业项目中的方式如下:
我有一个标准的IValueConverter
public class ViewTemplateChooser : IValueConverter { /// <summary> /// Modifies the source data before passing it to the target for display in the UI. /// </summary> /// <returns> /// The value to be passed to the target dependency property. /// </returns> /// <param name="value">The source data being passed to the target.</param><param name="targetType">The <see cref="T:System.Type"/> of data expected by the target dependency property.</param><param name="parameter">An optional parameter to be used in the converter logic.</param><param name="culture">The culture of the conversion.</param> public object Convert(object value,Type targetType,object parameter,CultureInfo culture) { if (value is MyViewModel) { return new MyView { DataContext = value }; } return value; } /// <summary> /// Modifies the target data before passing it to the source object. This method is called only in <see cref="F:System.Windows.Data.BindingMode.TwoWay"/> bindings. /// </summary> /// <returns> /// The value to be passed to the source object. /// </returns> /// <param name="value">The target data being passed to the source.</param><param name="targetType">The <see cref="T:System.Type"/> of data expected by the source object.</param><param name="parameter">An optional parameter to be used in the converter logic.</param><param name="culture">The culture of the conversion.</param> public object ConvertBack(object value,CultureInfo culture) { throw new NotImplementedException(); } }
转换器需要命名空间注册
xmlns:Converters="clr-namespace:YourProject.Converters"
然后在资源部分中引用转换器:
<UserControl.Resources> <Converters:ViewTemplateChooser x:Key="TemplateChooser" /> </UserControl.Resources>
最后我使用转换器将ViewModel转换为View,并将视图的Datacontext设置为ViewModel
<ContentControl Content="{Binding Workspace,Converter={StaticResource TemplateChooser}}" Margin="5,35,5,5" Grid.Column="1" />
可以修改转换器以实现导航策略,我试图使示例尽可能简单.
我希望这有帮助,你不必走极端 – 或第三方图书馆 – 来获得你想要的东西.