title: PRISM View Injection inside ItemsControl
body: <p><strong>UPDATED (12/17/2009):</strong> Now reflects latest progress I've made.</p>
  
  <p>This is the first application that myself and a co-worker are developing using Prism and MVVM in Silverlight 3.0. I am working on a shell/framework for the project that will have a list of "plugins" that can be added to a "workspace". </p>
  
  <p>The plugins are registered with a WorkSpaceManager class during their particular PRISM IModule.Initialize() methods like so:</p>
  
  <pre><code>workspace.RegisterPlugin(new PluginInfo() { Name = "MyPlugin", ViewType = typeof(MyPluginView), SettingsViewType = null });
  </code></pre>
  
  <p>The RegisterPlugin() method simply adds the PluginInfo object to a dictionary keyed on the "Name" property. Then when I want to add a plugin to the workspace I do the following:</p>
  
  <pre><code>workspace.AddPluginToWorkspace("MyPlugin");
  </code></pre>
  
  <p>The AddPluginToWorkspace method of the WorkspaceManager class looks like this:</p>
  
  <pre><code>public void AddPluginToWorkspace(string pluginName)
      {
          if (AvailablePlugins.ContainsKey(pluginName))
          {
              PluginInfo pi = AvailablePlugins[pluginName];
              WorkspacePlugin wsp = new WorkspacePlugin();
  
              // Create the View
              wsp.View = (Control)this.unityContainer.Resolve(pi.ViewType);
              wsp.Name = pi.Name;
  
              // Wire up the CloseCommand to WorkspaceManager's PluginClosing handler
              wsp.CloseCommand = new DelegateCommand&lt;WorkspacePlugin&gt;(this.PluginClosing);
  
              // Add the plugin to the active plugins (modules) collection
              this.modules.Add(wsp);
  
              // FIX: This should notify anyone listening that the ActivePlugins have changed. When enabled, this causes the same error that will be mentioned further on when attempting to close a plugin.
              //this.eventAggregator.GetEvent&lt;ActivePluginsChanged&gt;().Publish(wsp);
          }
  
      }
  </code></pre>
  
  <p>The Workspace ViewModel simply exposes the WorkspaceManager Service's modules collection which is the datacontext of the Workspace View as shown here:</p>
  
  <pre><code>&lt;Grid x:Name="LayoutRoot"
        Background="White"&gt;
      &lt;ListBox x:Name="ModuleListBox"
               Grid.Row="1"
               rgn:RegionManager.RegionName="Workspace"
               Background="Yellow"
               ItemsSource="{Binding Plugins}"&gt;
          &lt;ListBox.ItemsPanel&gt;
              &lt;ItemsPanelTemplate&gt;
                  &lt;Canvas /&gt;
              &lt;/ItemsPanelTemplate&gt;
          &lt;/ListBox.ItemsPanel&gt;
          &lt;ListBox.Template&gt;
              &lt;ControlTemplate&gt;
                  &lt;Grid x:Name="ListBoxGrid"&gt;
                      &lt;ItemsPresenter&gt;&lt;/ItemsPresenter&gt;
                  &lt;/Grid&gt;
              &lt;/ControlTemplate&gt;
          &lt;/ListBox.Template&gt;
          &lt;ListBox.ItemTemplate&gt;
              &lt;DataTemplate&gt;
                  &lt;Border BorderBrush="Black"
                          BorderThickness="2"
                          Margin="0"
                          Padding="0"&gt;
                      &lt;Grid&gt;
                          &lt;Grid.RowDefinitions&gt;
                              &lt;RowDefinition Height="20"&gt;&lt;/RowDefinition&gt;
                              &lt;RowDefinition Height="*"&gt;&lt;/RowDefinition&gt;
                              &lt;RowDefinition Height="5"&gt;&lt;/RowDefinition&gt;
                          &lt;/Grid.RowDefinitions&gt;
                          &lt;Grid Grid.Row="0"&gt;
                              &lt;Grid.ColumnDefinitions&gt;
                                  &lt;ColumnDefinition Width="*"&gt;&lt;/ColumnDefinition&gt;
                                  &lt;ColumnDefinition Width=".05*"&gt;&lt;/ColumnDefinition&gt;
                              &lt;/Grid.ColumnDefinitions&gt;
                              &lt;Button Content="X"
                                      HorizontalAlignment="Right"
                                      Grid.Column="1"
                                      cmd:Click.Command="{Binding CloseCommand}"
                                      cmd:Click.CommandParameter="{Binding}"&gt;&lt;/Button&gt;
                          &lt;/Grid&gt;
                          &lt;Border BorderBrush="Black"
                                  BorderThickness="2"
                                  Margin="0"
                                  VerticalAlignment="Center"
                                  HorizontalAlignment="Center"
                                  Grid.Row="1"&gt;
                              &lt;tk:Viewbox Stretch="Uniform"
                                          StretchDirection="Both"&gt;
                                  &lt;ContentControl Content="{Binding View}"&gt;&lt;/ContentControl&gt;                    
                              &lt;/tk:Viewbox&gt;
                          &lt;/Border&gt;                            
                      &lt;/Grid&gt;
                  &lt;/Border&gt;
              &lt;/DataTemplate&gt;
          &lt;/ListBox.ItemTemplate&gt;
      &lt;/ListBox&gt;
  &lt;/Grid&gt;
  </code></pre>
  
  <p><strong>Notice the Content control that is bound to the "View" property of the WorkspacePlugin and the Button that has the Click.Command bound to the "CloseCommand".</strong> This is where I was stuck initially but for the most part, this works. The plugin's view is loaded inside the other controls and I'm still able to bind the close command (And other commands to be added at a later time) to an underlying model. </p>
  
  <p><strong>The problem now</strong> is that whenever I click the close button and the WorkspacePlugin is removed from the modules collection, a property changed event is fired on the ViewModel to let the listbox know to update I get the following error (This also happens if I uncomment the line below the "FIX" comment above:</p>
  
  <blockquote>
    <p>System.ArgumentException: Value does not fall within the expected range.
       at MS.Internal.XcpImports.CheckHResult(UInt32 hr)
       at MS.Internal.XcpImports.SetValue(INativeCoreTypeWrapper obj, DependencyProperty property, DependencyObject doh)
       at MS.Internal.XcpImports.SetValue(INativeCoreTypeWrapper doh, DependencyProperty property, Object obj)
       at System.Windows.DependencyObject.SetObjectValueToCore(DependencyProperty dp, Object value)
       at System.Windows.DependencyObject.RefreshExpression(DependencyProperty dp)
       at System.Windows.Data.BindingExpression.RefreshExpression()
       at System.Windows.Data.BindingExpression.SendDataToTarget()
       at System.Windows.Data.BindingExpression.SourceAquired()
       at System.Windows.Data.BindingExpression.DataContextChanged(Object o, DataContextChangedEventArgs e)
       at System.Windows.FrameworkElement.OnDataContextChanged(DataContextChangedEventArgs e)
       at System.Windows.FrameworkElement.OnTreeParentUpdated(DependencyObject newParent, Boolean bIsNewParentAlive)
       at System.Windows.DependencyObject.UpdateTreeParent(IManagedPeer oldParent, IManagedPeer newParent, Boolean bIsNewParentAlive, Boolean keepReferenceToParent)
       at MS.Internal.FrameworkCallbacks.ManagedPeerTreeUpdate(IntPtr oldParentElement, IntPtr parentElement, IntPtr childElement, Byte bIsParentAlive, Byte bKeepReferenceToParent)</p>
  </blockquote>
  
  <p>From what I gather by looking online, this typically means that a visual element that was already added to the visual tree is trying to be added again. This kind of makes since if I only have 1 plugin displayed and close it, it disappears and there is no error. I am fairly certain that the error is due to the WorkspacePlugin.View property being a visual control and the binding update is attempting to re-add it to the visual tree.</p>
  
  <p>How can I work around this or achieve the desired result without the error message? </p>