我在几个商业项目中的做法如下:
我有一个标准的 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>
最后我使用转换器将 ViewModel 转换为 View,并将 View 的 Datacontext 设置为 ViewModel
<ContentControl Content="{Binding Workspace, Converter={StaticResource TemplateChooser}}" Margin="5,35,5,5" Grid.Column="1" />
可以修改转换器以实现导航策略,我试图使示例尽可能简单。
我希望这会有所帮助,您不必走极端 - 或第三方库 - 即可获得所需的内容。