in my WPF application I have a lot of DockPanels that consist of a checkbox and a label. I would like to have the app handle the mousedown event of the DockPanel as if the checkbox was clicked, i.e. the user doesn't have to click the checkbox specifically; he can also click the label to check/uncheck the checkbox. I have added an Eventhandler "DockPanel_MouseDown", which simply flips the IsChecked property of the checkbox, and this works. My problem is that I have a lot of those DockPanels and I don't want to give each checkbox and each dockpanel a name and write hundreds of eventhandlers that basically do the same thing. Is there a way to put that behavior in a style or a template? C
Asked
Active
Viewed 371 times
2 Answers
3
Why are using separate label to check and uncheck the checkbox?
<StackPanel>
<CheckBox IsChecked="{Binding IsChecked, ElementName=checkbox}" Content="Hello">
<CheckBox.Template>
<ControlTemplate TargetType="CheckBox">
<ContentPresenter/>
</ControlTemplate>
</CheckBox.Template>
</CheckBox>
<CheckBox x:Name="checkbox" Content="Normal checkbox"/>
</StackPanel>

Community
- 1
- 1

sriman reddy
- 763
- 8
- 22
-
Haha. It has in fact never occured to me that a combobox might have a suitable attribute to achieve exactly this behavior. Thanks a buncht! – Curtis Apr 09 '15 at 14:53
1
You don't really have to name them or an event handler for each dockpanel.
You could use the same event handler for all of those dockpanels, and at your eventhandler you can use the sender instead of the name.
<StackPanel Orientation="Vertical">
<DockPanel Tag="false" MouseUp="DockPanel_OnMouseUp">
<CheckBox DockPanel.Dock="Left" IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DockPanel}}, Path=Tag, Mode=TwoWay}"/>
<Label DockPanel.Dock="Right" Content="CheckBox1" />
</DockPanel>
<DockPanel Tag="false" MouseUp="DockPanel_OnMouseUp">
<CheckBox DockPanel.Dock="Left" IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DockPanel}}, Path=Tag, Mode=TwoWay}"/>
<Label DockPanel.Dock="Right" Content="CheckBox1"/>
</DockPanel>
<DockPanel Tag="false" MouseUp="DockPanel_OnMouseUp">
<CheckBox DockPanel.Dock="Left" IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DockPanel}}, Path=Tag, Mode=TwoWay}"/>
<Label DockPanel.Dock="Right" Content="CheckBox1"/>
</DockPanel>
<DockPanel Tag="false" MouseUp="DockPanel_OnMouseUp">
<CheckBox DockPanel.Dock="Left" IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DockPanel}}, Path=Tag, Mode=TwoWay}"/>
<Label DockPanel.Dock="Right" Content="CheckBox1"/>
</DockPanel>
</StackPanel>
Code:
private void DockPanel_OnMouseUp(object sender, MouseButtonEventArgs e)
{
var dockPanel = (DockPanel) sender;
dockPanel.Tag = !dockPanel.Tag.ToString().ToLower().Equals("true");
}

Nawed Nabi Zada
- 2,819
- 5
- 29
- 40