如果集合值相同,为什么LongListSelector会添加额外的项目?

Iri*_*son 5 c# xaml windows-phone-8

我昨天在为WP编写演示应用程序时发现了这种奇怪的行为.通常我从不传递普通物品,也从不传递"相同" - 但这次我做了.当绑定到int或string类型的observablecollection时,如果值相同,则控件将添加第一个项,然后是两个,然后是三个,然后是四个.而不是每次添加一个.基本上这样做:

Items.Count ++

但是,如果我将项目(例如字符串)更改为唯一的(例如GUID.ToString),则它具有预期的行为.

这与DataContext的设置方式无关,或者我是否将LayoutMode ="List"IsGroupingEnabled ="False"添加到控件中.

为什么这样做?这是预期的行为吗?

我花了几个小时寻找答案,所以请不要粘贴关于控件的随机链接:)

视图代码:

<phone:PhoneApplicationPage
x:Class="Bug.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True"
DataContext="{Binding RelativeSource={RelativeSource Self}}">

<StackPanel>
    <Button Click="Button_Click">Add</Button>
    <phone:LongListSelector  Width="300" Height="600" ItemsSource="{Binding Items}"/>
</StackPanel>
</phone:PhoneApplicationPage>
Run Code Online (Sandbox Code Playgroud)

代码背后:

using System.Collections.ObjectModel;
using System.Windows;


namespace Bug
{
    public partial class MainPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            Items = new ObservableCollection<string>();

            //DataContext = this;
        }

        public ObservableCollection<string> Items { get; set; }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Items.Add("A");

            // This works as expected
            //Items.Add(Guid.NewGuid().ToString());
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

dot*_*ten 2

这是 LongListSelector 中的一个错误。它与 Guid 一起使用的原因是因为这将进行参考比较并避免错误。

这是使用引用对象代替的解决方法:

public partial class MainPage : PhoneApplicationPage
{
    // Constructor
    public MainPage()
    {
        InitializeComponent();

        // Sample code to localize the ApplicationBar
        Items = new ObservableCollection<Object>();

    }
    public ObservableCollection<Object> Items { get; set; }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        Items.Add(new Object() { Value = "A" });

        // This works as expected
        //Items.Add(Guid.NewGuid().ToString());
    }

}
public class Object
{
    public string Value { get; set; }

    public override string ToString()
    {
        return Value;
    }
}
Run Code Online (Sandbox Code Playgroud)