Wednesday, December 3, 2014

Changing SelectedIndex on one combo box triggers SelectionChanged event on a different combo box

WPF 4.0

I just spent ten minutes trying to figure out why changing the selected index on one combo box triggers the SelectionChanged event on a different combo box.

The two combo boxes are defined thus...

<ComboBox Name="SearchTransactionTypeCombo" Binding="{StaticResource TransactionTypes}"  SelectedValuePath="GLTransactionTypeID" DisplayMemberPath="Code" Style="{StaticResource DropDownList}"></ComboBox>

<ComboBox Name="EditTransactionTypeCombo" Binding="{StaticResource TransactionTypes}"  SelectedValuePath="GLTransactionTypeID" DisplayMemberPath="Code" Style="{StaticResource DropDownList}" SelectionChanged="TransactionTypeCombo_SelectionChanged" ></ComboBox>

When I change SearchTransactionTypeCombo.SelectedIndex in code the TransactionTypeCombo_SelectionChanged event is raised and the sender object is EditTransactionTypeCombo. How can this be?

Eventually I thought to look at the DropDownList style in case I had declared an EventSetter in there. Here is the style definition...

    <Style TargetType="{x:Type ComboBox}" x:Key="DropDownList" BasedOn="{StaticResource {x:Type ComboBox}}">
        <Setter Property="IsEditable" Value="False"/>
        <Setter Property="IsSynchronizedWithCurrentItem" Value="True"/>
        <Setter Property="HorizontalAlignment" Value="Stretch"/>
    </Style>

The problem is the IsSynchronizedWithCurrentItem property. Both combo boxes are bound to the same resource. When I changed SearchTransactionTypeCombo.SelectedIndex the current row of the collection was changed, which in turn changed the selected index of EditTransactionTypeCombo which raised the TransactionTypeCombo_SelectionChanged event.

As synchronization is not really needed, I removed it from the style. Alternatively I could have bound to different resources, or overridden synchronization in the control definitions.

No comments:

Post a Comment