PROBLEM:

I had to build a view which takes list of answers from model and dynamically create checkboxes for each. Also, these answers were long and hence, need to be wrapped and aligned.

SOLUTION:

Checkbox had custom attributes and behaviors. Hence, style was created for the checkbox.

As in style, there are two different image for checkbox for active and inactive state. In the ContentPresenter.ContentTemplate, the textblock displays the checkbox text. TextWrapping = “wrap” sets the text to be wrapped. In the ContentPresenter, note RecognizesAccessKey=”True”. This is required if you need the special characters like underscore to be recognised and displayed properly.

Now, Lets look at the implemented view xaml.

Grid defines the restricted width and height of the view.

StackPanel  allows the controls within to be stacked.

TextBlock displays the question or header text.

Inner StackPanel seperates the TextBlock from the list of checkboxes which it hosts via ListBox. 

CheckBox is set as the DataTemplate for the ListBox. With ItemsSource set to “{Binding Answers}” takes a collection of answer text from model and binds to generate list of checkboxes at runtime.

WrapPanel is defined as the ListBoxItemTemplate. This allows the text to be wrapped.

That is it… Pretty cool..

To learn more about DataTemplate and Styles in WPF, Check http://msdn.microsoft.com/en-us/library/ms745683.aspx

Happy coding….

WPF: Wrap text in checkbox
Tagged on:

Leave a Reply

Your email address will not be published. Required fields are marked *