这是非常难以追查,并导致我很大的痛苦 - 但似乎ItemsControls
不表现我所期望的。它几乎看起来像WPF中的错误 - 但对WPF来说是新手,我错在这是我的错,而不是他们的错。将ObservableCollection绑定到ItemsControl - 并不像听起来那么简单?
重现它非常简单 - 将ItemsControl
绑定到ObservableCollection
,然后替换集合中的项目。这很简单,我不能相信谷歌没有发现成千上万的人有同样的问题。
下面的代码只是将ItemsControl
绑定到Brush
的ObservableCollection
。更改画笔(通过单击按钮),并且由于矩形的画笔装订暂时为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;
}
}
}
这与我合作 –
我可以问你正在使用什么.NET版本?我在3.5,VS2008。 – Mania
我正在使用.NET 4.0 –