我這樣做是在幾個商業項目的方式如下:
我有一個標準的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