如何显式更新ItemsControl

时间:2014-01-28 19:49:58

标签: c# wpf xaml

我是WPF的新手(1周半),我尽可能多地阅读和练习,在我的一次练习中遇到了一个我无法解决的问题,< / p>

我想告诉你我已经知道了ObservableCollection,但我无法使用它,因为我在列表准备好显示之前就已经意识到了很多变化,所以这就是为什么我决定明确绑定:< / p>

 <ItemsControl  Background="Transparent" BorderBrush="Black" BorderThickness="1" Name="elementContainer" >
            <ItemsControl.ItemsSource>
                <Binding  UpdateSourceTrigger="Explicit" Mode="OneWay"  diag:PresentationTraceSources.TraceLevel="High" />
            </ItemsControl.ItemsSource>
                <ItemsControl.ItemContainerStyle>
                    <Style TargetType="ContentPresenter">
                        <Setter Property="Canvas.Left" Value="{Binding Rect.Left}" />
                        <Setter Property="Canvas.Top" Value="{Binding Rect.Top}" />
                    </Style>
                </ItemsControl.ItemContainerStyle>
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <Canvas/>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                            <Rectangle Width="{Binding Rect.Width}" Height="{Binding Rect.Height}" Stroke="#FFE01313" ></Rectangle>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>

C#代码:

List<Rect> mData;

DataContext = mData;

mData.Add(new Rect(20,20,20,20));

 var res = elementContainer.GetBindingExpression(ItemsControl.ItemsSourceProperty);
  res.UpdateTarget();

但我得到的只是这个日志:

System.Windows.Data Warning: 101 : BindingExpression (hash=44489159): GetValue at level 0 from List`1 (hash=45943265 Count=3) using <null>: List`1 (hash=45943265 Count=3)
System.Windows.Data Warning: 80 : BindingExpression (hash=44489159): TransferValue - got raw value List`1 (hash=45943265 Count=3)
System.Windows.Data Warning: 89 : BindingExpression (hash=44489159): TransferValue - using final value List`1 (hash=45943265 Count=3)

我暂时切换到ObservableCollection并且它有效,所以我错过了什么?

先谢谢。

1 个答案:

答案 0 :(得分:1)

如果您不想通知ItemsControl,因为您必须进行多次更改,可以将ItemsSource设置为null,然后将其重新设置为之前的值。如果您必须在集合中插入1000多个项目,这可以提供比每次插入后WPF更新视图更好的性能。

但正如其他人所指出的,你应该首先尝试使用ObservableCollection。

您还可以创建自己的实现INotifyCollectionChanged的类(例如,继承自ObservableCollection)。您对集合执行所需的更改,然后使用CollectionChanged引发NotifyCollectionChangedAction.Reset事件。这将指示ItemsControl完全自我更新。