I want to create a datatemplate (in code, but thats not the point) which allows me to click on an item and set its bool value. What I managed to create was a combination of CheckBox and TextBlock, which is colored depending on the bool value.
So far so good… But how can I tell WPF: If anybody clicks on the TextBlock, change the bool value. (removing the need for the ugly checkbox)
Code so far and working:
var dT = new DataTemplate(typeof(DirectoryWrapper));
var stackPanel = new FrameworkElementFactory(typeof(StackPanel));
var style = new Style(typeof(TextBlock));
var t = new DataTrigger() {Binding = new Binding(DirectoryWrapper.PropString(x => x.IsSelected)), Value = true};
t.Setters.Add(new Setter() { Property = TextBox.ForegroundProperty, Value = new SolidColorBrush(Colors.Green) });
style.Triggers.Add(t);
var box = new FrameworkElementFactory(typeof(CheckBox));
box.SetBinding(CheckBox.IsCheckedProperty, new Binding(DirectoryWrapper.PropString(x => x.IsSelected)));
stackPanel.AppendChild(box);
var entry = new FrameworkElementFactory(typeof(TextBlock));
entry.SetBinding(TextBlock.TextProperty, new Binding(DirectoryWrapper.PropString(x => x.Path)));
entry.SetValue(TextBox.StyleProperty, style);
stackPanel.AppendChild(entry);
dT.VisualTree = stackPanel;
return dT;
This is trivial in WPF: Just template your CheckBox to look like a TextBlock:
This might be extended by adding a
Borderaround theTextBlockor anything else you like to give it more pizzaz.The reason you want to use
CheckBoxinstead ofToggleButtonis thatCheckBoxhas additional keyboard suport, plus accessibilty support to map into the checkbox paradigm on the accessibilty device.ToggleButtondoesn’t give you these features.