将ObservableCollection绑定到ItemsControl - 不是听起来那么简单吗?

Man*_*nia 2 c# wpf xaml itemscontrol observablecollection

这很难追查并给我带来了很大的痛苦 - 但似乎ItemsControls并没有像我期望的那样表现.这几乎看起来像WPF中的一个错误 - 但是对WPF来说是新手,我犯错了,这是我的错,而不是他们的错.

要重现它非常简单 - 将an绑定ItemsControl到a ObservableCollection,然后替换集合中的项.这很简单,我无法相信谷歌没有找到数千人遇到同样的问题.

下面简单地将代码绑定一个ItemsControlObservableCollectionBrush.更改刷(点击按钮),你会得到一对夫妇的数据错误为矩形的画笔结合是暂时的DataContextItemsControl(!),而不是新的项目.这种绑定的瞬间崩溃导致我的应用程序每当我替换集合中的(不可变的,常规的CLR对象)项时在调试器中运行时需要花费半秒钟更新 - 我做错了什么?

<Window x:Class="Dummy.Test"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Test" Height="300" Width="300">
    <Grid>
        <ItemsControl ItemsSource="{Binding Foos}">
            <ItemsControl.ItemTemplate>
                <DataTemplate DataType="{x:Type Brush}">
                    <Rectangle Width="20" Height="20" Fill="{Binding}" />
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
        <Button HorizontalAlignment="Center" VerticalAlignment="Bottom" Click="SwitchClick">Switch</Button>
    </Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)
using System;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Media;

namespace Dummy
{
    public partial class Test : Window
    {
        private readonly ObservableCollection<Brush> foos = new ObservableCollection<Brush>();
        public ObservableCollection<Brush> Foos { get { return foos; } }
        public Test()
        {
            InitializeComponent();
            Foos.Add(Brushes.Green);
            DataContext = this;
        }

        private void SwitchClick(object sender, EventArgs e)
        {
            Foos[0] = Foos[0] == Brushes.Green ? Brushes.Silver : Brushes.Green;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

All*_*hua 5

啊在我使用.NET 4.0的单元中尝试它之后,我认为这是.NET 3.5中的一个问题.如果您的客户坚持在.NET 3.5版本中使用它,建议他们升级到.NET 4.0,这个问题将被关闭.谢谢 :)