2011-11-18 80 views
2

这是非常难以追查,并导致我很大的痛苦 - 但似乎ItemsControls不表现我所期望的。它几乎看起来像WPF中的错误 - 但对WPF来说是新手,我错在这是我的错,而不是他们的错。将ObservableCollection绑定到ItemsControl - 并不像听起来那么简单?

重现它非常简单 - 将ItemsControl绑定到ObservableCollection,然后替换集合中的项目。这很简单,我不能相信谷歌没有发现成千上万的人有同样的问题。

下面的代码只是将ItemsControl绑定到BrushObservableCollection。更改画笔(通过单击按钮),并且由于矩形的画笔装订暂时为ItemsControl(!)的DataContext,而不是新项目,因此会出现一些数据错误。当我更换集合中的一个(不可变的,常规的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> 
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; 
     } 
    } 
} 
+0

这与我合作 –

+1

我可以问你正在使用什么.NET版本?我在3.5,VS2008。 – Mania

+0

我正在使用.NET 4.0 –

回答

5

Ahmm在我单位,它使用.NET 4.0尝试它后,它的工作了,我认为这是.NET 3.5中的问题。如果你的客户坚持要在.NET 3.5中使用它,建议他们升级到.NET 4.0,这个问题应该关闭。谢谢:)

+0

很高兴知道这个... –

相关问题