开发者

WPF : Multiple views, one DataContext

开发者 https://www.devze.com 2022-12-30 01:37 出处:网络
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.

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 :

<Items开发者_开发百科Control 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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消