WPF ComboBox SelectedItem 在 TabControl 开关上设置为 Null [英] WPF ComboBox SelectedItem Set to Null on TabControl Switch
问题描述
我的 WPF 应用程序有一个简单的问题,让我把头撞在桌子上.我有一个 TabControl,其中每个 TabItem 都是使用类似于以下的 DataTemplate 为 ViewModel 生成的视图:
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 包含一个组合框:
FooView contains a ComboBox:
<ComboBox ItemsSource="{Binding Path=BarList}" DisplayMemberPath="Name" SelectedItem="{Binding Path=SelectedBar}"/>
和 FooViewModel 包含一个简单的属性: public Bar SelectedBar { get;放;}
.我的问题是,当我为 ComboBox 设置值时,更改到另一个选项卡,然后再改回来,ComboBox 再次为空.如果我在我的属性的 setter 上设置断点,当我切换到另一个选项卡时,我会看到该属性被分配给 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?
setter 断点处的调用堆栈仅显示 [外部代码] - 那里没有提示.
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!