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 perf开发者_JS百科ectly.
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
property 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.
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.
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.
精彩评论