首页 > 解决方案 > ItemsControl 中的元素不会更新,但在 ListBox 中它们会更新

问题描述

(编辑整篇文章,因为你们认为有一些代码魔法正在发生)

介绍

我有一个Observable Collection应该在列表中可视化

为此,我想使用ItemsControl,但列表元素不会更新(它们为空或显示我定义的后备值)

当使用ListBox 时,它按预期工作,但是我得到了我不想要的列表项选择。

TL;博士; 问题

ItemsControl 不显示正确的值,但 ListBox 可以。

重现代码

为了重现问题,我做了一个新的 WPF 项目,尽可能简单地显示问题,这是我的最小示例的完整代码

我有一个自定义 UserControl 主要显示一些文本,在这种情况下是一个地址,它(当前)仅在构造函数中设置:

using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Controls;

namespace WpfApp1
{
    public partial class MyUserControl : UserControl, INotifyPropertyChanged
    {
        private readonly string _address;

        public MyUserControl()
        {
            InitializeComponent();
        }

        public MyUserControl(string address)
        {
            InitializeComponent();
            _address = address;
            OnPropertyChanged(nameof(Address));
        }

        public string Address => _address;

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

    }
}

这是用户控件的 XAML 代码:

<UserControl x:Class="WpfApp1.MyUserControl"
             <!-- snip namespaces --> 
             xmlns:local="clr-namespace:WpfApp1"
             mc:Ignorable="d" 
             d:DesignHeight="20" d:DesignWidth="300">
    <Border BorderBrush="Black" BorderThickness="0.6">
        <Border.Style> <!-- snip --> </Border.Style>
        <StackPanel Orientation="Horizontal">
            <Label Grid.Column="0" Grid.Row="0" Padding="2" Content="Address:"/>
            <Label Grid.Column="1" Grid.Row="0" Padding="2" Grid.ColumnSpan="2" Content="{Binding Path=Address, FallbackValue=00000000000000000000000000000}"/>
        </StackPanel>
    </Border>
</UserControl>

主窗口的 XAML 现在使用相同的绑定呈现两个列表,一个 ItemsControl 和一个 ListBox

<Window x:Class="WpfApp1.MainWindow"
       <!-- snip namespaces -->
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <StackPanel x:Name="FeeKeyListView" VerticalAlignment="Top" HorizontalAlignment="Stretch" Margin="5">
            <ItemsControl ItemsSource="{Binding MyList, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}" HorizontalContentAlignment="Stretch" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MinHeight="200">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <StackPanel/>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <local:MyUserControl/>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
            <ListBox ItemsSource="{Binding MyList, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}" HorizontalContentAlignment="Stretch" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MinHeight="200">
                <ListBox.ItemsPanel>
                    <ItemsPanelTemplate>
                        <StackPanel/>
                    </ItemsPanelTemplate>
                </ListBox.ItemsPanel>
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <local:MyUserControl/>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </StackPanel>
    </Grid>
</Window>

最后但并非最不重要的 MainWindow 类,其中包含 Observable 列表:

using System.Collections.ObjectModel;
using System.Windows;

namespace WpfApp1
{
    public partial class MainWindow : Window
    {

        public ObservableCollection<MyUserControl> MyList { get; set; } = new ObservableCollection<MyUserControl>();

        public MainWindow()
        {
            InitializeComponent();

            MyList.Clear();
            MyList.Add(new MyUserControl("my address1"));
        }
    }
}

结果窗口显示,值已正确绑定在 ListBox 中,但未正确绑定在 ItemsControl 中

所需的行为是,ItemsControl 像 ListBox 一样显示“我的地址 1”。

在此处输入图像描述

标签: c#wpflistboxitemscontrol

解决方案


ItemsControlIsItemItsOwnContainerOverride中方法的不同实现导致不同的行为

protected virtual bool IsItemItsOwnContainerOverride(object item)
{
    return (item is UIElement);
}

并在列表框中

protected override bool IsItemItsOwnContainerOverride(object item)
{
    return (item is ListBoxItem);
}

Items当该方法为or集合中的项目返回 true 时ItemsSource- 它在 ItemsControl 中为您的 UserControls 执行 - 不会生成项目容器,因此不会应用 ItemTemplate。

但是,您通常不会将 UIElement 的集合分配给 ItemsSource 属性,而是将视图模型项的集合 - ItemTemplate 中的元素绑定到它们的属性。


推荐阅读