views:

159

answers:

1

Hi,

I'm working on a WPF application which must handle multiple screens (two at this this time).

One view can be opened on several screens and user actions must be reflected consistently on all screens.

To achieve this, for a given type of view, a single DataContext is instantiated. Then, when a view is displayed on a screen, the unique DataContext is attached to it. So, one DataContext, several views (same type of view/xaml).

So far so good. It works quite well in most cases.

I do have a problem with a specific view which relies on ItemsControl. These ItemsControl are used to display UIElements dynamically build in the ViewModel/DataContext (C# code). These UIElements are mostly Path objects. Example :

<ItemsControl ItemsSource="{Binding WindVectors}">
   <ItemsControl.Template>
     <ControlTemplate TargetType="{x:Type ItemsControl}">
       <Canvas IsItemsHost="True" />
     </ControlTemplate>
   </ItemsControl.Template>
 </ItemsControl>

Here, WindVectors is a ObservableCollection<UIElement>.

When the view is opened the first time, everything is fine. The problem is that when the view is opened one another screen, all ItemsControl are removed from the first screen and displayed one the second screen. Other WPF components (TextBlock for instance) on this view react normally and are displayed on both screens.

Any help would be greatly appreciated.

Thanks.

Fabrice

A: 

This is the expected behavior (ie been that way since winforms)- this is because the ObservableCollection is a reference. This wont happen with value types, only reference types.

The short answer is 'dont do that'. You could try looking into defining a collection view in the xaml or code a custom data provider and bind to one of those instead.

J Rothe
Thanks for the answer.I don't think references or ObservableCollection are involved. I have other graphical components bound to ObservableCollections of reference objects (via ListBox for example) and they are displayed on both screens. I think it's more about ItemsControl but I can't really elaborate on this :)
zapho
List box takes the items and generates ListItems- it does not use the item in the collection directly where as ItemsControl does. When you bind an ItemsControl (or similar control) to a collection the target control holds onto that collection as a reference- binding the same collection to another control shifts the reference away from the current control which will cause it to lose its data. You either have to clone the list or look into a collectionview.
J Rothe