简体   繁体   English

WPF ListBox 未随 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 设置中应该是简单的双向数据绑定,但是列表框(目标)不会随着集合的变化而更新。

I'm setting this ItemsSource of the ListBox programmatically:我正在以编程方式设置 ListBox 的 ItemsSource:

lstVariable_Selected.ItemsSource = m_VariableList;

And the ListBox is declared as follows: ListBox 声明如下:

<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.当我最初设置 ItemsSource 时,ListBox(当时不可见)设置了它的项目。 However, if I go view the ListBox, updates seem to stop at that point.但是,如果我 go 查看列表框,更新似乎会在此时停止。

I can then remove an item from the m_VariableList collection, and it does not disappear from the ListBox.然后我可以从 m_VariableList 集合中删除一个项目,它不会从 ListBox 中消失。 Likewise, if I add one, it doesn't appear.同样,如果我添加一个,它也不会出现。

What gives?是什么赋予了?

Is your m_VariableList implementing INotifyCollectionChanged ?您的 m_VariableList 是否正在实施INotifyCollectionChanged If it's not an ObservableCollection, then changes to it's contents will not automatically be reflected in the UI.如果它不是 ObservableCollection,则对其内容的更改不会自动反映在 UI 中。

The problem is not in the XAML that you have provided.问题不在您提供的 XAML 中。 I used the same XAML successfully in a test application;我在测试应用程序中成功使用了相同的 XAML; however, I was able to replicate the issue you are experiencing by re-instantiating the m_VariableList variable.但是,我能够通过重新实例化 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.当 m_VariableList 被赋予一个新实例,或指向一个新的 object 时,它不会反映在 ListBox 中,因为控件有自己的数据引用。 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.这可能不是你的问题的原因,但我建议你查看你的代码隐藏以确保变量没有被重新实例化。

i got stuck for more than hour and then simple logic solved this problem just set itemsource to clear list and then set source u need again我被困了一个多小时,然后简单的逻辑解决了这个问题,只需将 itemsource 设置为清除列表,然后再次设置你需要的源

lstVariable_Selected.ItemsSource = new List<Object>();
lstVariable_Selected.ItemsSource = m_VariableList;

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

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