This blog has, IMO, some great resources. Unfortunately, some of those resources are becoming less relevant. I'm still blogging, learning tech and helping others...please find me at my new home on http://www.jameschambers.com/.

Friday, May 29, 2009

Setting Template Properties on a ComboBox

In WPF the ComboBox is a tricky little control that doesn’t easily allow you to adjust properties on the inner controls of the template.

If you try to override the template you will find very quickly that you might get into the trap of having to override the entire visual tree, thus having to recreate the entire control from scratch.

Below is a way to get at the controls from the template, per my answer to a question on the MSDN forums. In particular, the question was about getting the TextBox (actually, in his case, the TextBlock) to have underlined text.

cboTest.Loaded += delegate {
if (cboTest.IsEditable)
{
TextBox textEditPart = ((TextBox)cboTest.Template.FindName("PART_EditableTextBox", cboTest));
textEditPart.TextDecorations = TextDecorations.Underline;
}
else
{
Grid layoutGrid = VisualTreeHelper.GetChild(cboTest, 0) as Grid;
ContentPresenter nonEditPart = VisualTreeHelper.GetChild(layoutGrid, 2) as ContentPresenter;
TextBlock textNonEditPart = VisualTreeHelper.GetChild(nonEditPart, 0) as TextBlock;
textNonEditPart.TextDecorations = TextDecorations.Underline;
}
};


Man, code on this blog is hard to read.  :o/



Okay, so what’s going on is basically that we have to hunt down the TextBox or TextBlock, depending on if the ComboBox is set to be editable or not.



After finding that, we simply set the TextDecorations property to the pre-defined Underline text decoration. Paste that code into your code-behind after InitializeComponent and you should be good to go.



I found the elements in question by using Mole.  When we have an object that is named, we can use the Template.FindName to get the control loaded up locally.  When we don’t, we’ll need to use VisualTreeHelper’s static GetChild method to dig.



Side note: this won’t work in a big way if you’ve otherwise edited your template.  This is fairly hard-coded against the VisualTree provided by ComboBox out-of-the-box (but could easily be adapted to be a little less tightly coupled).

No comments:

Post a Comment