2014-01-28 16 views
1

我是新來的WPF(1個半周),我已經閱讀並儘可能多地練習,並且在我的一次練習中我遇到了一個我一直沒有遇到的問題能夠解決,如何更新ItemsControl明確

我想告訴你,我已經知道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和它的工作,所以我缺少什麼?

在此先感謝。

+0

什麼問題?爲什麼ObservableCollection可以工作,或者如何顯式更新ItemsControl以顯示集合中的數據? –

+0

如何更新ItemsControl以顯示我的列表中的數據 – elios264

+1

您應該使用'INotifyPropertyChanged'來通知綁定源屬性已準備就緒。在這個例子中沒有理由直接操作綁定表達式。 – McGarnagle

回答

1

如果您不想通知ItemsControl,因爲你必須做出很多變化,你可以設置ItemsSourcenull,然後將其重新設置爲先前的值。如果您必須在集合中插入1000多個項目,則可以提供比每次插入後WPF更新視圖更好的性能。

但正如其他人指出的那樣,您應該首先嚐試使用ObservableCollection。

您也可以創建自己的類來實現INotifyCollectionChanged(例如通過繼承ObservableCollection)。您對集合進行必要的更改,然後用NotifyCollectionChangedAction.Reset提高CollectionChanged事件。這將指示ItemsControl完全更新自己。