【问题标题】:WPF Combobox selectedvalue not updating when update selecteditem更新选定项时 WPF 组合框选定值未更新
【发布时间】:2011-08-23 09:31:04
【问题描述】:

有绑定到组合框的 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 不会更新,直到我再次在组合框中手动更改它。

【问题讨论】:

    标签: wpf binding combobox selectedvalue


    【解决方案1】:

    尝试为 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 会改变。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-06
      • 1970-01-01
      相关资源
      最近更新 更多