Question

We've created a custom ComboBox control that has a button to clear the ComboBox's selection:

<Style TargetType="{x:Type local:ClearableComboBox}">
    <Setter Property="SelectedItem" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:ClearableComboBox}">
                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
                    <DockPanel>
                        <Button Name="btnClear" DockPanel.Dock="Right" ToolTip="Clear" Width="20">
                            <Image Source="pack://application:,,,/img/icons/silk/cross.png" Stretch="None" />
                        </Button>
                        <ComboBox Name="comboBox"
                                  ItemsSource="{TemplateBinding ItemsSource}"
                                  SelectedItem="{TemplateBinding SelectedItem}"
                                  DisplayMemberPath="{TemplateBinding DisplayMemberPath}" />
                    </DockPanel>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

The binding for ItemsSource works fine, however the binding for SelectedItem does not. After searching on Google, I found the solution to the problem here. Specifically, changing the SelectedItem binding to

SelectedItem="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=SelectedItem}"

makes it work as expected.

Why doesn't the original TemplateBinding on SelectedItem work, while the TemplateBinding for ItemsSource worked just fine?

Was it helpful?

Solution

One of the differences (which, as I think, is the main problem in your case) is that TemplateBinding is always OneWay, whereas Binding chooses to be OneWay or TwoWay depending on the property. (More details here.)

You may find other differences at this discussion.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top