簡體   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