tags:

views:

171

answers:

1

If I create multiple ListViews with the same ItemsSource they become strangely linked. In the following example, the two ListViews display a common list of strings. The assertions show that the two ItemCollections and SortDescriptionCollections are distinct, but if I attempt to sort the ListViews differently, the second sort order is applied to both.

The two ItemCollections must be related in order for the Selector.IsSynchronizedWithCurrentItem property to have any effect, but I would like to be able to break this association so that I can do things like I've tried in this example. Does anyone know how these collections are related, and how I can sever this relationship?

XAML:

<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:llv="clr-namespace:LinkedListViews"
        x:Class="LinkedListViews.Window1"
        x:Name="Window"
        Title="Window1"
        Width="640" Height="480">

    <Grid x:Name="LayoutRoot">
        <ListView 
          x:Name="ListView1"
          ItemsSource="{Binding ElementName=Window, Path=Data}" 
          Margin="75,8,0,8" Width="237" HorizontalAlignment="Left"/>
        <ListView 
          x:Name="ListView2"
          ItemsSource="{Binding ElementName=Window, Path=Data}" 
          HorizontalAlignment="Right" Margin="0,8,73,8" Width="243"/>
    </Grid>
</Window>

Code behind:

using System;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.ComponentModel;
using System.Collections.Generic;

namespace LinkedListViews
{
    public partial class Window1
    {
        private List<string> _Data = new List<string>
        { 
            "Alpha", "Beta", "Gamma"
        };
        public List<string> Data
        {
            get { return _Data; }
        }

        public Window1()
        {
            this.InitializeComponent();

            // Insert code required on object creation below this point.
            System.Diagnostics.Debug.Assert(ListView1.Items != ListView2.Items);
            System.Diagnostics.Debug.Assert(ListView1.Items.SortDescriptions != ListView2.Items.SortDescriptions);
            this.ListView1.Items.SortDescriptions.Add(new SortDescription(null, ListSortDirection.Ascending));
            this.ListView2.Items.SortDescriptions.Clear();
            this.ListView2.Items.SortDescriptions.Add(new SortDescription(null, ListSortDirection.Descending));
        }
    }
}