0

有绑定到组合框的 Observable 集合。

public ObservableCollection<AnyType> AnyTemplates { get; set; }

以及绑定到此集合的组合框:

<ComboBox Name="cmbKeyA" 
          Width="100" 
          SelectedValue="{Binding Path=KeyAName}"
          ItemsSource="{Binding Path=DataContext.KeyTemplates, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" 
          DisplayMemberPath="Name" 
          SelectedValuePath="Name"/>

第一个集合是空的。然后,当我在集合中添加新值时,checkBox selectedItem 更改为该值。如果我更改集合 Item 中的 Name 属性,则组合框 selectedItem 会更改(我看到 DisplayMemberPath 更改为新值),但 Selected 值不会更改,直到我再次手动选择此项目。Name 属性集合元素调用 PropertyChanged 事件。为什么这不起作用。

摘要:当我以编程方式更改组合框 SelectedItem 中的 NameProperty 时,组合框 SelectedItem 已更改,但 SelectedValue 不会更新,直到我再次在组合框中手动更改它。

4

1 回答 1

0

尝试对 ComboBox 使用 ItemStyle Container,使其看起来像这样:

<ComboBox Name="cmbKeyA" 
          Width="100" 
          SelectedValue="{Binding Path=KeyAName}"                           
          ItemsSource="{Binding AnyTemplates}"                            
          DisplayMemberPath="Name" 
          SelectedValuePath="Name">
    <ComboBox.ItemContainerStyle>
        <Style TargetType="{x:Type ComboBoxItem}">
            <Setter Property="IsSelected" Value="{Binding Path=IsCurrent, Mode=TwoWay}"/>
        </Style>
    </ComboBox.ItemContainerStyle>
</ComboBox>

此外,请确保您已使用 NotifyPropertyChanged 完成所有操作并设置了 DataContext。另一件事是确保您在加载时首先在视图模型中设置初始值,然后只有 SelectedItem 会改变。

于 2012-08-02T11:05:50.400 回答