这很难追踪,并且给我带来了很大的痛苦 - 但似乎 ItemsControls
的行为并不符合我的预期。它几乎看起来像是 WPF 中的一个错误 - 但作为 WPF 的新手,我错误地认为这是我的错,而不是他们的错。
重现它非常简单 - 将 ItemsControl
绑定(bind)到 ObservableCollection
,然后替换集合中的项目。这太简单了,我不敢相信 Google 没有找到成千上万有同样问题的人。
下面的代码只是将 ItemsControl
绑定(bind)到 Brush
的 ObservableCollection
。更改画笔(通过单击按钮),您会收到一些数据错误,因为矩形的画笔绑定(bind)暂时属于 ItemsControl
的 DataContext
(!),而不是比新项目。每当我替换集合中的(不可变的常规 CLR 对象)项时,绑定(bind)的短暂崩溃都会导致我的应用程序在调试器中运行时需要半秒多的时间来更新 - 我做错了什么?
<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 4.0 的设备中尝试并成功后,我认为这是 .NET 3.5 中的问题。如果您的客户坚持在.NET 3.5版本中使用它,建议他们升级到.NET 4.0,这个问题将得到解决。谢谢:)
关于c# - 将 ObservableCollection 绑定(bind)到 ItemsControl - 并不像听起来那么简单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8177245/