[英]Binding ContentControl to ViewModel and preserving that VM in the View associated with.
我正在創建WP8應用程序,其中將contentcontrol綁定到ViewModel。 此ContentControl采用該VM的App.xaml.cs中指定的DataTemplate並綁定到contentcontrol模板。 但是問題是我無法在View中獲取該VM的實例。 如何獲取或傳遞我的VM實例到綁定到內容控件的View。 這是代碼?
問題是當DyncmicContentControl獲取一個ViewModel時,它將調用GetTemplate()方法從App.xaml.cs獲取相應的DataTemplate,這將創建該View的新實例,但我無法將此ViewModel傳遞給該View。 我該如何實現?
ContentControl.cs
public class DynamicContentControl : ContentControl
{
/// <summary>
/// Called when the value of the <see cref="P:System.Windows.Controls.ContentControl.Content" /> property changes.
/// </summary>
/// <param name="oldContent">The old value of the <see cref="P:System.Windows.Controls.ContentControl.Content" /> property.</param>
/// <param name="newContent">The new value of the <see cref="P:System.Windows.Controls.ContentControl.Content" /> property.</param>
protected override void OnContentChanged(object oldContent, object newContent)
{
if (newContent != null)
{
base.OnContentChanged(oldContent, newContent);
this.ContentTemplate = DataTemplateSelector.GetTemplate(newContent);
}
}
}
DataTemplateSelector.cs
/// <summary>
/// Gets the template.
/// </summary>
/// <param name="param">The parameter.</param>
/// <returns></returns>
public static DataTemplate GetTemplate(object param)
{
Type t = param.GetType();
DataTemplate templateData = App.Current.Resources[t.Name] as DataTemplate;
return templateData;
}
MainPage.xaml
<Controls:DynamicContentControl Content="{Binding UsrCntrlDynamic}" />
MainPageViewModel.cs
public static ObservableCollection<object> ContentControlItems;
public MainPageViewModel()
{
ContentControlItems = new ObservableCollection<object>();
ContentControlItems.Add(new UserControlViewModel());
}
應用程式
<DataTemplate x:Key="UserControlViewModel">
<vm:UserControlView />
</DataTemplate>
在ContentControl
的ContentTemplate
屬性上設置的DataTemplate
將應用於在該ContentControl
的Content
屬性上設置的對象。 因此,在這種情況下,設置ContentTemplate
應該使用綁定到的UsrCntrlDynamic
屬性中的任何內容呈現該DataTemplate
。 這假定ContentControl
的ControlTemplate
設置正確,包括一個ContentPresenter
來接收和呈現Content
,而自定義DynamicContentControl
可能不是這種情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.