【发布时间】:2021-02-24 18:15:02
【问题描述】:
我在 WPF 中有一个 ComboBox。 ComboBox 位于网格内部,并且网格的 DataContext 绑定到 ListView 的 SelectedItem。 ComboBox 的 ItemsSource 设置为 StaticResource,位于窗口资源中。 ItemsSource 不会改变。我尝试同时使用 SelectedValue 和 SelectedItem 但它们都对我造成了同样的问题。问题是,当 ListView 的 SelectedItem 发生更改时,ComboBox 实际上是在将 PREVIOUSLY 选定项的属性值设置为 NEWLY 选定项的属性值。显然我做错了什么,因为我过去曾多次使用组合框而没有这个问题。我搜遍了网络,找不到答案。我发现的最接近、最相似的问题是:Strange behaviour (or bug?) with ComboBox in WPF when changing DataContext and having bound ItemsSource and SelectedItem
但它似乎没有解决方案。 cmets 中列出的解决方案对我不起作用。
我为 ListView 和 ComboBox 创建了 SelectionChanged 事件,并在每个事件和正在设置的属性处设置了断点。该属性实际上是在触发其中任何一个之前设置的。因此,即使我想创建一些 hack 解决方法,我也做不到。
郑重声明,ComboBox 功能运行良好。当在 ListView 中选择一个对象时,我可以看到 Template name 属性,正如我应该看到的那样,并且项目列表是正确的。如果我手动更改所选项目,则该属性将更改为新项目,就像它应该的那样。问题是,当我更改 ListView 中的选定项时,新选定对象的“模板”属性被设置为先前选定对象的“模板”属性。所以组合框的变化是最先发生的。
ListView 和 ComboBox 的 xaml 如下。
<ListView x:Name="my_ListBox" FlowDirection="RightToLeft"
Margin="5" Grid.RowSpan="2" SelectedIndex="0"
ItemsSource="{Binding Source={StaticResource myList}}"
DisplayMemberPath="Name"
SelectionChanged="my_ListBox_SelectionChanged"/>
<Grid DataContext="{Binding ElementName=my_ListBox, Path=SelectedItem}">
<ComboBox Name="comboBox_myTemplate"
ItemsSource="{Binding Source={StaticResource myTemplatesList}}"
SelectedValue="{Binding Template}"
SelectionChanged="comboBox_myTemplate_SelectionChanged"
DisplayMemberPath="Name" FontSize="20" Margin="5"/>
</Grid>
【问题讨论】: