【发布时间】:2014-04-09 05:18:24
【问题描述】:
我正在创建一个 WP8 应用程序,我在其中将 contentcontrol 绑定到 ViewModel。此 ContentControl 采用在 App.xaml.cs 中为该 VM 指定的 DataTemplate 并绑定到 contentcontrol 模板。但问题是我无法在我的视图中获取该虚拟机的实例。如何获取或传递我的 VM 实例到绑定到内容控件的视图。这是代码?
问题是当 DynacmicContentControl 获取 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());
}
App.xaml
<DataTemplate x:Key="UserControlViewModel">
<vm:UserControlView />
</DataTemplate>
【问题讨论】:
标签: c# wpf xaml windows-phone-8 mvvm