【问题标题】:Binding ContentControl to ViewModel and preserving that VM in the View associated with.将 ContentControl 绑定到 ViewModel 并将该 VM 保留在关联的 View 中。
【发布时间】: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


    【解决方案1】:

    ContentControlContentTemplate 属性上设置的DataTemplate 应用于在ContentControlContent 属性上设置的对象。因此,在这种情况下,设置 ContentTemplate 应该使用您绑定到的 UsrCntrlDynamic 属性中的任何内容呈现 DataTemplate。这假设您的ContentControlControlTemplate 设置正确,包括用于接收和呈现ContentContentPresenter,而您的自定义DynamicContentControl 可能不是这种情况。

    【讨论】:

    • 那么解决方案是什么,您可以提出相同的解决方案吗?我正在努力寻找答案,但无法解决
    • 首先找到用于显示控件的 ControlTemplate。如果您不知道,可以尝试创建一个并明确应用它作为起点。
    • 能否详细说明。你的意思是我应该尝试找到UsrCntrlDyncmic User控件父级的父级并上VisualTree然后尝试派生ViewModel?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-18
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    相关资源
    最近更新 更多