问题描述
我的WPF应用程序中有一个简单的问题,使我无法自拔.我有一个TabControl,其中每个TabItem都是使用类似于以下内容的DataTemplate为ViewModel生成的View:
I've got a simple problem in my WPF application which has me banging my head on the table. I have a TabControl, where every TabItem is a View generated for a ViewModel using a DataTemplate similar to this:
<DataTemplate DataType="{x:Type vm:FooViewModel}">
<vw:FooView/>
</DataTemplate>
FooView包含一个ComboBox:
FooView contains a ComboBox:
<ComboBox ItemsSource="{Binding Path=BarList}" DisplayMemberPath="Name" SelectedItem="{Binding Path=SelectedBar}"/>
和FooViewModel包含一个简单的属性:public Bar SelectedBar { get; set; }
.我的问题是,当我为ComboBox设置值时,切换到另一个选项卡,然后再改回来,ComboBox再次为空.如果我在属性的设置器上设置断点,则当我切换到另一个选项卡时,会看到该属性已分配给null
.
and FooViewModel contains a simple Property: public Bar SelectedBar { get; set; }
. My problem is that when I set the value for my ComboBox, change to another tab, then change back, the ComboBox is empty again. If I set a breakpoint on the setter for my property, I see that the property is assigned to null
when I switch to another tab.
据我了解,切换选项卡时,会将其从VisualTree中删除-但是为什么将ViewModel的属性设置为null
?这使我很难保持持久状态,并且检查value != null
似乎不是正确的解决方案.任何人都可以在这种情况下摆脱困境吗?
From what I understand, when a tab is switched, it is removed from the VisualTree - but why is it setting my ViewModel's property to null
? This is making it very difficult for me to hold persistent state, and checking value != null
does not seem like the right solution. Can anyone shed some like on this situation?
在设置器断点处的调用堆栈仅显示[外部代码]-那里没有提示.
The call stack at the setter breakpoint only shows [External Code] - no hints there.
推荐答案
我们只是遇到了同样的问题.我们找到了描述问题的博客条目.看来这是WPF中的错误,并且有一种解决方法:在ItemsSource绑定之前指定之前的SelectedItem绑定,问题应该消失了.
we just ran into the same problem. We found a blog entry describing the problem. It looks like it is a bug in WPF and there is a workaround:Specify the SelectedItem binding before the ItemsSource binding and the problem should be gone.
博客文章的链接:
http://www.metanous.be/pharcyde/post/Bug-in-WPF-combobox-databinding.aspx
这篇关于WPF ComboBox SelectedItem在TabControl开关上设置为Null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!