C# 将ContentControl绑定到ViewModel并在与关联的视图中保留该VM。
我正在创建一个WP8应用程序,将contentcontrol绑定到ViewModel。此ContentControl获取App.xaml.cs中为该VM指定的数据模板,并绑定到ContentControl模板。但问题是,我无法在我的视图中获取该VM的实例。如何获取或将VM实例传递给绑定到内容控件的视图。这是密码 问题是,当DyncmicContentControl获取ViewModel时,它调用GetTemplate方法从App.xaml.cs获取相应的DataTemplate,这将创建该视图的新实例,但我无法将此ViewModel传递给该视图。我怎样才能做到这一点 ContentControl.cs DataTemplateSelector.cs MainPage.xaml MainPageViewModel.cs App.xamlC# 将ContentControl绑定到ViewModel并在与关联的视图中保留该VM。,c#,wpf,xaml,windows-phone-8,mvvm,C#,Wpf,Xaml,Windows Phone 8,Mvvm,我正在创建一个WP8应用程序,将contentcontrol绑定到ViewModel。此ContentControl获取App.xaml.cs中为该VM指定的数据模板,并绑定到ContentControl模板。但问题是,我无法在我的视图中获取该VM的实例。如何获取或将VM实例传递给绑定到内容控件的视图。这是密码 问题是,当DyncmicContentControl获取ViewModel时,它调用GetTemplate方法从App.xaml.cs获取相应的DataTemplate,这将创建该视图的
ContentControl的ContentTemplate属性上设置的DataTemplate将应用于在该ContentControl的Content属性上设置的对象。因此,在本例中,设置ContentTemplate应该使用绑定到的UsrCntrlDynamic属性中的任何内容呈现该DataTemplate。这假设ContentControl的ControlTemplate设置正确,包括接收和呈现内容的ContentPresenter,而自定义DynamicContentControl可能不是这种情况。那么解决方案是什么?您可以为相同的问题建议解决方案吗。我正在努力寻找答案,但无法通过找到用于显示控件的ControlTemplate来解决问题。如果您不知道,可以尝试创建一个,并将其明确应用为起点。请详细说明。您的意思是我应该尝试找到UsrCntrlDyncmic用户控件父控件的父控件,然后进入VisualTree,然后尝试导出ViewModel吗?
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);
}
}
}
/// <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;
}
<Controls:DynamicContentControl Content="{Binding UsrCntrlDynamic}" />
public static ObservableCollection<object> ContentControlItems;
public MainPageViewModel()
{
ContentControlItems = new ObservableCollection<object>();
ContentControlItems.Add(new UserControlViewModel());
}
<DataTemplate x:Key="UserControlViewModel">
<vm:UserControlView />
</DataTemplate>