繁体   English   中英

如何显式更新ItemsControl

[英]How to Update ItemsControl explicitly

我是WPF的新手(半个星期),我已尽可能多地阅读和练习,在我的一项练习中,我遇到了一个无法解决的问题,

我想让您知道我已经知道ObservableCollection,但是我不能使用它,因为在准备好显示列表之前我意识到对列表的许多更改,所以这就是为什么我决定使绑定显式的原因:

 <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并成功运行,所以我缺少什么?

提前致谢。

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

但是正如其他人指出的那样,您应该首先尝试使用ObservableCollection。

您也可以创建自己的实现INotifyCollectionChanged的类(例如,通过从ObservableCollection继承)。 您对集合进行了必要的更改,然后使用NotifyCollectionChangedAction.Reset引发CollectionChanged事件。 这将指示ItemsControl完全更新自身。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM