开发者

WPF Combobox selectedvalue not updating when update selecteditem

开发者 https://www.devze.com 2023-03-30 05:07 出处:网络
There is Observable collection which bind to combobox. public ObservableCollection<AnyType> AnyTemplates { get; set; }

There is Observable collection which bind to combobox.

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

And combobox which bind to this collection:

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

First collection is empty. Then when i add new value in collection, checkBox selectedItem change to this value. If I cha开发者_如何学Gonge Name property in collection Item, combobox selectedItem is changed(I see what DisplayMemberPath change to new value), but Selected value not changed until i manualy choose this item again. The Name property collection element call PropertyChanged event. Why this did not work.

Summary: when I change NameProperty in comboxo SelectedItem programicaly, combobox SelectedItem is changed, but SelectedValue not update until i manualy change it in combobox again.


Try using the ItemStyle Container for the ComboBox so it looks like this:

<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>

Also, make sure that you have done everything with NotifyPropertyChanged and set up the DataContext. Another thing to not is to make sure you set up the initial values in the view model on load first and then just the SelectedItem will change.

0

精彩评论

暂无评论...
验证码 换一张
取 消