c# - 当 ObservableCollection 触发 CollectionChanged 时,ItemsControl 不会自行更新

标签 c# wpf mvvm binding

我已经阅读了很多关于这个问题的答案,但它们通常包含“你错过了 INotifyPropertyChanged”之类的内容。
我使用 MVVM light 来实现 ViewModelBase、ObservableObject 等。

查看:

<Window x:Class="BaseFlyingFigure.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:BaseFlyingFigure"
    xmlns:helpers="clr-namespace:BaseFlyingFigure.Helpers"
    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
    xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Platform"
    xmlns:system="clr-namespace:System;assembly=mscorlib"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="525"
    DataContext="{Binding MainViewModel, Source={StaticResource Locator}}">
<i:Interaction.Triggers>
    <i:EventTrigger EventName="Loaded">
        <cmd:EventToCommand Command="{Binding LoadedCommand}" />
    </i:EventTrigger>
    <i:EventTrigger EventName="PreviewKeyDown">
        <cmd:EventToCommand Command="{Binding PreviewKeyDownCommand}"
                            PassEventArgsToCommand="True" />
    </i:EventTrigger>
</i:Interaction.Triggers>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Menu Grid.Row="0">
        <MenuItem Header="File">
            <MenuItem Header="Exit" Command="{Binding AppExitCommand}" />
        </MenuItem>
    </Menu>
    <ItemsControl Grid.Row="1" helpers:SizeObserver.Observe="True"
                  helpers:SizeObserver.ObservedWidth="{Binding CanvasWidth, Mode=OneWayToSource}"
                  helpers:SizeObserver.ObservedHeight="{Binding CanvasHeight, Mode=OneWayToSource}"
                  ItemsSource="{Binding Elements, Converter={helpers:ElementToShapeConverter}, 
        Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
                  >
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Canvas ClipToBounds="True" />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>
</Grid>

查看型号:
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
using BaseFlyingFigure.Services.Interfaces;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;

namespace BaseFlyingFigure.ViewModels
{
    public class MainViewModel : ViewModelBase
    {
        private readonly IFigureRepository _repository;
        private ObservableCollection<Element> _elements = new ObservableCollection<Element>();


        public MainViewModel(IFigureRepository repository)
        {
            _repository = repository;

            AppExitCommand = new RelayCommand(Exit);
            LoadedCommand = new RelayCommand(WindowLoaded);

            PreviewKeyDownCommand = new RelayCommand<KeyEventArgs>(PreviewKeyDown);

            Elements.Add(new Element(new Ellipse {
                    Fill = Brushes.HotPink,
                    Width = 100,
                    Height = 100
                })
                {Left = 250, Top = 250});
        }

        public RelayCommand AppExitCommand { get; private set; }
        public RelayCommand LoadedCommand { get; private set; }
        public RelayCommand<KeyEventArgs> PreviewKeyDownCommand { get; private set; }

        public double CanvasWidth { get; set; }
        public double CanvasHeight { get; set; }

        public ObservableCollection<Element> Elements
        {
            get { return _elements; }
            set 
            {
                if (value != _elements)
                    Set(ref _elements, value);
            }
        }

        private void PreviewKeyDown(KeyEventArgs e)
        {
            switch (e.Key) {
                case Key.OemPlus:
                    Elements.Add(new Element(new Ellipse
                    {
                            Fill = Brushes.HotPink,
                            Width = 100,
                            Height = 100
                        })
                        {Left = 250, Top = 250});
                    Debug.WriteLine("+");
                    break;
            }
        }

        private void WindowLoaded()
        {
            Elements.CollectionChanged += (sender, args) => Debug.WriteLine("changed");
        }

        private void Exit() => Application.Current.Shutdown();
    }
}

转换器:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Windows.Data;
using System.Windows.Markup;
using BaseFlyingFigure.ViewModels;

namespace BaseFlyingFigure.Helpers
{
    public class ElementToShapeConverter : MarkupExtension, IValueConverter
    {
        private static ElementToShapeConverter _converter;

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var list = (value as ICollection<Element>)?.Select(el => el.Shape).ToList();
            return list;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return _converter ?? (_converter = new ElementToShapeConverter());
        }
    }
}

