我这样做是在几个商业项目的方式如下:
我有一个标准的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, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
转换器需要一个命名空间注册
xmlns:Converters="clr-namespace:YourProject.Converters"
然后您在资源部分参考了转换器:
<UserControl.Resources>
<Converters:ViewTemplateChooser x:Key="TemplateChooser" />
</UserControl.Resources>
,最后我用转换器将视图模型转换为视图设置为视图模型
<ContentControl Content="{Binding Workspace, Converter={StaticResource TemplateChooser}}" Margin="5,35,5,5" Grid.Column="1" />
该转换器可进行修改,以实现导航的战略视图的DataContext的,我试图让这个例子尽可能简单。
我希望这会有所帮助,您不必去极端或第三方图书馆得到您要找的东西。
我也在使用Prism的RegionManager,但是能否详细说明一下你如何做这件事的具体细节? – Jeff 2010-07-06 15:44:39
详细说明在我上面的编辑中。 – 2010-07-06 17:03:35
是的,谢谢。我喜欢这种方法。但它仍不能解决我上面提到的一个问题;绑定到IEnumerable - 例如将TabControl绑定到集合并期望每个选项卡显示MyViewForMyViewModelClass UserControl。或者有什么办法来调整你的方法来支持它?谢谢。 –
Jeff
2010-07-06 21:37:40