WPF MVVM ComboBox SelectedValue 在导航离开时被清除

Bru*_*o V 7 c# wpf xaml combobox mvvm

我遇到了ComboBox最终能够解决的 WPF问题。但问题的原因尚不清楚。

使用时出现的问题ComboBox,其中ItemsSource被引用不同的DataContextSelectedValue。执行此操作并导航离开时,该SelectedValue属性设置为null。由于某些属性在更改时包含逻辑(当字段 A 更改时,也会更改字段 B),因此某些逻辑执行不正确。

<ComboBox x:Name="Sector" 
                     ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.SectorList}" 
                     SelectedValuePath="Id" 
                     SelectedValue="{Binding SectorId, Mode=TwoWay}" />
Run Code Online (Sandbox Code Playgroud)

我发现了几个类似的问题(这可能是最接近的:https : //stackoverflow.com/a/5033924/3357566),但没有一个解决了我的问题。许多修复与加载顺序有关ItemsSourceSelectedValue因此这使我走上了正确的轨道。

我没有DataContextUserControlthrough RelativeSources中获取 ,而是遍历了 ViewModels 的父级以找到 SectorList,因此 XAML 现在如下所示(注意Root属性):

<ComboBox x:Name="Sector" 
                     ItemsSource="{Binding Root.SectorList}" 
                     SelectedValuePath="Id" 
                     SelectedValue="{Binding SectorId, Mode=TwoWay}" />
Run Code Online (Sandbox Code Playgroud)

有人可以解释一下为什么后一个代码在离开页面时没有清除 SelectedValue 而第一个代码会清除吗?

编辑

澄清 的结构ViewModels

  • 客户入口视图模型
    • SectorList(以及其他ComboBoxes仅在 中使用的要填充的列表CustomerEntryViewModel
    • CustomerViewModel(单独ViewModel在其他模块中重用)
      • 姓名
      • 地址
      • 扇区号
      • ...

DataContext视图的是CustomerEntryViewModel,但它的第一个容器具有DataContext集到CustomerViewModel。因此,要获得的SectorList从这里,我要么去DataContextUserControl通过RelativeSource(第一个例子)或我要遍历我的ViewModel父母顶端(第二个例子)。

问题仍然是为什么两个示例之间的行为不同。