WPF列表框沒有使用ItemsSource更新

[英]WPF ListBox not updating with the ItemsSource


I have what I believe should be simple two-way databinding in WPF setup, but the listbox (target) is not updating as the collection changes.

我相信在WPF設置中應該是簡單的雙向數據綁定,但是listbox (target)不會隨着集合的變化而更新。

I'm setting this ItemsSource of the ListBox programmatically:

我正在程序化地設置列表框的這個ItemsSource:

lstVariable_Selected.ItemsSource = m_VariableList;

And the ListBox is declared as follows:

列表框聲明如下:

           <ListBox Margin="5" Name="lstVariable_Selected">
              <ListBox.ItemsPanel>
                 <ItemsPanelTemplate>
                    <VirtualizingStackPanel Orientation="Horizontal"/>
                 </ItemsPanelTemplate>
              </ListBox.ItemsPanel>
              <ListBox.ItemTemplate>
                 <DataTemplate>
                    <Border BorderBrush="Gray" BorderThickness="1" Margin="0">
                       <TextBlock FontSize="25" Text="{Binding Path=Name}" />
                    </Border>
                 </DataTemplate>
              </ListBox.ItemTemplate>
           </ListBox>

When I initially set the ItemsSource, the ListBox (which is not visible at the time) gets its items set. However, if I go view the ListBox, updates seem to stop at that point.

當我最初設置ItemsSource時,ListBox(當時不可見)會設置它的項。

I can then remove an item from the m_VariableList collection, and it does not disappear from the ListBox. Likewise, if I add one, it doesn't appear.

然后我可以從m_VariableList集合中刪除一個項,它不會從列表框中消失。同樣,如果我加上一個,它就不會出現。

What gives?

到底發生了什么事?

2 个解决方案

#1


18  

Is your m_VariableList implementing INotifyCollectionChanged? If it's not an ObservableCollection, then changes to it's contents will not automatically be reflected in the UI.

你的m_VariableList實現inotifycollection更改了嗎?如果它不是一個觀察匯總,那么對其內容的更改不會自動地反映在UI中。

#2


8  

The problem is not in the XAML that you have provided. I used the same XAML successfully in a test application; however, I was able to replicate the issue you are experiencing by re-instantiating the m_VariableList variable.

問題不在你提供的XAML中。我在測試應用程序中成功地使用了相同的XAML;但是,我可以通過重新實例化m_VariableList變量來復制您正在經歷的問題。

When the m_VariableList is given a new instance, or pointed to a new object, it is not reflected in the ListBox because the control has its own reference to the data. This may not be the cause of your problem, but I'd recommend looking over your code-behind to ensure that the variable is not getting re-instantiated.

當m_VariableList獲得一個新實例或指向一個新對象時,它不會在列表框中反映出來,因為該控件對數據有自己的引用。這可能不是問題的原因,但我建議檢查代碼隱藏,以確保變量不會被重新實例化。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2009/06/16/72ff5231cd81f126c5f0af95d7a91d99.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com