tags:

views:

52

answers:

2

I created two custom ComboBox controls, both inherit from the default ComboBox control.

public BlueComboBox : ComboBox {}
public WhiteComboBox : ComboBox {}

BlueComboBox contains a template and is styled properly and works perfectly. WhiteComboBox is a bit more complex. It contains a template consisting of a TextBlock and a BlueComboBox.

Incorrect snippet, but you should get the idea:

<ControlTemplate>
  <Grid>
    <TextBlock />
    <BlueComboBox />
  </Grid>
</ControlTemplate>

Here's the tricky part: since WhiteComboBox is a ComboBox control I would like to bind the items in BlueComboBox to the ones set in my WhiteComboBox control.

<WhiteComboBox>
  <ComboBoxItem Content="Foo" />
  <ComboBoxItem Content="Bar" />
</WhiteComboBox>

I tried binding the ItemSource of the BlueComboBox entity used in the template to the ItemsSource proprety of my WhiteComboBox, but that did not seem to work:

<ControlTemplate>
  <Grid>
    <TextBlock />
    <BlueComboBox ItemsSource="{TemplateBinding ItemsSource}" />
  </Grid>
</ControlTemplate>

What's the proper way to use the items defined in my WhiteComboBox instance to the BlueComboBox instance? Am I using the ItemsSource property incorrectly, or should I use another one?

Any help would be greatly appreciated.

A: 

You could try using a RelativeSource binding:

<ControlTemplate>
  <Grid>
    <TextBlock />
    <BlueComboBox ItemSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type ComboBox}}}, Path=Items}" />
  </Grid>
</ControlTemplate>

As an aside, usual practice in WPF is to use Styles to alter visual aspects of controls, rather than creating derived types.

Samuel Jack
Thank you, that did the trick.I am using styles, but each ComboBox type contains extra DependencyProperties and since I'm fairly new at this creating my own custom controls based upon them was the easiest way to do it.
tyfius
A: 

There's a second problem I'm experiencing with this.

I styled the ItemContainerStyle property and set a SystemColors.HighlightBrushKey value. When I use the BlueComboBox on its own this works perfectly when I hover over an item. However, when I embed my BlueComboBox in my new control this doesn't work anymore when I use the ItemsSource template binding. When I directly add some ComboBoxItems in my control template to the BlueComboBox item it works again. It also works when I explicitly click on an item.

I tried setting the ItemContainerStyle property on my WhiteComboBox control template and passing it down, but none of the things I tried seems to do the trick.

tyfius