c# - 将 ObservableCollection 绑定(bind)到 ItemsControl - 并不像听起来那么简单?

标签 c# wpf xaml observablecollection itemscontrol

这很难追踪,并且给我带来了很大的痛苦 - 但似乎 ItemsControls 的行为并不符合我的预期。它几乎看起来像是 WPF 中的一个错误 - 但作为 WPF 的新手,我错误地认为这是我的错,而不是他们的错。

重现它非常简单 - 将 ItemsControl 绑定(bind)到 ObservableCollection,然后替换集合中的项目。这太简单了,我不敢相信 Google 没有找到成千上万有同样问题的人。

下面的代码只是将 ItemsControl 绑定(bind)到 BrushObservableCollection。更改画笔(通过单击按钮),您会收到一些数据错误,因为矩形的画笔绑定(bind)暂时属于 ItemsControlDataContext(!),而不是比新项目。每当我替换集合中的(不可变的常规 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/

相关文章:

c# - 为什么我们应该避免公共(public)方法?封装的好处

C# - 使用 Lambda 创建多线程

c# Regex.Matches 具有多个匹配结果的问题

c# - MVC5 区域不工作

c# - 如何在 WPF 中找到 UserControl 宽度?

wpf - 类似于 XAML 中的 For 循环

wpf - 如何在应用程序、窗口或控制级别关闭所有触摸输入?

.net - 使用 .Net 4.5 的功能区功能

C# WPF 无法从 UserControl 访问 ControlTemplate 中定义的按钮

c# - 在网格中使用 2 个不同的 ViewModel