簡體   English   中英

將ContentControl綁定到ViewModel並在與之關聯的View中保留該VM。

[英]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>

ContentControlContentTemplate屬性上設置的DataTemplate將應用於在該ContentControlContent屬性上設置的對象。 因此,在這種情況下,設置ContentTemplate應該使用綁定到的UsrCntrlDynamic屬性中的任何內容呈現該DataTemplate 這假定ContentControlControlTemplate設置正確,包括一個ContentPresenter來接收和呈現Content ,而自定義DynamicContentControl可能不是這種情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM