ListView项集合如何相关?

时间:2009-07-01 14:18:13

标签: c# wpf

如果我使用相同的ListView创建多个ItemsSource,则它们会变得奇怪地相关联。在以下示例中,两个ListView显示一个公共字符串列表。断言显示两个ItemCollectionSortDescriptionCollection是不同的,但如果我尝试以不同方式对ListView进行排序,则第二个排序顺序将应用于两者。

两个ItemCollection必须相关才能使Selector.IsSynchronizedWithCurrentItem属性产生任何影响,但我希望能够打破这种关联,这样我才能做出像我这样的事情在这个例子中尝试过。有谁知道这些集合是如何相关的,以及我如何切断这种关系?

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>

代码背后:

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));
        }
    }
}

1 个答案:

答案 0 :(得分:1)