Search code examples
wpfcheckboxwpf-controlsuielementcontentpresenter

WPF Checkbox won't display a UIElement as its content


I'm working with a custom checkbox, and I'm trying to set the content to a WPF Viewbox. The problem is, simply, nothing is displayed. The checkbox appears and works, but it has no content. This is sample code (not the actual code) of what I'm trying to do.

MyCheckbox myCheckbox = new MyCheckbox();

Viewbox viewbox = new Viewbox();
viewbox.Height = 20;
viewbox.Width = 20;

Label label = new Label();
label.Content = "Test";

viewbox.Child = label;
myCheckbox.Content = viewbox;

The Content property accepts an object, so there is no problem setting it to a Viewbox, and the ContentPresenter can display a UIElement. I thought perhaps the ContentPresenter couldn't display the Label contained in the Viewbox, so I created some test code, setting the checkbox's content to a simple rectange. Still nothing.

Any thoughts or ideas? Thanks for your help!

Oh - Setting the Content property to a string works.


Solution

  • You may need to post the relevant XAML of your custom CheckBox. Check the ControlTemplate has a ContentPresenter and that if you have a ContentTemplate that it is not interfering. You can see an example template here.

    If you just want to change the look of a CheckBox, you can re-template the standard CheckBox without writing a custom class.