元素:
using System.Windows.Controls;
using System.Windows.Shapes;
using GalaSoft.MvvmLight;

namespace BaseFlyingFigure.ViewModels
{
    public class Element : ObservableObject
    {
        private double _left;
        private Shape _shape;
        private double _top;

        public Element(Shape shape)
        {
            Shape = shape;
        }

        public double Left
        {
            get { return _left; }
            set
            {
                Set(ref _left, value);
                Canvas.SetLeft(Shape, value);
            }
        }

        public double Top
        {
            get { return _top; }
            set
            {
                Set(ref _top, value);
                Canvas.SetTop(Shape, value);
            }
        }

        public Shape Shape
        {
            get { return _shape; }
            set { Set(ref _shape, value); }
        }
    }
}

当我们按下 + 时,CollectionChanged 会触发。但是 Canvas 显示在构造函数中制作和添加的形状。
查看模型定位器:
public class ViewModelLocator
{
    public ViewModelLocator()
    {
        ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
        SimpleIoc.Default.Register<MainViewModel>();
        SimpleIoc.Default.Register<IFigureRepository, FigureRepository>();
    }

    public MainViewModel MainViewModel => ServiceLocator.Current.GetInstance<MainViewModel>();
}

那有什么问题? XAML 或其他内容中的任何错误?

最佳答案

您的方法的基本问题是您使用 Shape View 模型中的对象。

除此之外,不可能有多个 View 来可视化这个 View 模型(因为 UIElements 只能有一个父级),它还迫使您使用一种非常规且有缺陷的方法来转换 ObservableCollection<Element>List<Shape>在 ItemsSource 绑定(bind)的转换器中。如评论和其他答案中所述,List<Shape>从转换器返回的 ObservableCollection<Element> 中的更改不会通知 View 。 .

适当的 MVVM 方法将使用没有 UI 元素的形状表示,例如像这样:

public class Element
{
    public Geometry Shape { get; set; }
    public Brush Fill { get; set; }
    public Brush Stroke { get; set; }
    public double StrokeThickness { get; set; }
}

您现在可以为 ItemsControl 中的形状的可视化声明一个常规 DataTemplate:
<ItemsControl ItemsSource="{Binding Elements}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Path Data="{Binding Shape}"
                  Fill="{Binding Fill}"
                  Stroke="{Binding Stroke}"
                  StrokeThickness="{Binding StrokeThickness}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

将示例椭圆添加到您的 View 模型现在看起来像这样:
Elements.Add(new Element
{
    Shape = new EllipseGeometry(new Point(250, 250), 50, 50),
    Fill = Brushes.HotPink
});

如果出于任何原因您还需要为每个元素添加额外的 x/y 位置偏移量,您可以向 Element 类添加两个属性
public class Element
{
    ...
    public double X { get; set; }
    public double Y { get; set; }
}

并添加 ItemsContainerStyle到使用这些属性的 ItemsControl:
<ItemsControl ItemsSource="{Binding Elements}">
    ...
    <ItemsControl.ItemContainerStyle>
        <Style TargetType="ContentPresenter">
            <Setter Property="Canvas.Left" Value="{Binding X}"/>
            <Setter Property="Canvas.Top" Value="{Binding Y}"/>
        </Style>
    </ItemsControl.ItemContainerStyle>
</ItemsControl>

关于c# - 当 ObservableCollection 触发 CollectionChanged 时,ItemsControl 不会自行更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40258990/

相关文章:

wpf - 在 DataGrid 中使用 DataGridComboBoxColumn 作为自动完成组合框

c# - 创建新 View 时如何初始化 View 模型中的属性?

c# - 如何以编程方式设置 AppBar 高度?

c# - MVC4中的Html.Serialize在哪里

c# - 如何在不违反 MVVM 模式的情况下从 WPF 中的 TabControl 更改 Tab

c# - 带有 Windows 窗体的 WPF - STAThread

wpf - 使用 Caliburn.Micro 时对多个控件使用相同的方法

c# - Linq 查询中的异常处理

c# - 有方法的属性?

wpf - 获取 WPF ListView 的 HeaderClick 事件